ralphex
CLAUDE.md1.5k starsChanged 3 months agoMITView on GitHub
Autonomous plan execution with Claude Code - Go rewrite of ralph.py. See @llms.txt for usage instructions and Claude Code integration commands. go get -u ./... does NOT update dependencies behind build tags. The e2e/ package uses //go:build e2e, so playwright-go and other e2e-only deps require a separate update:
- Reads credentials
- Installs packages
Trending
Less talk lately.about the whole repository
Who's talking about umputun/ralphex
- sshroot/ralphex-opencode“chore(deps): update Ralphex and OpenCode versions”GitHub · Oct 5, 2026
- sudosubin/agents.nix“claude-code-plugins.github.umputun.ralphex: init at 1.7.0”GitHub · Oct 4, 2026
- sudosubin/agents.nix“claude-code-marketplaces.github.umputun.ralphex: init at 1.7.0”GitHub · Oct 4, 2026
- sudosubin/agents.nix“agent-skills.github.umputun.ralphex: init at 1.7.0”GitHub · Oct 3, 2026
- sshroot/ralphex-opencode“chore(deps): update Ralphex and OpenCode versions”GitHub · Sep 21, 2026
The biggest 5 of 24 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 24
Talked about on GitHub (24 times).
On GitHub · 24
- Oct 5, 2026chore(deps): update Ralphex and OpenCode versions — sshroot/ralphex-opencode0 reactions
- Oct 4, 2026claude-code-plugins.github.umputun.ralphex: init at 1.7.0 — sudosubin/agents.nix0 reactions
- Oct 4, 2026claude-code-marketplaces.github.umputun.ralphex: init at 1.7.0 — sudosubin/agents.nix0 reactions
- Oct 3, 2026agent-skills.github.umputun.ralphex: init at 1.7.0 — sudosubin/agents.nix0 reactions
- Sep 21, 2026chore(deps): update Ralphex and OpenCode versions — sshroot/ralphex-opencode0 reactions
19 more on GitHub
- Sep 14, 2026chore(deps): update Ralphex and OpenCode versions — sshroot/ralphex-opencode0 reactions
- Sep 9, 2026ralphex: update to 1.7.0 — macports/macports-ports0 reactions
- Sep 7, 2026ralphex: 1.6.1 -> 1.7.0 — NixOS/nixpkgs0 reactions · 1 comment
- Sep 7, 2026chore(deps): update Ralphex and OpenCode versions — sshroot/ralphex-opencode0 reactions
- Aug 31, 2026chore(deps): update Ralphex and OpenCode versions — sshroot/ralphex-opencode0 reactions
- Aug 24, 2026chore(deps): update Ralphex and OpenCode versions — sshroot/ralphex-opencode0 reactions
- Aug 17, 2026chore(deps): update Ralphex and OpenCode versions — sshroot/ralphex-opencode0 reactions
- Aug 17, 2026chore: replace Renovate with Dependabot — sshroot/ralphex-opencode0 reactions
- Jul 25, 2026ralphex: update to 1.6.1 — macports/macports-ports0 reactions
- Jul 23, 2026ralphex: 1.6.0 -> 1.6.1 — NixOS/nixpkgs0 reactions
- Jul 14, 2026ralphex: 1.5.1 -> 1.6.0 — NixOS/nixpkgs0 reactions · 1 comment
- Jun 28, 2026ralphex: update to 1.6.0 — macports/macports-ports0 reactions
- Jun 22, 2026ralphex: update to 1.5.1 — macports/macports-ports0 reactions
- Jun 10, 2026ralphex: 1.4.0 -> 1.5.1 — NixOS/nixpkgs0 reactions · 1 comment
- Jun 8, 2026ralphex: update to 1.5.0 — macports/macports-ports0 reactions
- Jun 1, 2026ralphex: 1.3.2 -> 1.4.0 — NixOS/nixpkgs0 reactions · 1 comment
- May 30, 2026ralphex: update to 1.3.2 — macports/macports-ports0 reactions
- May 20, 2026ralphex: init at 1.3.2 — NixOS/nixpkgs0 reactions · 3 comments
- Apr 21, 2026feat(skills): add ralphex as execution option — dvlkv/igor0 reactions
In this repositoryOne other file it gives its agents.
- llms.txtllms.txt
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
29 rules. About 0 are common, 12 are distinctive, and 17 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈12
Distinctive · estimate
This author's own choices. Worth a look.
17
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 59
Use jessevdk/go-flags for CLI parsing
- Distinctive: line 60
All comments lowercase except godoc
- Very specific: line 153
Every timeout here passes -k "$CLI_KILL_GRACE".
- Very specific: line 164
All git operations are methods on Service (CreateBranchForPlan, CreateWorktreeForPlan, MovePlanToCompleted, EnsureLocalGitignore, etc.)
- Very specific: line 185
Only active for ModeFull and ModeTasksOnly (review/plan/external modes skip worktree)
- Very specific: line 202
When ready, Claude emits PLAN_DRAFT signal with full plan content for user review
- Distinctive: line 205
If revised (manually or via interactive review), feedback is passed to Claude for plan modifications
- Distinctive: line 208
After completion, prompts user: "Continue with plan implementation?"
- Distinctive: line 209
If "Yes", creates branch and runs full execution mode on the new plan
- Distinctive: line 237
When adding platform-specific code (syscalls, signals, file locking):
- Very specific: line 238
Use build tags: //go:build !windows for Unix-only code, //go:build windows for Windows stubs
- Very specific: line 239
Create separate files: foo_unix.go and foo_windows.go
- Distinctive: line 240
Keep common code in the main file, extract platform-specific functions
- Very specific: line 298
Fallback loading: when loading config/prompts/agents, if file content is all-commented (no actual values), embedded defaults are used
- Very specific: line 368
Add new .txt files to create custom agents
- Very specific: line 369
Run ralphex --init to create local .ralphex/ project config with commented-out defaults
- Very specific: line 370
Run ralphex --reset to interactively restore defaults, or delete ALL .txt files manually
- Very specific: line 371
Run ralphex --dump-defaults <dir> to extract raw embedded defaults for comparison or merging
- Very specific: line 372
Use /ralphex-update skill for smart merging of updated defaults into customized configs
- Very specific: line 373
Use /ralphex-adopt skill to convert plans from other formats (OpenSpec, spec-kit, GitHub/GitLab issues, task-lists, free-form markdown) …
- Very specific: line 464
Run unit tests: make test
- Distinctive: line 466
MUST: ask the user before running the toy end-to-end test (see above).
- Distinctive: line 473
If you're an AI agent preparing a contribution, complete this checklist:
- Very specific: line 518
All tests MUST use t.TempDir() for any file operations
- Very specific: line 520
Verify tests are clean: compare MD5 checksums of config files before/after go test ./...
- Distinctive: line 525
CHANGELOG: Never modify during development - updates are part of release process only
- Distinctive: line 526
Version sections: Never add entries to existing version sections - versions are immutable once released
- Very specific: line 527
Linter warnings: Add exclusions to .golangci.yml instead of _, _ = prefixes for fmt.Fprintf/Fprintln
- Distinctive: line 528
Exporting functions: When changing visibility (lowercase to uppercase), check ALL callers including test files
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
ralphex
Autonomous plan execution with Claude Code - Go rewrite of ralph.py.
LLM Documentation
See @llms.txt for usage instructions and Claude Code integration commands.
Build Commands
make build # build binary to .bin/ralphex
make test # run tests with coverage
make lint # run golangci-lint
make fmt # format codeUpdating Dependencies
go get -u ./... does NOT update dependencies behind build tags. The e2e/ package uses //go:build e2e, so playwright-go and other e2e-only deps require a separate update:
go get -u ./... # update main deps
go get -u -tags=e2e github.com/mxschmitt/playwright-go # update e2e deps
go mod tidy && go mod vendor # tidy and re-vendorProject Structure
cmd/ralphex/ # main entry point, CLI parsing
pkg/config/ # configuration loading, defaults, prompts, agents
pkg/executor/ # claude and codex CLI execution
pkg/git/ # git operations (external git CLI)
pkg/input/ # terminal input collector (fzf/fallback, draft review)
pkg/notify/ # notification delivery (telegram, email, slack, webhook, custom)
pkg/plan/ # plan file selection, parsing, and manipulation
pkg/processor/ # pipeline coordinator, prompt rendering, executor policy, signal wrappers
pkg/processor/phase/ # task/review/external/finalize/plan phase engines
pkg/progress/ # timestamped logging with color
pkg/status/ # shared execution model types: signals, phases, sections
pkg/web/ # web dashboard, SSE streaming, session management
e2e/ # playwright e2e tests for web dashboard
scripts/ # utility scripts organized by function
scripts/ralphex-dk/ # Docker wrapper script (Python) with tests
scripts/codex-as-claude/ # codex wrapper for Claude-compatible output
scripts/copilot-as-claude/ # GitHub Copilot CLI wrapper for Claude-compatible output
scripts/gemini-as-claude/ # gemini wrapper for Claude-compatible output
scripts/agy-as-claude/ # Antigravity (agy) CLI wrapper for Claude-compatible output
scripts/pi-as-claude/ # pi wrapper for Claude-compatible output
scripts/hg2git/ # Mercurial-to-git translation script with tests
scripts/opencode/ # opencode wrapper scripts with tests
scripts/internal/ # internal dev/CI scripts (prep-toy-test, init-docker, etc.)
docs/plans/ # plan files locationCode Style
- Use jessevdk/go-flags for CLI parsing
- All comments lowercase except godoc
- Table-driven tests with testify
- 80%+ test coverage target
- Documentation: use
--flag=valueform for long CLI flags with values (not--flag value)
Key Patterns
- Plan format: Checkboxes (
- [ ]/- [x]) belong only in Task sections (### Task N:or### Iteration N:). TheTask/Iterationkeywords are structural tokens matched bypkg/plan/parse.go(taskHeaderPattern) and MUST stay in English even when plan content is written in another language — task titles and body text may be localized, but the section header keyword is fixed. Success criteria, Overview, and Context should not use checkboxes — they cause extra loop iterations. The task prompt handles them when present, but plan authors should avoid them. - Plan file rename tolerance: two layers prevent the task phase looping when a plan file is renamed mid-run. (a)
make_plan.txtdoes not ask the LLM togit mvthe plan intocompleted/— the framework callsMovePlanToCompletedat end-of-run idempotently usingr.cfg.PlanFile's exact basename. (b)planLocator.Path(pkg/processor/plan_locator.go) andMovePlanToCompleted(pkg/git/service.go) probe an alternate-date-format basename (YYYY-MM-DD-<slug>↔YYYYMMDD-<slug>) both alongside the original path (in-place rename) and undercompleted/; the in-place alternate is probed before thecompleted/paths so a current renamed file wins over a stale completed copy.MovePlanToCompletedalso treats an alternate-named file in the original directory as the move source.TaskPhase.HasUncompletedTasks(pkg/processor/phase/task.go) treatsfs.ErrNotExistfromParsePlanFileas "no uncompleted tasks" rather than "assume incomplete". - Signal-based completion detection (COMPLETED, FAILED, REVIEW_DONE signals) — constants in
pkg/status/ - Processor phase architecture:
Runnerinpkg/processor/runner.gocoordinates mode sequencing only. Task, internal review, external review, finalize, and plan creation behavior lives inpkg/processor/phaseand is injected through consumer-side interfaces inpkg/processor. Shared prompt rendering, executor retry/timeout policy, and plan location stay inpkg/processor; break handling and git snapshots are phase-owned shared support. Keep new phase behavior out ofRunner; preserve late-bound setters throughphase.Deps. - Plan creation signals: QUESTION (with JSON payload), PLAN_DRAFT (full draft content), and PLAN_READY
- Streaming output with timestamps
- Progress logging to files
- Progress file locking (flock) for active session detection
- Watch-mode dashboard reactivates completed sessions on fsnotify Write events, resuming tailing from
Session.lastOffset— recovery path for the flock race inRefreshStatesthat can prematurely mark a running session completed.Session.Reactivate()is idempotent and scoped to the written path;loadProgressFileIntoSessionrecordslastOffsetafter the initial load so reactivation does not re-emit replayed events - Progress file fresh start: files ending in a
Completed:footer are archived and then truncated on reuse; files ending in aFailed:footer (written byLogger.SetFailedbeforeClose) or with no footer preserve content and write a--- restarted at ... ---separator, so retried failed/aborted runs keep history.SetFailedis called incmd/ralphex/main.goforr.Runerrors (includingErrUserAborted), dashboard start errors, and errors fromrunWithWorktree - Completed-log archiving (#447):
archiveAndTruncateCompleted(pkg/progress/progress.go) copies the completed log to.ralphex/progress/history/<stem>/archive-<YYYYMMDD-HHMMSS>-<token>.txtbefore truncating the canonical file, so a repeated--reviewno longer destroys the previous transcript. The copy is read from the still-locked fd through anio.NewSectionReader, written to a temp file and renamed into place; the canonical file is never renamed or reopened, so its flock keeps serializing concurrent runs on the same path. The timestamp comes from the archived run's ownCompleted:footer, not the archiving moment. The archive basename deliberately carries anarchive-marker and noprogress-prefix:isProgressFile(pkg/web/watcher.go) matchesprogress-*.txtandDiscoverRecursivewalks the whole tree withskipDirscovering neither.ralphexnorhistory, so a prefixed archive would be discovered and replayed as a dashboard session of its own.pruneProgressArchivesmatches onlyarchiveNameRegex, so foreign files and in-flight.tmparchives are never deleted. Order is archive → truncate → prune: pruning last means a truncate failure rolls back to exactly the starting state, where pruning first would delete the oldest archive to make room for one the rollback then withdraws. Retention ismaxProgressRuns(10) total per canonical path — the live file plus 9 archives — and pruning is best effort: a removal failure warns throughLogger.Warnafter the header is written (so it lands in the new run's log) and lets the run continue, because everyNewLoggercaller treats an error as fatal and removing an open file fails on Windows.removeProgressArchiveandtruncateProgressFileare test seams for the failure paths --codexis an executor switch (not a new pipeline mode): setscfg.Executor = config.ExecutorCodexso task, both reviews, and finalize run throughCodexExecutor(s) withMultiAgent=true(enablesfeatures.multi_agent, registers therevieweragent for spawn_agent calls). Forcescfg.ExternalReviewTool = "none"(codex-reviewing-codex is weak-signal self-review).--pass-claude-md(codex executor only) setsCodexExecutor.PassClaudeMd = true. TheModeenum is unchanged; theExecutorsstruct uses role-named fields (Task/Review/External/Custom), andbuildCodexExecutorswires one codex instance into bothTaskandReviewwhen the resolved review model/effort matches task, or two distinct instances when they differ. Review prompts are shared with claude — the{{agent:<name>}}expansion inpkg/processor/prompts.goreadscfg.AppConfig.Executorand emitsUse the Task tool(claude) orspawn_agent(agent='reviewer', task='...')(codex). Codex config is passed as additive-coverrides per invocation by(*CodexExecutor).configOverrides()inpkg/executor/codex.go, layered on top of the user's~/.codex/config.tomlso user customizations are preserved. ralphex never writes to~/.codex/; for user-level CLAUDE.md it prints a one-time hint toln -s ~/.claude/CLAUDE.md ~/.codex/AGENTS.md- Shared reviewer contract:
reviewContextInstruction(pkg/processor/prompts.go) is prepended byformatAgentExpansionto every{{agent:<name>}}body, for both executors and for local/global/embedded agent files alike. It supplies WHERE (thegit diff {{DEFAULT_BRANCH}}...HEADlead-in) plus five contract lines the agent body files do not carry: diff scope with a severity bar for pre-existing issues, read-only (the parent loop owns fixing), no sub-delegation, an evidence threshold, and theNO ISSUES FOUNDsentinel. Go-side placement is deliberate and the non-overridability is the intended trade-off — a spawned agent's whole prompt is this lead-in plus its body, so a directive inreview_first.txt/review_second.txtreaches only the root session and never the agent, and Go injection keeps the contract on users who replaced the embedded review prompts or wrote their own agents. Consequence to keep in mind: a custom agent written for a deliberately repo-wide sweep still gets the scope line, and the only escape is to drop{{agent:<name>}}and hard-code the invocation block inline (losing frontmatter model/agent-type support and the claude/codex shape switch). Reach is wider than the review phase —expandAgentReferencesruns insidereplacePromptVariables, so an{{agent:}}reference placed intask.txtorfinalize.txtwould carry the contract too; the embedded prompts reference agents only fromreview_first.txtandreview_second.txt. The separateReport findings only - no positive observations.line is not part of the contract — it lives informatAgentExpansionClaude/formatAgentExpansionCodex - Codex review-phase directives:
prependCodexReviewGuidance(pkg/processor/prompts.go) injects a=== Codex orchestration directives ===block throughpromptBuilder.FirstReviewPromptandpromptBuilder.SecondReviewPromptwhencfg.isCodexExecutor()is true (no-op for claude). Covers two codex multi_agent quirks: (a) spawn_agent must pass onlyagentandtask—fork_context=truewith explicitagent_typeis rejected by the codex API; (b) on await_agenttimeout for a sub-agent that died mid-tool-call, re-spawn that agent ONCE then proceed with partial results. Section-level injection works for embedded and customized review prompts alike;phase.ReviewPhaseconsumes the final prompts. - Codex task-phase skill-conflict directive:
prependCodexTaskGuidance(pkg/processor/prompts.go) injects the=== Codex task-execution directives ===block (codexTaskGuidance) throughpromptBuilder.TaskPromptwhencfg.isCodexExecutor()is true (no-op for claude).phase.TaskPhaseconsumes the final prompt. It tells codex that ralphex's task prompt is authoritative and a conflicting auto-activated skill from~/.codex/skills/must not be followed. Deliberately generic (names no specific skill); a soft prompt-level mitigation, not a hard guard — codex 0.133.0 has no per-invocation skill-disable flag. Task-phase only - Codex output streaming: codex has no
stream-jsonequivalent, so assistant message text + tool dispatch land only in the session rollout file at~/.codex/sessions/<y>/<m>/<d>/rollout-<ts>-<session-id>.jsonl.CodexExecutor.Runextracts the session id from the stderr header banner (extractSessionID+ bufferedsessionIDCh) and spawnstailRolloutFileto follow it.formatRolloutEventforwards two rollout record types: assistant message text (formatAssistantMessage) and reasoning-summary titles (formatReasoningSummary,**-stripped).function_callandcustom_tool_call_outputrecords are skipped as tool-machinery noise. Reasoning is taken from the rollout — NOT the live stderr reasoning stream — on purpose: codex 0.144+ echoes loaded skill/tool markdown verbatim onto stderr, and skill headers (**Detect stale base:**) are shape-identical to genuine reasoning titles, so no text-shape stderr filter can separate them; the rollout's typedreasoningrecords never carry that echo.tailCtxis canceled after stdout EOF so the tailer drains once more and exits - Codex stderr filtering:
shouldDisplay(pkg/executor/codex.go) forwards ONLY codex's resolvedmodel:/sandbox:/reasoning effort:header lines, and only on the executor's firstRun()call (headerEmitted atomic.Bool), so users see what codex resolved from~/.codex/config.toml. Everything else on stderr is suppressed — per-iteration startup banner, exec output, hook lifecycle lines, and the reasoning stream (which comes from the rollout instead; see above). The ralphex-side banner (printExecutorInfo,cmd/ralphex/main.go) emitssandbox:(andmodel:/reasoning effort:whencodex_model/codex_reasoning_effortare set; empty values skipped) - Claude subagent progress: newer Claude Code streams Task-tool subagent activity as
systemevents with subtypetask_started/task_progress(no text block, soextractTextdrops them) — this is why a multi-agent review phase used to go silent for the whole agent run.ClaudeExecutor.parseStream(pkg/executor/executor.go) synthesizes a<description>heartbeat line from those events viasubagentLineand forwards it toOutputHandleronly (not intooutput/recentText/signalor thediagnosticswindow). Only the description is shown — the subagent type and tool name are deliberately omitted: stock config runs every review agent asgeneral-purposeso a[general-purpose]prefix would be pure noise (only user-customized agents withagent:frontmatter carry distinct types), and the description already names the action ("QA review of branch", "Running tests").task_started(the agent's task title) is unthrottled;task_progress(per step) is throttled to one persubagentProgressInterval(10s) so parallel agents don't flood. Completion (task_updated/task_notification) is not surfaced — without an agent label a bare "done" is ambiguous across parallel agents. The model's own text is never throttled.nowFn(unexported, defaults totime.Now) makes the throttle window deterministically testable. Only Task-tool SUBAGENT activity is surfaced this way — a skill that runs INLINE in the main session (e.g./smellson a small change) does its Read/Bash tool calls in the main session with notask_*events, so those stretches stay quiet by design - Debugging claude/codex executor streaming: to learn what the real upstream CLIs emit (stream-json shapes, stderr format, rollout records), run controlled experiments in a fresh agterm session —
agtermctl session new --wait --command "zsh -lc '<cli> ... > out 2> err'"— and inspect the captured files. Nestedclaude/codexlaunched from the agent's OWN tool shell is blocked by the auto-mode classifier, so a separate agterm session is the only way to capture real streams. Useful captures:claude --dangerously-skip-permissions --output-format=stream-json --verbose --print(subagentsystem/task_*events,parent_tool_use_id);codex exec --sandbox read-onlystderr (header banner,**bold**reasoning,execoutput echo) plus its rollout file at~/.codex/sessions/<y>/<m>/<d>/rollout-*-<session-id>.jsonl(typedreasoning/message/custom_tool_call_outputrecords — the clean source of truth). Gate this whole approach onAGTERM_ENABLED(only usable when running inside agterm) --plan-model/--task-model/--review-modelresolve per-phase model/effort.plan_modelfalls back totask_model;review_modelfalls back totask_model. Claude mode injects--model/--effortintoclaude_command. Codex mode:ResolveCodexModelEffort(pkg/processor/executor_factory.go) resolves themodel[:effort]spec againstcodex_model/codex_reasoning_effortdefaults;buildCodexExecutorsbuilds a separate reviewCodexExecutorwhen review differs from task.maxeffort does not exist in codex — kept default,maxDroppedreported,codexModelBanner/codexPlanBanner(cmd/ralphex/main.go) warns
Finalize Step
Optional post-completion step after successful review phases. Triggers on ModeFull, ModeReview, ModeCodexOnly. Disabled by default (finalize_enabled). Runs once, no signal loop — best effort (failures logged, don't block success). Default behavior when enabled: rebase commits onto default branch, optionally squash, run tests.
Key files:
pkg/processor/phase/finalize.go-FinalizePhase.Run()method called at end of review modespkg/config/defaults/prompts/finalize.txt- default finalize prompt
Custom External Review
Custom scripts instead of codex for external review (external_review_tool = custom, custom_review_script). Script gets the prompt file path as its single arg, outputs findings to stdout for Claude to evaluate.
{{DIFF_INSTRUCTION}}expands per iteration: firstgit diff main...HEAD, subsequentgit diff(uncommitted only)max_external_iterations0 = auto,max(3, max_iterations/5)review_patiencestalemate detection: terminates after N consecutive no-commit rounds (0 = disabled)session_timeout/idle_timeout(see Configuration): in default Claude mode neither applies to external codex/custom review; under--codexsession_timeoutcovers every executor call- Manual break: Ctrl+\ pauses task phase (fresh session re-reads plan on resume), terminates external review immediately. Break channel is repeatable (send-on-channel, not close-once);
SetPauseHandler()sets the task pause callback. Not on Windows codex_enabled = falsebackward compat: treated asexternal_review_tool = none
Key files:
pkg/executor/custom.go- CustomExecutor for running external scriptspkg/config/defaults/prompts/codex_review.txt/custom_review.txt/custom_eval.txt- external review promptspkg/processor/prompts.goandpkg/processor/prompt_builder.go-getDiffInstruction(),buildPreviousContext(), prompt assemblypkg/processor/phase/external_review.go- tool selection and external review loop
Alternative Providers for Claude Phases
claude_command/claude_args replace Claude Code with any stream-json-compatible CLI. Included wrappers: scripts/codex-as-claude/codex-as-claude.sh, scripts/copilot-as-claude/copilot-as-claude.sh, scripts/gemini-as-claude/gemini-as-claude.sh, scripts/agy-as-claude/agy-as-claude.sh, scripts/opencode/opencode-as-claude.sh, scripts/pi-as-claude/pi-as-claude.sh. Wrappers must ignore unknown flags gracefully (*) shift ;;) — default Claude flags may still be passed via config fallback. See docs/custom-providers.md.
Env vars:
- Codex:
CODEX_MODEL,CODEX_SANDBOX,CODEX_VERBOSE - Copilot:
COPILOT_MODEL,COPILOT_GITHUB_TOKEN,GH_TOKEN,GITHUB_TOKEN - pi:
PI_PROVIDER,PI_MODEL,PI_THINKING,PI_VERBOSE,PI_EXTRA_ARGSCopilot wrapper: native autopilot mode —--autopilot --no-ask-user --allow-allfor task/review,--autopilot --allow-allfor plan runs (soQUESTIONsignals surface). pi wrapper: line-buffers pi's token-level text deltas so<<<RALPHEX:...>>>signals land intact in onecontent_block_delta; suppressed events emit empty keepalive deltas soidle_timeoutdoesn't fire during silent tool runs; literal<<<RALPHEX:on re-emitted stderr is neutralized to<<< RALPHEX:; the prompt reaches pi via stdin (temp-file redirect), never argv; translation jq runs in the background with an interruptiblewaitso the TERM-forwarding trap fires while pi is alive. Task/review phases only — plan creation mode has no pi adapter.
AWS Bedrock Provider (Docker Wrapper Only)
scripts/ralphex-dk.sh supports AWS Bedrock as a Claude provider (--claude-provider bedrock / RALPHEX_CLAUDE_PROVIDER). See docs/bedrock-setup.md.
Key functions in scripts/ralphex-dk.sh:
get_claude_provider()- returns provider from CLI flag or env varbuild_bedrock_env_args()- builds docker -e flags for BEDROCK_ENV_VARSexport_aws_profile_credentials()- exports credentials from AWS profilevalidate_bedrock_config()- validates bedrock config, returns warnings
Docker Socket Support (Docker Wrapper Only)
--docker flag (or RALPHEX_DOCKER_SOCKET) mounts the host Docker socket for testcontainers. Socket path from DOCKER_HOST (unix://) or /var/run/docker.sock; GID auto-detected and passed via DOCKER_GID. Missing socket = fail-fast error.
Key functions in scripts/ralphex-dk.sh:
is_docker_enabled()- checks CLI flag andRALPHEX_DOCKER_SOCKETenv varresolve_docker_socket()- resolves socket path fromDOCKER_HOSTor defaultget_docker_socket_gid()- detects socket file GID viaos.stat()
Docker Network Mode (Docker Wrapper Only)
--network MODE flag (or RALPHEX_DOCKER_NETWORK) passes --network <value> to docker run — lets the container reach docker-compose services on localhost.
CLI Refresh at Container Start
The Dockerfile installs claude/codex unpinned, so a published tag freezes both at whatever npm served on that build (#410). Since they ship far more often than ralphex is tagged, a stale image silently resolves a short model alias (sonnet) to an older model rather than failing. Claude's own updater cannot apply here: npm installs it root-owned under /usr/local/lib/node_modules and the container runs as app, so the check only prints a startup notice — hence ENV DISABLE_AUTOUPDATER=1 in the Dockerfile. The refresh is opt-in (RALPHEX_CLI_UPDATE): the base ralphex image leaves it off so authors building on it get no surprise npm install, network call, or version drift at start; Dockerfile-go bakes ENV RALPHEX_CLI_UPDATE=1 so the wrapper's default image (ralphex-go) stays current.
update_cli_tools() in scripts/internal/init-docker.sh runs npm install -g @anthropic-ai/claude-code@latest @openai/codex@latest at start when the refresh is enabled, as root, before baseimage drops to app. Usually ~5s, bounded by CLI_UPDATE_TIMEOUT (90s) plus --fetch-timeout=20000 --fetch-retries=1 — npm's own defaults (300s fetch-timeout, 2 retries) would let a black-holed registry stall every start for minutes. Best effort by design: install failure or deadline leaves the baked versions in place and returns 0. npm exit 0 does not imply working CLIs, so both are smoke-checked via cli_version() (bounded by CLI_SMOKE_TIMEOUT, 20s); the install replaces the baked packages in place, leaving no fallback, so a broken or hung CLI is reported loudly (pointing at re-running without RALPHEX_CLI_UPDATE) rather than failing later unexplained.
Every timeout here passes -k "$CLI_KILL_GRACE". Busybox timeout sends only SIGTERM by default, and a process ignoring it runs to completion and exits 0 — so a bare timeout would neither bind the deadline nor report the overrun as a failure.
run_cli_install() and cli_version() exist as stub seams: both wrap a timeout that execs a real binary, so a shell-function npm/claude stub would not intercept and the suite would install for real on the test machine. cli_update_enabled() gates on RALPHEX_CLI_UPDATE (opt-in, off by default; truthy 1/true/yes), lowercasing and stripping whitespace to match is_docker_enabled() in scripts/ralphex-dk.sh. build_base_env_vars() there forwards a host-set RALPHEX_CLI_UPDATE into the container; when unset it forwards nothing, leaving the image's own default in charge (off for base, on for ralphex-go). The --help path pins RALPHEX_CLI_UPDATE=0 on its own docker run, overriding a forwarded opt-in or the baked go-image default: the entrypoint is /init.sh and runs /srv/init.sh whatever command it is given, so rendering help would otherwise trigger the install.
Exercised by scripts/internal/init-docker_test.sh via the INIT_DOCKER_SOURCE_ONLY guard — run it by hand (sh scripts/internal/init-docker_test.sh), no CI job or make target invokes it. CLI_UPDATE_LOG exists so that suite does not write to the caller's real /tmp.
Known trade-off (applies only when enabled): this pulls @latest as root on every start, after the credential/workspace mounts are attached, so an upstream compromise executes npm lifecycle scripts with those mounts present (build-time installs had no user mounts). Off-by-default in the base image keeps that exposure opt-in. --ignore-scripts is not an option — claude-code's postinstall fetches its native binary, so the CLI is unusable without it.
Git Package API
Single public entry point: git.NewService(path, logger, vcsCmd...) (*Service, error)
- All git operations are methods on
Service(CreateBranchForPlan, CreateWorktreeForPlan, MovePlanToCompleted, EnsureLocalGitignore, etc.) Loggerinterface for dependency injection, compatible with*color.Color- Uses
backendinterface internally, implemented byexternalBackendwhich shells out to the configured VCS command - Optional
vcsCmdparameter overrides the default"git"command (e.g., path tohg2git.shtranslation script) MovePlanToCompletedcommits throughcommitFiles(pathspec-restricted), never the barecommit. This call used to run against the user's main checkout in worktree mode, which stays usable during the run, so a bare commit swept anything staged there intomove completed plan: ...(#435); #450 moved the call into the worktree, and the pathspec restriction stays because the worktree index can hold unrelated state too. The source path is passed only when the move went throughgit mv, which stages the source deletion; theos.Renamefallback is reached both for an untracked source and for a tracked one whose destination already exists, and naming a path git does not know fails the whole commit. Anos.Lstat(destPath)immediately before thatos.Renamerefuses the move whencompleted/<basename>is already there:git mvdeclines an existing destination butos.Renamereplaces it silently, and an uncommitted archive copy has no other copy anywhere.resolvePlanMoveTargetstherefore returnsdone=trueonly when the source is gone and acompleted/copy proves the plan already archived — a source that still exists returnsdone=falsewhatever sits incompleted/, so the collision reaches the move path and errors instead of passing for a successful archive (the caller readsdoneas archived). The list is therefore built from the branch taken, not by re-testing the file. Consequence: a pathspec commit is refused while a merge or cherry-pick is in progress in the target checkout (cannot do a partial commit during a merge), so the archive fails loudly there instead of silently absorbing the user's merge. The archive is best effort in the caller (executePlan), and a failure is reported twice on purpose: as aWARN:through the progress logger, so the progress file keeps it where the previous bare stderr write left no trace, and as aplan archive did not complete: ...line at the end of the completion summary. A watch-mode dashboard picks that line out of the progress file (detectEventType,pkg/web/tail.go); a single-session--serverun does not, because live SSE events come fromBroadcastLoggerandweb.Loggercarries noWarn. A rejected archive commit (e.g. acommit-msghook enforcing conventional commits, #439) leaves the staged rename in the tree, and theWARNlands after the runner'sall phases completed successfullyand before the summary block, which is easy to miss. In worktree mode that staged rename is inside the worktree, so the failure also sets the preserve flag that stops cleanup deleting it — see the Worktree Isolation Mode section
Key files:
pkg/git/service.go-Servicetype,backendinterfacepkg/git/external.go- VCS CLI backend (externalBackendtype)
Worktree Isolation Mode
--worktree flag or use_worktree = true config option runs each plan in an isolated git worktree, enabling parallel execution of multiple plans on the same repo. --branch flag overrides the branch name derived from the plan filename (useful when auto-detection is fragile, e.g. generic filenames or spec-driven layouts).
- Worktrees created at
.ralphex/worktrees/<branch-name>inside main repo - Progress logger created before chdir so files land in main repo's
.ralphex/progress/ - The header records two plan paths:
Plan:is the main-checkout path the run was launched with,Worktree plan:(worktree mode only) is the copy the run actually ticks, computed byworktreePlanFile()before the logger is built.handleSessionPlan(pkg/web/server.go) serves the worktree copy while it exists and falls back toPlan:once the worktree is removed, so a watch-mode dashboard shows live checkbox state instead of the untouched main copy (#440). Unknown header lines are ignored byparseHeaderField, so older readers are unaffected. Not fixed by this: the main-checkout copy stays unticked at its original path, so once the worktree is gone the panel falls back to it and a finished worktree run's plan panel reads 0 done - The plan archive runs on the feature branch, never in the main checkout (#450).
archivePlan(cmd/ralphex/main.go) always usesreq.GitSvc/req.PlanFile, which in worktree mode are the worktree's service and the ticked copy, somove completed plan: ...lands beside the task commits and reaches the PR. Archiving in the main checkout instead put the commit on whatever branch that checkout sat on — unpushable under branch protection, and for an untracked plan it added an untickedcompleted/file there that merged cleanly alongside the branch's ticked original, leaving two copies and no real archive. The user's main-checkout copy is deliberately left in place: it is their file, often untracked, and deleting it is not ralphex's call — so the completion summary annotates the archived path with the branch it was committed on (displayMeta'splanNote), since the path alone stops resolving the moment the worktree is removed. Ordering matters and is not what it first looks like:DiffStatsruns before the archive andsendNotificationafter it. Taking the stats afterwards double-counts the plan underdiff.renames=false, because the archived copy differs from the base copy by every ticked checkbox and so falls below git's rename-similarity threshold — measured,-Mdoes not rescue it and only an implausibly low-M1%does. Before the archive the ticked plan is counted exactly once at its source path, which is the same content delta - A failed archive keeps the worktree instead of removing it.
archivePlansetsreq.WtPreserve(anatomic.Bool, read from the interrupt watcher's goroutine) andcleanupWorktreethen restores CWD but skipsRemoveWorktree; the closure installed inWtCleanupis the same one, so the 5-second force-exit path cannot delete it either. Without this,git worktree remove --forcewould discard the staged rename a rejected commit leaves behind (#439) — the ticked plan is already committed on the branch, so what is lost is the archive operation itself, not the plan. The run still exits green: archiving is best effort, and the success notification is sent after the failed attempt. The summary names the retained worktree and saysgit -C <root> status, because a baregit statusafter the chdir back inspects the main checkout - Worktree auto-removed on completion, failure, or SIGINT; branch preserved for PR. The one exception is a failed plan archive, which retains it (see above)
- Source-checkout cleanliness is enforced only in in-place branch mode.
preparePlanBranch'sworktreeModeflag splits the two: ordinary dirty files are a hard error when the feature branch uses the same checkout, but worktree mode lists them in a warning and does not copy them (#444). An uncommitted selected plan is the exception and is copied bycopyToWorktree. A new feature branch starts at the currentHEAD; an existing feature branch keeps its own tip. Local.ralphexconfiguration is loaded before worktree creation and still applies. Unfinished Git operations are a hard error in worktree mode;externalBackend.operationInProgressdetects merge, cherry-pick, revert, rebase, am, and bisect state throughgit rev-parse --git-path. The guard is a conservative source-state boundary: a worktree forks committed HEAD and carries none of the unfinished operation's index or staged state, so the source checkout is an unsound base to fork from. Its original rationale was that completion archived the plan in that checkout, which #450 changed — the archive now commits in the worktree — so the reason was rewritten rather than the guard relaxed. Reusing an existing feature branch mid-operation may in fact work; whether to narrow the guard is a #445 policy decision with its own blast radius, deliberately not taken in #450 - Only active for
ModeFullandModeTasksOnly(review/plan/external modes skip worktree) runWithWorktree()incmd/ralphex/main.goencapsulates the full lifecycle- Case-insensitive path handling:
CreateBranchForPlan(),CreateWorktreeForPlan(), andCommitPlanFile()resolve plan file paths to actual on-disk case viaresolveFilesystemCase()to handle macOS APFS case-insensitive filesystems.hasChangesOtherThan()uses case-insensitive comparison for plan file exclusion
Key files:
cmd/ralphex/main.go-runWithWorktree(),selectAndExecutePlan(), interrupt cleanuppkg/git/service.go-CreateWorktreeForPlan(),CommitPlanFile(),RemoveWorktree(),resolveFilesystemCase()pkg/git/external.go-addWorktree(),removeWorktree(),pruneWorktrees()(unexported backend methods)
Plan Creation Mode
The --plan "description" flag enables interactive plan creation:
- Claude explores codebase and asks clarifying questions
- Questions use QUESTION signal with JSON:
{"question": "...", "options": [...]} - User answers via fzf picker (or numbered fallback); an "Other" option allows typing a custom answer
- Q&A history stored in progress file for context
- When ready, Claude emits PLAN_DRAFT signal with full plan content for user review
- User can Accept, Revise (with feedback), Interactive review, or Reject the draft
- Interactive review opens
$EDITORwith the plan content; on save, a unified diff is computed and fed back as revision feedback - If revised (manually or via interactive review), feedback is passed to Claude for plan modifications
- Loop continues until user accepts and Claude emits PLAN_READY signal
- Plan file written to docs/plans/
- After completion, prompts user: "Continue with plan implementation?"
- If "Yes", creates branch and runs full execution mode on the new plan
Plan creation signals:
QUESTION- asks user a question with options (JSON payload)PLAN_DRAFT- presents plan draft for review (plan content between markers)PLAN_READY- indicates plan file was written successfully
Key files:
pkg/input/input.go- terminal input collector (fzf/fallback, draft review)pkg/status/status.go- shared signal constants (COMPLETED, FAILED, REVIEW_DONE, etc.)pkg/processor/phase/signals.go- runtime phase signal parsers for QUESTION and PLAN_DRAFT, plus signal helperspkg/processor/signals.go- processor compatibility wrappers around phase signal helperspkg/config/defaults/prompts/make_plan.txt- plan creation prompt
Platform Support
- Linux/macOS: supported
- Windows: best effort. It builds and runs, releases carry no Windows binary, and the maintainer
has no Windows machine, so a Windows-only report cannot be reproduced and a Windows-only fix
cannot be verified. Such an issue or PR is merged only when the cause is clear-cut, the change is
small and self-contained, and it cannot affect Linux or macOS; otherwise it is closed. Known gaps:
- Process group signals not available (graceful shutdown kills direct process only, not child processes)
- File locking not available (active session detection disabled)
- Ctrl+\ manual break not available
- Prompts are passed to the claude CLI via stdin (not
-pflag) to avoid the cmd.exe 8191-character command-line limit
Cross-Platform Development
When adding platform-specific code (syscalls, signals, file locking):
- Use build tags:
//go:build !windowsfor Unix-only code,//go:build windowsfor Windows stubs - Create separate files:
foo_unix.goandfoo_windows.go - Keep common code in the main file, extract platform-specific functions
- Windows stubs can be no-ops where functionality is optional
Example files:
pkg/executor/procgroup_unix.go/procgroup_windows.go- process group managementpkg/progress/flock_unix.go/flock_windows.go- file locking helpers
Cross-compile to verify Windows builds:
GOOS=windows GOARCH=amd64 go build ./...Configuration
- Global config location:
~/.config/ralphex/(override with--config-dirorRALPHEX_CONFIG_DIR) - Local config location:
.ralphex/(per-project, optional) - Config file format: INI (using gopkg.in/ini.v1)
- Embedded defaults in
pkg/config/defaults/ - Precedence: CLI flags > local config > global config > embedded defaults
- Custom prompts:
~/.config/ralphex/prompts/*.txtor.ralphex/prompts/*.txt - Custom agents:
~/.config/ralphex/agents/*.txtor.ralphex/agents/*.txt plan_model/task_model/review_modelconfig options:model[:effort]for plan creation / task / review phases;plan_modelandreview_modelfall back totask_model. CLI flags--plan-model/--task-model/--review-modeltake precedence. Parsed by executor setup (pkg/processor/executor_factory.go). See the Key Patterns bullet for claude- vs codex-executor behavior. Disabled by default (empty = Claude CLI defaults)default_branchconfig option: override auto-detected default branch for review diffsmax_iterationsconfig option: override CLI default (50) for maximum task iterations per plan (CLI flag--max-iterationstakes precedence)vcs_commandconfig option: override the VCS binary used by the git backend (default:"git"). Set to a translation script path (e.g.,scripts/hg2git/hg2git.sh) to use ralphex with Mercurial repos. Seedocs/hg-support.mdcommit_trailerconfig option: trailer line appended to all ralphex-orchestrated git commits (both Go-code commits and LLM-prompted commits). When set, the trailer is appended after a blank line at the end of every commit message. Example:commit_trailer = Co-authored-by: ralphex <noreply@ralphex.com>. Disabled by default (empty)- Notification config:
notify_channels,notify_on_error,notify_on_complete,notify_timeout_ms, plus channel-specificnotify_*fields (seedocs/notifications.md) review_patienceconfig option: terminate external review after N consecutive unchanged rounds (0 = disabled). CLI flag--review-patiencetakes precedencewait_on_limitconfig option: duration to wait before retrying on rate limit (e.g., "1h", "30m"). CLI flag--waittakes precedence. Disabled by defaultsession_timeoutconfig option: per-session timeout (e.g., "30m"). Applies to claude in default mode and to every executor call under--codex(task/review/finalize/eval); external codex/custom review in Claude mode is not affected. Kills hanging sessions, continues to next iteration. Applied inretryPolicy.runWithSessionTimeoutviacontext.WithTimeout, gated onExecutor==ExecutorCodex || toolName=="claude". CLI flag--session-timeouttakes precedence. Disabled by defaultidle_timeoutconfig option: kills claude/codex executor sessions when no output for a given duration (e.g., "5m"). Resets on each output line; only fires when the session goes silent. Implemented inClaudeExecutor.Run()/CodexExecutor.Run()viatime.AfterFunc. Wired bybuildCodexExecutorfor first-class--codex; NOT bybuildExternalCodexExecutor, so external codex review in default-claude mode has no idle timeout. Custom external review unaffected. CLI flag--idle-timeouttakes precedence. Disabled by defaultmove_plan_on_completionconfig option: controls whether completed plans move todocs/plans/completed/on success. Defaulttrue. Disable for workflows that manage plan lifecycle externally (spec-driven tooling with separate archive steps)preserve_anthropic_api_keyconfig option /--preserve-anthropic-api-keyCLI flag: when true,ANTHROPIC_API_KEYis passed through to the child claude process (needed for API-key auth rather than OAuth/keychain). Defaultfalsestrips the key. The merge sentinelPreserveAnthropicAPIKeySetlives only onValues(load-bearing for local-overrides-global merge);Configcarries the resolved bool. Plumbed:Config.PreserveAnthropicAPIKey→pkg/processor/executor_factory.go→ClaudeExecutor.PreserveAPIKey→execClaudeRunner.preserveAPIKey→claudeChildEnv()(pkg/executor/executor.go). When enabled, the startup banner emitsauth: ANTHROPIC_API_KEY passthrough enabled. Claude Code's per-session markers (CLAUDECODE,CLAUDE_CODE_SESSION_ID,CLAUDE_CODE_MESSAGING_SOCKETand the rest ofsessionEnvVarsinpkg/executor/executor.go) are always stripped regardless of this setting, which prevents nested-session errors. Marker names are matched exactly, so configuration variables such asCLAUDE_CODE_USE_BEDROCKare preserved. The custom review script is the one spawn path that still inherits the host env unfiltered
Local Project Config (.ralphex/)
Projects can have local configuration that overrides global settings. Run ralphex --init to create the .ralphex/ directory with commented-out defaults:
project/
├── .ralphex/ # optional, project-local config (created by --init)
│ ├── config # overrides specific settings (per-field merge)
│ ├── prompts/ # per-file fallback: local → global → embedded
│ │ └── task.txt # only override task prompt
│ └── agents/ # per-file fallback: local → global → embedded
│ └── custom.txt # project-specific agentMerge strategy:
- Config file: per-field override (local values override global, missing fields fall back)
- Prompts: per-file fallback (local → global → embedded for each prompt file)
- Agents: per-file fallback (local → global → embedded for each agent file, same as prompts)
Config Defaults Behavior
- Commented templates: config file, prompts, and agents are installed with all content commented out (prefixed
#) - Auto-update: files with only comments/whitespace are safe to overwrite on updates - users get new defaults automatically
- User customization: uncommenting any line marks the file as customized - it will be preserved and never overwritten
- Fallback loading: when loading config/prompts/agents, if file content is all-commented (no actual values), embedded defaults are used
- Comment handling: leading meta-comment block (2+ contiguous
# ...lines at top of file) is stripped when loading prompts and embedded defaults; a single# Titleat the top is preserved (treated as markdown header, not meta-comment). FullstripCommentsis only used for emptiness detection to trigger fallback - scalars/colors: per-field fallback to embedded defaults if missing
*Setflags (e.g.,CodexEnabledSet) distinguish explicitfalse/0from "not set"
Error Pattern Detection
Configurable patterns detect rate limit and quota errors in claude/codex output:
claude_error_patterns/codex_error_patterns: comma-separated error patterns (default strings in the embedded config, mirrored in the README config table; not carried inllms.txt). Codex phrases are tightened so review findings that talk about rate limiting do not trip a false positive. The claude error set enumeratesAPI Error:by code (400/401/403/404/413/429/500) rather than the bare substring, keeping failed-run wrapper output specific; clean assistant narration is excluded separately by source provenance. The transient529/502/503/504codes are handled byclaude_retry_patterns, not here- Matching is case-insensitive substring search
- Whitespace is trimmed from each pattern
- For claude:
parseStreamseparates complete surfacedOutput, bounded recent surfacedRecentText, and bounded trustedDiagnosticText. The trusted window contains at most 10 structured result/error, assistant API-error, relevant system/error, and non-JSON CLI blocks in chronological order; ordinary assistant content, successful result summaries, and subagent progress are excluded even if they quote a configured phrase. Aresultrecord counts as diagnostic when it authenticates itself as an error (is_error:true,terminal_reason:"api_error", or a non-zeroapi_error_status) — a bareterminal_reasondoes not qualify, because a successful result can carry one.subtypeis never consulted: Claude Code has been observed emittingsubtype:"success"on a genuine rate-limit result (anthropics/claude-code#79500).system/api_retryis excluded entirely — it reports an attempt, not an outcome, and Claude often recovers from one - Claude patterns always check
DiagnosticText. SurfacedRecentTextis promoted to pattern input only when the process itself failed — a non-zero exit or a stream read error (an idle timeout cancels the stream context, so it arrives as one). Signal absence is deliberately NOT part of that rule: a successful run often emits no marker by design (review_first.txtpath B stays silent after fixing issues,task.txtemitsALL_TASKS_DONEonly once the plan has no boxes left), so treating "no signal" as failure evidence would readmit narration on clean runs. The promotion path is what keeps limit classification working for the bundled wrapper scripts (gemini/copilot/opencode/pi/agy), whose result records carry nois_errorfield and which surface child stderr as ordinary deltas. The codex-as-claude wrapper discards child stderr and always exits 0 after the child run, so it is not covered. Explicit parent cancellation bypasses pattern checks Result.DiagnosticTextmakes the exact classified window available to executor callers and tests;Result.Outputand normal progress streaming keep their existing full surfaced output behavior. Debug mode additionally labels non-JSON lines as they are classified- For codex: patterns checked against stdout AND a live per-line scan of stderr. Stderr scanning runs inside
processStderrbefore the 5-line / 256-rune tail truncation, so detection is eviction- and truncation-resistant. The scan is gated byisCodexErrorLine(matcheserror:/fatal:/panic:prefix, case-insensitive) so progress chatter cannot trigger false positives. The first matching limit/error pattern per category is recorded onstderrResult.{limitMatch,errorMatch}and consumed byCodexExecutor.checkPatterns. Priority is limit-class first across both sources:stdout limit → stderr limit → stdout error → stderr error(within a class, stdout wins). Patterns are evaluated only when the process exits non-zero and context is not canceled. Stderr is scanned because OpenAI/ChatGPT plan-quota errors are emitted on stderr while stdout is empty on failure - For custom executors: stderr is merged into stdout by the executor itself (
cmd.Stderr = cmd.Stdout), so the same pattern check covers both streams. Patterns checked only when process exits non-zero and context is not canceled - On match, ralphex exits gracefully with pattern info and help command suggestion
Transient retry patterns for wrapper-level stalls:
claude_retry_patterns: comma-separated transient Claude/fya markers retried like executor timeouts. Default:FYA_TRANSIENT_TIMEOUT,API Error: 529,API Error: 502,API Error: 503,API Error: 504. The transient HTTP errors (529 Overloaded, 502/503/504 gateway) live here, not inclaude_limit_patterns: they are short-lived server hiccups, so they auto-retry without requiring--wait(500 is intentionally excluded — it can be a deterministic server failure, caught by the enumeratedAPI Error: 500error pattern). Precedence is retry → limit → error, so a no-signal 529 matches the retry tier first; the claude error set enumerates only hard codes (API Error: 400/401/403/404/413/429/500), not the transient ones, so a signal-present 529 is no longer flagged as an error and the completed run's signal is honored- Retry patterns are checked before limit and error patterns. They do not use
wait_on_limit; the phase receives timeout-style metadata and applies its existing bounded retry behavior. The task loop (pkg/processor/phase/task.go) and review-iteration loop (pkg/processor/phase/review.go) wait a short fixedretryBackoff(5s, defined inpkg/processor/phase/phase.go) before re-running the timed-out/transiently-failed iteration; the first-review soft-skip path is not a retry and has no backoff - Retry detection is suppressed when
result.Signalis non-empty: a completed run that emitted a structured signal (e.g.ALL_TASKS_DONE) must not be discarded and re-run because a trusted diagnostic contains a retry marker.patternError(patternText, signal)(pkg/executor/executor.go) gates only the retry tier on the signal; trusted limit and error patterns still fire regardless (they surface loudly rather than silently re-running)
Limit patterns for wait+retry behavior:
claude_limit_patterns/codex_limit_patterns: comma-separated limit patterns (default strings in the embedded config, mirrored in the README config table andllms.txt)wait_on_limit: duration string (e.g., "1h", "30m"), disabled by default--waitCLI flag overrideswait_on_limitconfig- Priority: retry patterns checked first, then limit patterns; if a limit pattern matches AND wait > 0, wait and retry; if match AND wait == 0, fall through to error pattern behavior
- Limit patterns intentionally overlap with error patterns —
wait_on_limitacts as the toggle
Implementation:
PatternMatchErrortype inpkg/executor/executor.gowithPatternandHelpCmdfieldsLimitPatternErrortype inpkg/executor/executor.gowithPatternandHelpCmdfieldsRetryPatternErrortype inpkg/executor/executor.gowith aPatternfieldmatchPattern()helper for case-insensitive matching (used by error, limit, and retry pattern checks)ClaudeExecutor.extractDiagnostic()classifies trusted stream events;resolveRunResult()combines that provenance with signals, idle timeout, and process exit state- Patterns passed via
ClaudeExecutor.ErrorPatterns/LimitPatterns/RetryPatternsandCodexExecutor.ErrorPatterns/LimitPatterns(codex has no retry patterns) retryPolicy.Run()inpkg/processor/execution_policy.gowraps executor calls with retry logic
Agent System
5 default agents are installed on first run to ~/.config/ralphex/agents/ as commented-out templates:
implementation.txt- verifies code achieves stated goalsquality.txt- reviews for bugs, security issues, race conditionsdocumentation.txt- checks if docs need updatessimplification.txt- detects over-engineeringtesting.txt- reviews test coverage and quality
Loading behavior: agents are loaded with per-file fallback: local .ralphex/agents/ → global ~/.config/ralphex/agents/ → embedded default. The 5 embedded agents are always the baseline — deleting an agent file from disk does not disable it, the embedded version is used as fallback. To disable a specific agent, remove its {{agent:name}} reference from the prompt files (review_first.txt, review_second.txt), not the agent file itself.
Frontmatter options: Agent files support optional YAML frontmatter (--- delimited) for per-agent model and subagent type:
model: haiku|sonnet|opus|fable— Claude model for this agentagent: <type>— Claude Code Task tool subagent type (default:general-purpose)- Parsed by
parseOptions()inpkg/config/frontmatter.go, validated byOptions.Validate() - Full model IDs (e.g.
claude-sonnet-4-5-20250929) are normalized to short keywords (sonnet) - Invalid model values are dropped with a warning, falling back to defaults
Template variables: Prompt files support variable expansion via replacePromptVariables() in pkg/processor/prompts.go:
{{PLAN_FILE}}- path to plan file or fallback text{{PROGRESS_FILE}}- path to progress log or fallback text{{GOAL}}- human-readable goal (plan-based or branch comparison){{DEFAULT_BRANCH}}- detected default branch (main, master, origin/main, etc.), overridable via--base-refCLI flag ordefault_branchconfig option{{DIFF_INSTRUCTION}}- git diff command for current iteration (first:git diff main...HEAD, subsequent:git diff){{PREVIOUS_REVIEW_CONTEXT}}- previous review context block for external review iterations (empty on first iteration, formatted context on subsequent){{agent:name}}- expands to Task tool instructions for the named agent
Variables are also expanded inside agent content, so custom agents can use {{DEFAULT_BRANCH}} etc.
Customization:
- Edit files in
~/.config/ralphex/agents/to modify agent prompts - Add new
.txtfiles to create custom agents - Run
ralphex --initto create local.ralphex/project config with commented-out defaults - Run
ralphex --resetto interactively restore defaults, or delete ALL.txtfiles manually - Run
ralphex --dump-defaults <dir>to extract raw embedded defaults for comparison or merging - Use
/ralphex-updateskill for smart merging of updated defaults into customized configs - Use
/ralphex-adoptskill to convert plans from other formats (OpenSpec, spec-kit, GitHub/GitLab issues, task-lists, free-form markdown) into ralphex format - Alternatively, reference agents installed in your Claude Code directly in prompt files (like
qa-expert,go-smells-expert)
Testing
go test ./... # run all tests
go test -cover ./... # with coverageWeb UI E2E Tests
Playwright-based e2e tests for the web dashboard are in e2e/ directory:
# install playwright browsers (first time only)
go run github.com/mxschmitt/playwright-go/cmd/playwright@latest install --with-deps chromium
# run web ui e2e tests
go test -tags=e2e -timeout=10m -count=1 -v ./e2e/...
# run with visible browser (for debugging)
E2E_HEADLESS=false go test -tags=e2e -timeout=10m -count=1 -v ./e2e/...Tests cover: dashboard loading, SSE connection and reconnection, phase sections, plan panel, session sidebar, keyboard shortcuts, error/warning event rendering, signal events (COMPLETED/FAILED/REVIEW_DONE), task and iteration boundary rendering, auto-scroll behavior, plan parsing edge cases.
End-to-End Testing
Unit tests mock external calls. After ANY code changes, ask the user before running an e2e test with a toy project because it can take time and consume claude/codex credits. Run it only after explicit approval to verify actual claude/codex integration and output streaming.
Create Toy Project
./scripts/internal/prep-toy-test.shThis creates /tmp/ralphex-test with a buggy Go file and a plan to fix it.
Test Full Mode
cd /tmp/ralphex-test
.bin/ralphex docs/plans/fix-issues.mdExpected behavior:
- Creates branch
fix-issues - Phase 1: executes Task 1, then Task 2
- Phase 2: first Claude review
- Phase 2.5: codex external review
- Phase 3: second Claude review
- Moves plan to
docs/plans/completed/
Test Review-Only Mode
cd /tmp/ralphex-test
git checkout -b feature-test
# make some changes
echo "// comment" >> main.go
git add -A && git commit -m "add comment"
# run review-only (no plan needed)
go run <ralphex-project-root>/cmd/ralphex --reviewTest Codex-Only Mode
cd /tmp/ralphex-test
# run codex-only review
go run <ralphex-project-root>/cmd/ralphex --codex-onlyMonitor Progress
# live stream (use actual filename from ralphex output)
tail -f .ralphex/progress/progress-fix-issues.txt
# recent activity
tail -50 .ralphex/progress/progress-*.txtDevelopment Workflow
CRITICAL: After ANY code changes to ralphex:
- Run unit tests:
make test - Run linter:
make lint - MUST ask the user before running the toy end-to-end test (see above); run it only after explicit approval
- Monitor
tail -f .ralphex/progress/progress-*.txtto verify output streaming works
Unit tests don't verify actual codex/claude integration or output formatting. The toy project test is the only way to verify streaming output works correctly.
Before Submitting a PR
If you're an AI agent preparing a contribution, complete this checklist:
Code Quality:
- Run
make test- all tests must pass - Run
make lint- fix all linter issues - Run
make fmt- code is properly formatted - New code has tests with 80%+ coverage
Project Patterns:
- Studied existing code to understand project conventions
- One
_test.gofile per source file (notfoo_something_test.go) - Tests use table-driven pattern with testify
- Test helper functions call
t.Helper() - Mocks generated with moq, stored in
mocks/subdirectory - Interfaces defined at consumer side, not provider
- Context as first parameter for blocking/cancellable methods
- Private struct fields for internal state, accessor methods if needed
- Regex patterns compiled once at package level
- Deferred cleanup for resources (files, contexts, connections)
- No new dependencies unless directly needed - avoid accidental additions
PR Scope:
- Changes are focused on the requested feature/fix only
- No "general improvements" to unrelated code
- PR is reasonably sized for human review
- Large changes split into logical, focused PRs
Self-Review:
- Can explain every line of code if asked
- Checked for security issues (injection, secrets exposure, etc.)
- Commit messages describe "why", not just "what"
Documentation Site (Zensical)
- Site source:
site/directory withmkdocs.yml(read natively by Zensical) - Builder:
zensical(replaced mkdocs-material;requirements.txtlists onlyzensical) - Landing page:
site/docs/index.htmlis a manually crafted HTML page, not generated by the SSG. Edit it directly to update the landing page. - Template overrides:
site/overrides/withcustom_dir: overridesin mkdocs.yml - Python version: Zensical requires Python ≥ 3.10. Local builds use a venv at
site/.venv/(auto-created bymake prep_site); Cloudflare Pages requiresPYTHON_VERSIONenv var ≥ 3.10 - Brand color: dark-mode palette uses Material's
tealkeyword, thensite/docs/stylesheets/extra.cssoverrides--md-primary-fg-color/--md-accent-fg-colorto#2dd4bf(Tailwind teal-400) so the docs match the landing page brand color - Raw .md files: SSG renders ALL
.mdfiles indocs_diras HTML pages. To serve raw markdown (e.g.,assets/claude/*.mdfor Claude Code skills), copy them AFTERzensical build- seeprep_sitetarget in Makefile
Testing Safety Rules
- CRITICAL: Tests must NEVER touch real user config directory (
~/.config/ralphex/) - All tests MUST use
t.TempDir()for any file operations - Config pollution is hard to debug - corrupted files cause cryptic errors
- Verify tests are clean: compare MD5 checksums of config files before/after
go test ./...
Workflow Rules
- Plugin version: bump
.claude-plugin/plugin.jsonand.claude-plugin/marketplace.jsonversions on release if skill files (assets/claude/) changed since last plugin version bump - CHANGELOG: Never modify during development - updates are part of release process only
- Version sections: Never add entries to existing version sections - versions are immutable once released
- Linter warnings: Add exclusions to
.golangci.ymlinstead of_, _ =prefixes for fmt.Fprintf/Fprintln - Exporting functions: When changing visibility (lowercase to uppercase), check ALL callers including test files
- Completed plans are immutable: Plans in
docs/plans/completed/represent historical record of changes. Never modify completed plans. If further changes are needed (refactoring, fixes, etc.), create a new plan
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

