Original source pages and recordings require authorized access. The full article text here is public.
Web developers already run agents against real repos, dev servers, browser panes, and local QA loops; the Ralph Loop helps those agents keep working toward a bounded goal instead of stopping after one polite assistant turn. It is especially useful for web tasks where success is observable only after code, tests, logs, and browser behavior line up.
Current Codex Stop contract
A Ralph Loop must use the Stop event’s continuation decision, not a general hook-output flag. In the official Stop contract, a synchronous hook that exits successfully requests another pass by writing JSON such as:
{"decision":"block","reason":"Original goal: prove the checkout flow. Browser proof is still missing. Run the bounded checkout verification, save the observed result, and re-check the completion criteria."}
For Stop, decision: "block" does not reject the work: Codex creates a continuation prompt from reason, acting as a new user prompt. The reason should identify the original goal, the missing evidence, and the next bounded action. {"continue":true} alone does not request another turn. systemMessage and suppressOutput are not substitutes for a Stop continuation decision.
When completion is verified, the iteration cap is reached, or a blocker requires human review, the hook can explicitly end continuation:
{"continue":false,"stopReason":"Iteration cap reached; browser proof remains missing. Stop for review, not success."}
Use a truthful reason for the actual terminal state. A cap or blocker is not evidence that the goal succeeded. Returning JSON without a blocking decision leaves this hook with no continuation request; continue: false is stronger and takes precedence over continuation decisions from other matching Stop hooks.
- On exit code
0, Stop output must be valid JSON; plain text on stdout is invalid. An alternative continuation signal is exit code2with the reason on stderr. stop_hook_activereports whether Stop already continued this turn. It is a boolean, not a persistent iteration counter. Maintain an explicit run-scoped cap and check completion evidence on every invocation.- Keep the Stop hook synchronous and fast. It should inspect evidence and decide, not perform the slow browser/API work itself. Background hooks cannot enforce turn continuation.
- Review and trust the exact hook definition through
/hooks; installing a plugin is not the same as trusting its hooks. Recheck after hook definitions change. - Plugin configuration and supported fields are version-specific. The historical reference below is retained for context, but use the event-specific contract above for an operational Stop loop.
Copy-paste workflow
When to use: When you want an agent to pursue a goal across many turns without manual nudging. A Stop hook re-checks the original task when the agent tries to stop and pushes it to keep working until a clear completion condition is met.
Copy-paste prompt
You are my coding agent. Build a minimal "Ralph Loop" Codex plugin: a Stop hook that re-points the agent at the original goal and requests another pass until a completion condition or hard cap is reached. This workflow uses UserPromptSubmit, PreToolUse (Tool Use), and Stop as its three teaching landmarks; they are not the complete current event list. The Ralph Loop is a STOP hook. Use the Current Codex Stop contract above.
1. First enable hooks + plugins in ~/.codex/config.toml, then restart Codex:
[features]
hooks = true
plugins = true
plugin_hooks = true
2. Scaffold the real plugin layout:
my-plugin/
.codex-plugin/plugin.json # manifest, with "hooks": "hooks/hooks.json"
hooks/hooks.json # wires a Stop hook command
hooks/hook.py # the Stop hook script
3. In hooks/hooks.json, wire the Stop event to run the hook script, e.g.:
{
"hooks": {
"Stop": [
{ "hooks": [ { "type": "command", "command": "python3 \"${CODEX_PLUGIN_ROOT}/hooks/hook.py\"", "timeout": 5 } ] }
]
}
}
4. hook.py reads the Stop event JSON on stdin and writes EXACTLY ONE JSON line. When the goal is incomplete and the hard cap has not been reached, emit {"decision":"block","reason":"<original goal, missing evidence, and next bounded action>"}. When completion is verified, the cap is reached, or a blocker needs review, emit {"continue":false,"stopReason":"<truthful terminal reason>"}. Never report cap exhaustion as success. Do not rely on continue:true or suppressOutput to request another turn. Keep the hook synchronous, fast, and boring.
CRITICAL guardrail: the loop MUST have a hard completion condition — an iteration cap or an explicit target state — enforced by the hook, not just suggested in a prompt. Without it you get a runaway loop.
How it works
- UserPromptSubmit, tool-use events, and Stop are the lifecycle landmarks used here; current Codex supports additional events. The Ralph Loop uses Stop.
- The source plugin examples enable
hooks,plugins, andplugin_hooksin~/.codex/config.tomland restart Codex. Treat these flags as version-specific setup, and review/trust the installed hook definitions through/hooks. - The real plugin layout is
.codex-plugin/plugin.json(manifest) +hooks/hooks.json(wiring) + a hook script;${CODEX_PLUGIN_ROOT}resolves the plugin dir. - The hook reads event JSON and emits a Stop-specific decision:
{"decision":"block","reason":"<next bounded action>"}requests continuation.{"continue":true}alone does not. The harness acts on the decision and uses the reason as a new continuation prompt. - CRITICAL: require an explicit completion condition (iteration cap or target state) or you get runaway loops.
- Reference: Codex Hooks docs, Better Plugins.
Reusable skill
Install as ~/.agents/skills/ralph-loop-hook/SKILL.md, then restart Codex.
---
name: ralph-loop-hook
description: Trigger when the user wants an agent to keep pursuing a goal across turns via a Codex Stop hook (the Ralph Loop). Do NOT use without a clear completion condition — unbounded loops waste tokens and run tools too long.
---
# Ralph Loop hook
Scaffold a Ralph Loop: a Codex Stop hook that, when the agent tries to stop, re-points it at the original goal and requests another pass until a completion condition or hard cap is reached — enforced by the harness, not merely suggested in a prompt. UserPromptSubmit, PreToolUse (Tool Use), and Stop are the three teaching landmarks for this workflow, not the exhaustive current event list. The Ralph Loop uses Stop.
## Prerequisite
Enable hooks + plugins in `~/.codex/config.toml`, then restart Codex:
```toml
[features]
hooks = true
plugins = true
plugin_hooks = true
```
`/plugins` confirms install; `/hooks` reviews/trusts bundled hooks.
## Steps
1. Scaffold the real plugin layout:
```
my-plugin/
.codex-plugin/plugin.json # manifest, with "hooks": "hooks/hooks.json"
hooks/hooks.json # hook wiring
hooks/hook.py # the Stop hook script
```
2. Wire the Stop event in `hooks/hooks.json`:
```json
{
"hooks": {
"Stop": [
{ "hooks": [ { "type": "command", "command": "python3 \"${CODEX_PLUGIN_ROOT}/hooks/hook.py\"", "timeout": 5 } ] }
]
}
}
```
3. `hooks/hook.py` reads the Stop event JSON on stdin and writes EXACTLY ONE JSON line. While the goal is incomplete and below its hard cap, emit `{"decision":"block","reason":"<original goal, missing evidence, next bounded action>"}`. On verified completion, cap exhaustion, or a blocker requiring review, emit `{"continue":false,"stopReason":"<truthful terminal reason>"}`. Cap exhaustion is not success. `continue:true` alone does not request another turn; do not use `suppressOutput` as a continuation mechanism. Keep the hook synchronous and fast; let the resumed agent or a separate worker perform slow work, then inspect its evidence on the next Stop invocation.
## Guardrails
- MANDATORY: a hard completion condition (iteration cap or target state) enforced by the hook. Without it you get a runaway loop that wastes tokens and runs tools too long.
Scenarios
Keep fixing a checkout bug until browser proof passes
Role: As a senior frontend engineer responsible for a Next.js checkout flow
A local Next.js app has a flaky checkout path: the agent often fixes one validation error, reports done, and stops before proving the full browser flow from cart to confirmation. The team wants a Ralph Loop plugin that keeps the agent on the original checkout goal until tests and browser evidence prove the flow works.
As a senior frontend engineer, I want a Stop hook to re-point the agent at the original checkout goal until the checkout flow passes, so that the agent does not stop after only a partial code fix.
Agent brief
Build a minimal Ralph Loop Codex plugin for this repo. Inspect the Copy-paste workflow section of this playbook and the Reusable skill section of this playbook first. Enable hooks and plugins in ~/.codex/config.toml with hooks=true, plugins=true, plugin_hooks=true, then tell me to restart Codex before testing. Scaffold ralph-loop-checkout/.codex-plugin/plugin.json, ralph-loop-checkout/hooks/hooks.json, and ralph-loop-checkout/hooks/hook.py. Wire only the Stop hook to python3 "${CODEX_PLUGIN_ROOT}/hooks/hook.py" with timeout 5. The hook must read stdin JSON and write exactly one control JSON line. Store tiny local state for the original goal and iteration count. Completion condition: stop when all of these receipts exist in .notes/ralph-loop-checkout/: passing-test.log, browser-proof.md, and final-summary.md, or when iteration_count reaches 5. Do not use suppressOutput in Stop. After scaffolding, run a local simulation command that pipes mock Stop events into hook.py and proves both paths: continue before receipts exist, allow stop after receipts exist or at the cap. Expected output: plugin files, a short README section showing install/test steps, and simulation logs saved under .notes/ralph-loop-checkout/.
Implementation references
~/.codex/config.toml
ralph-loop-checkout/.codex-plugin/plugin.json
ralph-loop-checkout/hooks/hooks.json
ralph-loop-checkout/hooks/hook.py
Browser verification
Use the app's local dev server and a browser agent or Playwright-style flow to visit the checkout route, add a test item, fill the checkout form, submit, and capture the confirmation page state. Save the route, actions, visible confirmation text, and any console errors to .notes/ralph-loop-checkout/browser-proof.md. If running inside CMUX, open or use a browser pane for the local app and keep the terminal pane visible for test output.
Definition of done
- A valid Codex plugin layout exists with .codex-plugin/plugin.json, hooks/hooks.json, and hooks/hook.py.
- hooks/hooks.json wires a Stop hook command and does not add unrelated lifecycle hooks.
- hook.py emits exactly one control JSON line per event and never emits suppressOutput for Stop.
- A hard completion condition is enforced by receipt files plus an iteration cap of 5.
- Simulation logs show the hook continues before checkout proof exists and allows stopping after proof or cap.
- .notes/ralph-loop-checkout/browser-proof.md records the browser flow, visible result, and console-error status.
Failure modes and mitigations
- Common mistake: the agent only writes a prompt that says 'keep going' instead of enforcing continuation in a Stop hook. Mitigation: require a real hooks/hooks.json Stop entry and a hook.py simulation log.
- Common mistake: the loop is unbounded and can churn on tools forever. Mitigation: enforce the iteration cap in hook state and treat missing proof after the cap as a failed receipt, not silent success.
Stop-hook guard for visual regression cleanup
Role: As a product-minded UI developer polishing a dashboard redesign
A dashboard redesign has several small layout regressions across authenticated pages. Agents keep fixing the first obvious CSS issue and stopping without checking the rest of the dashboard routes in the running app.
As a UI developer, I want a Ralph Loop to keep the agent cycling through the original dashboard acceptance criteria until browser receipts are written for each target route, so that layout cleanup is proven in the app instead of inferred from code.
Agent brief
Create a Ralph Loop plugin named ralph-loop-dashboard for dashboard visual cleanup. Start by reading the Hooks and context hygiene article, the Copy-paste workflow section of this playbook, and the Command reference section of this playbook. Use the taught lifecycle model: UserPromptSubmit, PreToolUse or Tool Use, and Stop; implement only the Stop hook for this scenario. Plugin layout must be ralph-loop-dashboard/.codex-plugin/plugin.json, ralph-loop-dashboard/hooks/hooks.json, and ralph-loop-dashboard/hooks/hook.py. Add a .notes/ralph-loop-dashboard/acceptance.md file that lists the exact dashboard routes to verify and a .notes/ralph-loop-dashboard/proofs/ directory for receipts. Completion condition: allow stop only when acceptance.md has every route marked verified with a matching proof markdown file, or when 4 Stop iterations have happened. Each continuation message should point back to the original dashboard goal and name the next missing route proof. Expected output: plugin scaffold, acceptance/proof file contract, hook simulation, and instructions for installing with codex plugin marketplace add "$PWD" then codex plugin add ralph-loop-dashboard@better-plugins only if this repo is being used as a marketplace-style plugin source.
Implementation references
.notes/ralph-loop-dashboard/acceptance.md
.notes/ralph-loop-dashboard/proofs/
codex plugin marketplace add "$PWD"
codex plugin add ralph-loop-dashboard@better-plugins
Browser verification
Use a CMUX browser pane, agent-browser-style accessibility snapshot/click/fill/evaluate workflow, or Playwright to visit each listed dashboard route on localhost. For each route, capture the route URL, viewport size, key visible labels, broken layout notes, and console errors. Write one proof file per route under .notes/ralph-loop-dashboard/proofs/ and mark the route verified in acceptance.md only after the browser check has actually run.
Definition of done
- The Stop hook can identify the next missing dashboard route proof from acceptance.md.
- The hook continues while route proofs are missing and allows stop only after all proofs exist or after 4 iterations.
- Each route has a proof markdown file with URL, viewport, visible labels, and console-error status.
- The plugin scaffold uses the real Codex plugin layout and keeps hook work fast and boring.
- The final review artifact explains which routes were checked, which files changed, and whether any proof is still missing.
Failure modes and mitigations
- Common mistake: the agent marks routes verified from source inspection alone. Mitigation: require browser proof files and reject completion when a proof file is missing.
- Common mistake: the hook tries to do browser automation itself and becomes slow or brittle. Mitigation: keep the hook limited to state checks and continuation control; put browser verification in the agent workflow and receipt files.
Prototype a safe Ralph Loop before installing it globally
Role: As a developer-tools engineer maintaining local Codex plugin experiments
The team wants to experiment with stop-hook continuation, but the Better Plugins material is prototype-stage and personally configured. Before installing anything globally, they need a toy Ralph Loop with deterministic local simulation and clear guardrails.
As a developer-tools engineer, I want a toy Ralph Loop plugin with local simulations and an explicit completion cap, so that we can learn the hook mechanics without risking a runaway agent session in a production repo.
Agent brief
Build a toy plugin named ralph-loop-toy that demonstrates the Ralph Loop without touching application code. Use only the taught plugin/hook model from lesson 07 and the existing toolkit artifacts. Read the Hooks and context hygiene article, the documented scope and caveats in this playbook, the Reusable skill section of this playbook, and the Command reference section of this playbook. Scaffold ralph-loop-toy/.codex-plugin/plugin.json, ralph-loop-toy/hooks/hooks.json, ralph-loop-toy/hooks/hook.py, and ralph-loop-toy/tests/simulate-stop-events.py. The toy goal is: create .notes/ralph-loop-toy/done.txt containing DONE. The Stop hook should continue until done.txt exists or until iteration_count reaches 3. The simulator must run three cases: no done.txt means continue, done.txt means stop, cap reached means stop with a clear failure note. Expected output: the plugin files, simulator output, and a short README that tells developers to review /plugins and /hooks after install and to restart Codex after config changes.
Implementation references
ralph-loop-toy/tests/simulate-stop-events.py
~/.codex/config.toml
/plugins
/hooks
Browser verification
Browser proof is not the right proof for this toy plugin because the goal is hook mechanics, not web-app behavior. The useful UI move is optional: if running in CMUX, open a live Markdown tracker with cmux markdown open .notes/ralph-loop-toy/tracker.md --direction right so the human can watch the simulation cases and receipts update.
Definition of done
- Toy plugin files exist in the real plugin directory layout.
- hooks/hooks.json wires the Stop event to hook.py with a short timeout.
- simulate-stop-events.py proves continue, success stop, and cap stop behavior without requiring a live Codex session.
- The README includes the required ~/.codex/config.toml feature flags and restart note.
- The implementation avoids production app edits, broad plugin behavior, and unbounded continuation.
Failure modes and mitigations
- Common mistake: installing a prototype globally before proving local behavior. Mitigation: require simulator output before any install instructions are followed.
- Common mistake: mixing in #human, Toolsmith, Gemini Video, or dashboard behavior. Mitigation: keep this scenario to exactly one technique: Stop-hook continuation.
Implementation notes
- Keep the Ralph Loop to exactly one toolkit technique: Stop-hook continuation. Browser checks, Markdown trackers, and simulation scripts are proof surfaces, not extra toolkit topics.
- The hook should be fast and boring: parse event input, inspect small local state or receipt files, emit one control JSON line, and exit.
- Use a hard completion condition every time: iteration cap, explicit target state, or both. A Stop hook without a bound is not a workshop-quality scenario.
- For web-app scenarios, require browser receipts because source inspection alone does not prove UI behavior.
- Keep receipt files local under .notes/ so developers can inspect proof without committing noisy agent scratch work.
- Do not assume browser cookies are available to an agent-browser workflow. Authenticated flows need an explicit login/setup path or a local test fixture.
- Treat Better Plugins examples as prototype reference material, not polished drop-in infrastructure.
Boundaries and caveats
- Do not introduce MCP wrappers, daemon profiles, self-improving hooks, or background-worker architectures for this topic.
- Do not present #human, Toolsmith, or Gemini Video as part of the Ralph Loop implementation; they may be references, but this workflow is about Stop-hook continuation.
- Do not rely on a prompt-only 'keep going' instruction as the implementation. The taught distinction is that the harness enforces continuation through a Stop hook.
- Do not create unbounded loops, broad permissions, or hooks that perform slow browser/API work directly.
Agent reference map
Validated lesson 07 references
Use this as the source of truth for what was taught: compaction/forking, the big three hooks, Ralph Loop, skills versus plugins, and custom grammar triggers.
Lesson 07 validation notes
Use this to avoid overclaiming or reintroducing details that were removed from the validated lesson scope.
Existing Ralph Loop prompt
Use this as the implementation-facing prompt baseline for scaffolding a minimal Stop-hook continuation plugin.
Existing Ralph Loop Codex skill
Use this as the concise reusable skill contract: trigger conditions, prerequisite config, plugin layout, Stop hook wiring, and guardrails.
Verified Better Plugins command and layout notes
Use this for the real plugin directory layout, hooks.json shape, control JSON rules, and install commands; do not invent plugin flags.
CMUX CLI notes
Use only for optional local workspace proof such as browser panes, live Markdown trackers, reading screens, or inspecting panes.
Command reference
These command shapes are version-specific. Use the installed tool’s help and the linked public repository when platform behavior differs.
Enable hooks + plugins (~/.codex/config.toml)
[features]
hooks = true
plugins = true
plugin_hooks = true
Restart Codex after installing/updating. /plugins confirms install; /hooks reviews/trusts bundled hooks.
Plugin directory layout (real)
my-plugin/
.codex-plugin/plugin.json # manifest
hooks/hooks.json # hook wiring
hooks/<entrypoint>.py|.js # hook scripts
Manifest example (plugins/gemini-video/.codex-plugin/plugin.json — real)
{
"name": "gemini-video",
"description": "Detects .mp4 paths in prompts/tool calls and summarizes them with Gemini in a detached worker.",
"version": "0.1.0",
"hooks": "hooks/hooks.json"
}
hooks.json — three selected lifecycle events from the source plugin
{
"hooks": {
"UserPromptSubmit": [
{ "hooks": [ { "type": "command", "command": "python3 \"${CODEX_PLUGIN_ROOT}/hooks/hook.py\"", "timeout": 8 } ] }
],
"PostToolUse": [
{ "matcher": "*", "hooks": [ { "type": "command", "command": "python3 \"${CODEX_PLUGIN_ROOT}/hooks/hook.py\"", "timeout": 5 } ] }
],
"Stop": [
{ "hooks": [ { "type": "command", "command": "python3 \"${CODEX_PLUGIN_ROOT}/hooks/hook.py\"", "timeout": 5 } ] }
]
}
}
(Toolsmith uses UserPromptSubmit and PreToolUse; ${PLUGIN_ROOT} / ${CODEX_PLUGIN_ROOT} resolve the plugin dir.)
Historical hook-output example
The source hook_control.py example below is preserved as a version-specific historical specimen, not as a reliable current Stop continuation implementation. Its continue: true permits normal hook processing; it does not by itself force another agent turn. Its comment about suppressOutput reflects the source implementation, not the current event-support contract.
def control_for_event(event_name: str) -> dict:
out = {"continue": True}
if event_name == "UserPromptSubmit":
out["suppressOutput"] = True # suppressOutput is ONLY valid on UserPromptSubmit
return out
# emit: sys.stdout.write(json.dumps(out, separators=(",", ":")) + "\n")
The historical source claimed that Codex rejected suppressOutput outside UserPromptSubmit. Current common output documentation lists it for several events, including Stop, as parsed but not yet implemented; support remains event-specific. Neither that field nor continue: true blocks Stop. Use decision: "block" with a reason for continuation, and keep hooks fast: parse minimal state, inspect evidence, emit valid event-specific JSON, and leave slow work outside the Stop handler.
Ralph Loop (taught concept, lesson 07/08)
A Stop hook that, when the agent tries to stop, re-points it at the original goal and continues until a completion condition is met — enforced by the harness, not merely suggested in a prompt. MUST have a hard completion condition (iteration cap / target state) to avoid runaway loops.
Install (README, real)
codex plugin marketplace add johnlindquist/better-plugins # or: codex plugin marketplace add "$PWD"
codex plugin add <name>@better-plugins
# after edits:
codex plugin remove <name>@better-plugins && codex plugin add <name>@better-plugins
Toolsmith data paths (real)
~/.codex/plugins/data/better-plugins-toolsmith/ (events/ raw JSONL, indexes/tool-index.json compact).