agentleFS
umputunumputun/ralphex/CLAUDE.md

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

Dec 2025: 0 mentionsJan 2026: 0 mentionsFeb 2026: 0 mentionsMar 2026: 0 mentionsApr 2026: 1 mentionMay 2026: 2 mentionsJun 2026: 5 mentionsJul 2026: 3 mentionsAug 2026: 4 mentionsSep 2026: 5 mentionsOct 2026: 4 mentionsNov 2026: 0 mentions
Dec 2025Jun 2026Nov 2026
Mentions a month of the umputun/ralphex repository that our weekly crawl found. There is no adoption data for this file yet.

Who's talking about umputun/ralphex

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

19 more on GitHub
  • In this repositoryOne other file it gives its agents.

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
  1. Distinctive:

    Use jessevdk/go-flags for CLI parsing

    line 59
  2. Distinctive:

    All comments lowercase except godoc

    line 60
  3. Very specific:

    Every timeout here passes -k "$CLI_KILL_GRACE".

    line 153
  4. Very specific:

    All git operations are methods on Service (CreateBranchForPlan, CreateWorktreeForPlan, MovePlanToCompleted, EnsureLocalGitignore, etc.)

    line 164
  5. Very specific:

    Only active for ModeFull and ModeTasksOnly (review/plan/external modes skip worktree)

    line 185
  6. Very specific:

    When ready, Claude emits PLAN_DRAFT signal with full plan content for user review

    line 202
  7. Distinctive:

    If revised (manually or via interactive review), feedback is passed to Claude for plan modifications

    line 205
  8. Distinctive:

    After completion, prompts user: "Continue with plan implementation?"

    line 208
  9. Distinctive:

    If "Yes", creates branch and runs full execution mode on the new plan

    line 209
  10. Distinctive:

    When adding platform-specific code (syscalls, signals, file locking):

    line 237
  11. Very specific:

    Use build tags: //go:build !windows for Unix-only code, //go:build windows for Windows stubs

    line 238
  12. Very specific:

    Create separate files: foo_unix.go and foo_windows.go

    line 239
  13. Distinctive:

    Keep common code in the main file, extract platform-specific functions

    line 240
  14. Very specific:

    Fallback loading: when loading config/prompts/agents, if file content is all-commented (no actual values), embedded defaults are used

    line 298
  15. Very specific:

    Add new .txt files to create custom agents

    line 368
  16. Very specific:

    Run ralphex --init to create local .ralphex/ project config with commented-out defaults

    line 369
  17. Very specific:

    Run ralphex --reset to interactively restore defaults, or delete ALL .txt files manually

    line 370
  18. Very specific:

    Run ralphex --dump-defaults <dir> to extract raw embedded defaults for comparison or merging

    line 371
  19. Very specific:

    Use /ralphex-update skill for smart merging of updated defaults into customized configs

    line 372
  20. Very specific:

    Use /ralphex-adopt skill to convert plans from other formats (OpenSpec, spec-kit, GitHub/GitLab issues, task-lists, free-form markdown) …

    line 373
  21. Very specific:

    Run unit tests: make test

    line 464
  22. Distinctive:

    MUST: ask the user before running the toy end-to-end test (see above).

    line 466
  23. Distinctive:

    If you're an AI agent preparing a contribution, complete this checklist:

    line 473
  24. Very specific:

    All tests MUST use t.TempDir() for any file operations

    line 518
  25. Very specific:

    Verify tests are clean: compare MD5 checksums of config files before/after go test ./...

    line 520
  26. Distinctive:

    CHANGELOG: Never modify during development - updates are part of release process only

    line 525
  27. Distinctive:

    Version sections: Never add entries to existing version sections - versions are immutable once released

    line 526
  28. Very specific:

    Linter warnings: Add exclusions to .golangci.yml instead of _, _ = prefixes for fmt.Fprintf/Fprintln

    line 527
  29. Distinctive:

    Exporting functions: When changing visibility (lowercase to uppercase), check ALL callers including test files

    line 528

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

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 code

Updating 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-vendor

Project 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 location

Code 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=value form 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:). The Task / Iteration keywords are structural tokens matched by pkg/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.txt does not ask the LLM to git mv the plan into completed/ — the framework calls MovePlanToCompleted at end-of-run idempotently using r.cfg.PlanFile's exact basename. (b) planLocator.Path (pkg/processor/plan_locator.go) and MovePlanToCompleted (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 under completed/; the in-place alternate is probed before the completed/ paths so a current renamed file wins over a stale completed copy. MovePlanToCompleted also treats an alternate-named file in the original directory as the move source. TaskPhase.HasUncompletedTasks (pkg/processor/phase/task.go) treats fs.ErrNotExist from ParsePlanFile as "no uncompleted tasks" rather than "assume incomplete".
  • Signal-based completion detection (COMPLETED, FAILED, REVIEW_DONE signals) — constants in pkg/status/
  • Processor phase architecture: Runner in pkg/processor/runner.go coordinates mode sequencing only. Task, internal review, external review, finalize, and plan creation behavior lives in pkg/processor/phase and is injected through consumer-side interfaces in pkg/processor. Shared prompt rendering, executor retry/timeout policy, and plan location stay in pkg/processor; break handling and git snapshots are phase-owned shared support. Keep new phase behavior out of Runner; preserve late-bound setters through phase.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 in RefreshStates that can prematurely mark a running session completed. Session.Reactivate() is idempotent and scoped to the written path; loadProgressFileIntoSession records lastOffset after 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 a Failed: footer (written by Logger.SetFailed before Close) or with no footer preserve content and write a --- restarted at ... --- separator, so retried failed/aborted runs keep history. SetFailed is called in cmd/ralphex/main.go for r.Run errors (including ErrUserAborted), dashboard start errors, and errors from runWithWorktree
  • Completed-log archiving (#447): archiveAndTruncateCompleted (pkg/progress/progress.go) copies the completed log to .ralphex/progress/history/<stem>/archive-<YYYYMMDD-HHMMSS>-<token>.txt before truncating the canonical file, so a repeated --review no longer destroys the previous transcript. The copy is read from the still-locked fd through an io.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 own Completed: footer, not the archiving moment. The archive basename deliberately carries an archive- marker and no progress- prefix: isProgressFile (pkg/web/watcher.go) matches progress-*.txt and DiscoverRecursive walks the whole tree with skipDirs covering neither .ralphex nor history, so a prefixed archive would be discovered and replayed as a dashboard session of its own. pruneProgressArchives matches only archiveNameRegex, so foreign files and in-flight .tmp archives 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 is maxProgressRuns (10) total per canonical path — the live file plus 9 archives — and pruning is best effort: a removal failure warns through Logger.Warn after the header is written (so it lands in the new run's log) and lets the run continue, because every NewLogger caller treats an error as fatal and removing an open file fails on Windows. removeProgressArchive and truncateProgressFile are test seams for the failure paths
  • --codex is an executor switch (not a new pipeline mode): sets cfg.Executor = config.ExecutorCodex so task, both reviews, and finalize run through CodexExecutor(s) with MultiAgent=true (enables features.multi_agent, registers the reviewer agent for spawn_agent calls). Forces cfg.ExternalReviewTool = "none" (codex-reviewing-codex is weak-signal self-review). --pass-claude-md (codex executor only) sets CodexExecutor.PassClaudeMd = true. The Mode enum is unchanged; the Executors struct uses role-named fields (Task/Review/External/Custom), and buildCodexExecutors wires one codex instance into both Task and Review when the resolved review model/effort matches task, or two distinct instances when they differ. Review prompts are shared with claude — the {{agent:<name>}} expansion in pkg/processor/prompts.go reads cfg.AppConfig.Executor and emits Use the Task tool (claude) or spawn_agent(agent='reviewer', task='...') (codex). Codex config is passed as additive -c overrides per invocation by (*CodexExecutor).configOverrides() in pkg/executor/codex.go, layered on top of the user's ~/.codex/config.toml so user customizations are preserved. ralphex never writes to ~/.codex/; for user-level CLAUDE.md it prints a one-time hint to ln -s ~/.claude/CLAUDE.md ~/.codex/AGENTS.md
  • Shared reviewer contract: reviewContextInstruction (pkg/processor/prompts.go) is prepended by formatAgentExpansion to every {{agent:<name>}} body, for both executors and for local/global/embedded agent files alike. It supplies WHERE (the git diff {{DEFAULT_BRANCH}}...HEAD lead-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 the NO ISSUES FOUND sentinel. 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 in review_first.txt/review_second.txt reaches 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 — expandAgentReferences runs inside replacePromptVariables, so an {{agent:}} reference placed in task.txt or finalize.txt would carry the contract too; the embedded prompts reference agents only from review_first.txt and review_second.txt. The separate Report findings only - no positive observations. line is not part of the contract — it lives in formatAgentExpansionClaude/formatAgentExpansionCodex
  • Codex review-phase directives: prependCodexReviewGuidance (pkg/processor/prompts.go) injects a === Codex orchestration directives === block through promptBuilder.FirstReviewPrompt and promptBuilder.SecondReviewPrompt when cfg.isCodexExecutor() is true (no-op for claude). Covers two codex multi_agent quirks: (a) spawn_agent must pass only agent and task — fork_context=true with explicit agent_type is rejected by the codex API; (b) on a wait_agent timeout 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.ReviewPhase consumes the final prompts.
  • Codex task-phase skill-conflict directive: prependCodexTaskGuidance (pkg/processor/prompts.go) injects the === Codex task-execution directives === block (codexTaskGuidance) through promptBuilder.TaskPrompt when cfg.isCodexExecutor() is true (no-op for claude). phase.TaskPhase consumes 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-json equivalent, 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.Run extracts the session id from the stderr header banner (extractSessionID + buffered sessionIDCh) and spawns tailRolloutFile to follow it. formatRolloutEvent forwards two rollout record types: assistant message text (formatAssistantMessage) and reasoning-summary titles (formatReasoningSummary, **-stripped). function_call and custom_tool_call_output records 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 typed reasoning records never carry that echo. tailCtx is canceled after stdout EOF so the tailer drains once more and exits
  • Codex stderr filtering: shouldDisplay (pkg/executor/codex.go) forwards ONLY codex's resolved model:/sandbox:/reasoning effort: header lines, and only on the executor's first Run() 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) emits sandbox: (and model: / reasoning effort: when codex_model / codex_reasoning_effort are set; empty values skipped)
  • Claude subagent progress: newer Claude Code streams Task-tool subagent activity as system events with subtype task_started/task_progress (no text block, so extractText drops 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 via subagentLine and forwards it to OutputHandler only (not into output/recentText/signal or the diagnostics window). Only the description is shown — the subagent type and tool name are deliberately omitted: stock config runs every review agent as general-purpose so a [general-purpose] prefix would be pure noise (only user-customized agents with agent: 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 per subagentProgressInterval (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 to time.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. /smells on a small change) does its Read/Bash tool calls in the main session with no task_* 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. Nested claude/codex launched 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 (subagent system/task_* events, parent_tool_use_id); codex exec --sandbox read-only stderr (header banner, **bold** reasoning, exec output echo) plus its rollout file at ~/.codex/sessions/<y>/<m>/<d>/rollout-*-<session-id>.jsonl (typed reasoning / message / custom_tool_call_output records — the clean source of truth). Gate this whole approach on AGTERM_ENABLED (only usable when running inside agterm)
  • --plan-model/--task-model/--review-model resolve per-phase model/effort. plan_model falls back to task_model; review_model falls back to task_model. Claude mode injects --model/--effort into claude_command. Codex mode: ResolveCodexModelEffort (pkg/processor/executor_factory.go) resolves the model[:effort] spec against codex_model/codex_reasoning_effort defaults; buildCodexExecutors builds a separate review CodexExecutor when review differs from task. max effort does not exist in codex — kept default, maxDropped reported, 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 modes
  • pkg/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: first git diff main...HEAD, subsequent git diff (uncommitted only)
  • max_external_iterations 0 = auto, max(3, max_iterations/5)
  • review_patience stalemate 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 --codex session_timeout covers 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 = false backward compat: treated as external_review_tool = none

Key files:

  • pkg/executor/custom.go - CustomExecutor for running external scripts
  • pkg/config/defaults/prompts/codex_review.txt / custom_review.txt / custom_eval.txt - external review prompts
  • pkg/processor/prompts.go and pkg/processor/prompt_builder.go - getDiffInstruction(), buildPreviousContext(), prompt assembly
  • pkg/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_ARGS Copilot wrapper: native autopilot mode — --autopilot --no-ask-user --allow-all for task/review, --autopilot --allow-all for plan runs (so QUESTION signals surface). pi wrapper: line-buffers pi's token-level text deltas so <<<RALPHEX:...>>> signals land intact in one content_block_delta; suppressed events emit empty keepalive deltas so idle_timeout doesn'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 interruptible wait so 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 var
  • build_bedrock_env_args() - builds docker -e flags for BEDROCK_ENV_VARS
  • export_aws_profile_credentials() - exports credentials from AWS profile
  • validate_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 and RALPHEX_DOCKER_SOCKET env var
  • resolve_docker_socket() - resolves socket path from DOCKER_HOST or default
  • get_docker_socket_gid() - detects socket file GID via os.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.)
  • Logger interface for dependency injection, compatible with *color.Color
  • Uses backend interface internally, implemented by externalBackend which shells out to the configured VCS command
  • Optional vcsCmd parameter overrides the default "git" command (e.g., path to hg2git.sh translation script)
  • MovePlanToCompleted commits through commitFiles (pathspec-restricted), never the bare commit. 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 into move 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 through git mv, which stages the source deletion; the os.Rename fallback 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. An os.Lstat(destPath) immediately before that os.Rename refuses the move when completed/<basename> is already there: git mv declines an existing destination but os.Rename replaces it silently, and an uncommitted archive copy has no other copy anywhere. resolvePlanMoveTargets therefore returns done=true only when the source is gone and a completed/ copy proves the plan already archived — a source that still exists returns done=false whatever sits in completed/, so the collision reaches the move path and errors instead of passing for a successful archive (the caller reads done as 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 a WARN: through the progress logger, so the progress file keeps it where the previous bare stderr write left no trace, and as a plan 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 --serve run does not, because live SSE events come from BroadcastLogger and web.Logger carries no Warn. A rejected archive commit (e.g. a commit-msg hook enforcing conventional commits, #439) leaves the staged rename in the tree, and the WARN lands after the runner's all phases completed successfully and 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 - Service type, backend interface
  • pkg/git/external.go - VCS CLI backend (externalBackend type)

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 by worktreePlanFile() before the logger is built. handleSessionPlan (pkg/web/server.go) serves the worktree copy while it exists and falls back to Plan: 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 by parseHeaderField, 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 uses req.GitSvc/req.PlanFile, which in worktree mode are the worktree's service and the ticked copy, so move 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 unticked completed/ 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's planNote), since the path alone stops resolving the moment the worktree is removed. Ordering matters and is not what it first looks like: DiffStats runs before the archive and sendNotification after it. Taking the stats afterwards double-counts the plan under diff.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, -M does 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. archivePlan sets req.WtPreserve (an atomic.Bool, read from the interrupt watcher's goroutine) and cleanupWorktree then restores CWD but skips RemoveWorktree; the closure installed in WtCleanup is the same one, so the 5-second force-exit path cannot delete it either. Without this, git worktree remove --force would 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 says git -C <root> status, because a bare git status after 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's worktreeMode flag 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 by copyToWorktree. A new feature branch starts at the current HEAD; an existing feature branch keeps its own tip. Local .ralphex configuration is loaded before worktree creation and still applies. Unfinished Git operations are a hard error in worktree mode; externalBackend.operationInProgress detects merge, cherry-pick, revert, rebase, am, and bisect state through git 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 ModeFull and ModeTasksOnly (review/plan/external modes skip worktree)
  • runWithWorktree() in cmd/ralphex/main.go encapsulates the full lifecycle
  • Case-insensitive path handling: CreateBranchForPlan(), CreateWorktreeForPlan(), and CommitPlanFile() resolve plan file paths to actual on-disk case via resolveFilesystemCase() 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 cleanup
  • pkg/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 $EDITOR with 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 helpers
  • pkg/processor/signals.go - processor compatibility wrappers around phase signal helpers
  • pkg/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 -p flag) to avoid the cmd.exe 8191-character command-line limit

Cross-Platform Development

When adding platform-specific code (syscalls, signals, file locking):

  1. Use build tags: //go:build !windows for Unix-only code, //go:build windows for Windows stubs
  2. Create separate files: foo_unix.go and foo_windows.go
  3. Keep common code in the main file, extract platform-specific functions
  4. Windows stubs can be no-ops where functionality is optional

Example files:

  • pkg/executor/procgroup_unix.go / procgroup_windows.go - process group management
  • pkg/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-dir or RALPHEX_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/*.txt or .ralphex/prompts/*.txt
  • Custom agents: ~/.config/ralphex/agents/*.txt or .ralphex/agents/*.txt
  • plan_model / task_model / review_model config options: model[:effort] for plan creation / task / review phases; plan_model and review_model fall back to task_model. CLI flags --plan-model/--task-model/--review-model take 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_branch config option: override auto-detected default branch for review diffs
  • max_iterations config option: override CLI default (50) for maximum task iterations per plan (CLI flag --max-iterations takes precedence)
  • vcs_command config 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. See docs/hg-support.md
  • commit_trailer config 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-specific notify_* fields (see docs/notifications.md)
  • review_patience config option: terminate external review after N consecutive unchanged rounds (0 = disabled). CLI flag --review-patience takes precedence
  • wait_on_limit config option: duration to wait before retrying on rate limit (e.g., "1h", "30m"). CLI flag --wait takes precedence. Disabled by default
  • session_timeout config 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 in retryPolicy.runWithSessionTimeout via context.WithTimeout, gated on Executor==ExecutorCodex || toolName=="claude". CLI flag --session-timeout takes precedence. Disabled by default
  • idle_timeout config 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 in ClaudeExecutor.Run()/CodexExecutor.Run() via time.AfterFunc. Wired by buildCodexExecutor for first-class --codex; NOT by buildExternalCodexExecutor, so external codex review in default-claude mode has no idle timeout. Custom external review unaffected. CLI flag --idle-timeout takes precedence. Disabled by default
  • move_plan_on_completion config option: controls whether completed plans move to docs/plans/completed/ on success. Default true. Disable for workflows that manage plan lifecycle externally (spec-driven tooling with separate archive steps)
  • preserve_anthropic_api_key config option / --preserve-anthropic-api-key CLI flag: when true, ANTHROPIC_API_KEY is passed through to the child claude process (needed for API-key auth rather than OAuth/keychain). Default false strips the key. The merge sentinel PreserveAnthropicAPIKeySet lives only on Values (load-bearing for local-overrides-global merge); Config carries 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 emits auth: ANTHROPIC_API_KEY passthrough enabled. Claude Code's per-session markers (CLAUDECODE, CLAUDE_CODE_SESSION_ID, CLAUDE_CODE_MESSAGING_SOCKET and the rest of sessionEnvVars in pkg/executor/executor.go) are always stripped regardless of this setting, which prevents nested-session errors. Marker names are matched exactly, so configuration variables such as CLAUDE_CODE_USE_BEDROCK are 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 agent

Merge 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 # Title at the top is preserved (treated as markdown header, not meta-comment). Full stripComments is only used for emptiness detection to trigger fallback
  • scalars/colors: per-field fallback to embedded defaults if missing
  • *Set flags (e.g., CodexEnabledSet) distinguish explicit false/0 from "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 in llms.txt). Codex phrases are tightened so review findings that talk about rate limiting do not trip a false positive. The claude error set enumerates API 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 transient 529/502/503/504 codes are handled by claude_retry_patterns, not here
  • Matching is case-insensitive substring search
  • Whitespace is trimmed from each pattern
  • For claude: parseStream separates complete surfaced Output, bounded recent surfaced RecentText, and bounded trusted DiagnosticText. 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. A result record counts as diagnostic when it authenticates itself as an error (is_error:true, terminal_reason:"api_error", or a non-zero api_error_status) — a bare terminal_reason does not qualify, because a successful result can carry one. subtype is never consulted: Claude Code has been observed emitting subtype:"success" on a genuine rate-limit result (anthropics/claude-code#79500). system/api_retry is excluded entirely — it reports an attempt, not an outcome, and Claude often recovers from one
  • Claude patterns always check DiagnosticText. Surfaced RecentText is 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.txt path B stays silent after fixing issues, task.txt emits ALL_TASKS_DONE only 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 no is_error field 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.DiagnosticText makes the exact classified window available to executor callers and tests; Result.Output and 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 processStderr before the 5-line / 256-rune tail truncation, so detection is eviction- and truncation-resistant. The scan is gated by isCodexErrorLine (matches error:/fatal:/panic: prefix, case-insensitive) so progress chatter cannot trigger false positives. The first matching limit/error pattern per category is recorded on stderrResult.{limitMatch,errorMatch} and consumed by CodexExecutor.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 in claude_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 enumerated API Error: 500 error 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 fixed retryBackoff (5s, defined in pkg/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.Signal is 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 and llms.txt)
  • wait_on_limit: duration string (e.g., "1h", "30m"), disabled by default
  • --wait CLI flag overrides wait_on_limit config
  • 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_limit acts as the toggle

Implementation:

  • PatternMatchError type in pkg/executor/executor.go with Pattern and HelpCmd fields
  • LimitPatternError type in pkg/executor/executor.go with Pattern and HelpCmd fields
  • RetryPatternError type in pkg/executor/executor.go with a Pattern field
  • matchPattern() 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/RetryPatterns and CodexExecutor.ErrorPatterns/LimitPatterns (codex has no retry patterns)
  • retryPolicy.Run() in pkg/processor/execution_policy.go wraps 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 goals
  • quality.txt - reviews for bugs, security issues, race conditions
  • documentation.txt - checks if docs need updates
  • simplification.txt - detects over-engineering
  • testing.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 agent
  • agent: <type> — Claude Code Task tool subagent type (default: general-purpose)
  • Parsed by parseOptions() in pkg/config/frontmatter.go, validated by Options.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-ref CLI flag or default_branch config 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 .txt files to create custom agents
  • Run ralphex --init to create local .ralphex/ project config with commented-out defaults
  • Run ralphex --reset to interactively restore defaults, or delete ALL .txt files manually
  • Run ralphex --dump-defaults <dir> to extract raw embedded defaults for comparison or merging
  • Use /ralphex-update skill for smart merging of updated defaults into customized configs
  • Use /ralphex-adopt skill 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 coverage

Web 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.sh

This 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.md

Expected behavior:

  1. Creates branch fix-issues
  2. Phase 1: executes Task 1, then Task 2
  3. Phase 2: first Claude review
  4. Phase 2.5: codex external review
  5. Phase 3: second Claude review
  6. 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 --review

Test Codex-Only Mode

cd /tmp/ralphex-test

# run codex-only review
go run <ralphex-project-root>/cmd/ralphex --codex-only

Monitor Progress

# live stream (use actual filename from ralphex output)
tail -f .ralphex/progress/progress-fix-issues.txt

# recent activity
tail -50 .ralphex/progress/progress-*.txt

Development Workflow

CRITICAL: After ANY code changes to ralphex:

  1. Run unit tests: make test
  2. Run linter: make lint
  3. MUST ask the user before running the toy end-to-end test (see above); run it only after explicit approval
  4. Monitor tail -f .ralphex/progress/progress-*.txt to 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.go file per source file (not foo_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 with mkdocs.yml (read natively by Zensical)
  • Builder: zensical (replaced mkdocs-material; requirements.txt lists only zensical)
  • Landing page: site/docs/index.html is a manually crafted HTML page, not generated by the SSG. Edit it directly to update the landing page.
  • Template overrides: site/overrides/ with custom_dir: overrides in mkdocs.yml
  • Python version: Zensical requires Python ≥ 3.10. Local builds use a venv at site/.venv/ (auto-created by make prep_site); Cloudflare Pages requires PYTHON_VERSION env var ≥ 3.10
  • Brand color: dark-mode palette uses Material's teal keyword, then site/docs/stylesheets/extra.css overrides --md-primary-fg-color / --md-accent-fg-color to #2dd4bf (Tailwind teal-400) so the docs match the landing page brand color
  • Raw .md files: SSG renders ALL .md files in docs_dir as HTML pages. To serve raw markdown (e.g., assets/claude/*.md for Claude Code skills), copy them AFTER zensical build - see prep_site target 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.json and .claude-plugin/marketplace.json versions 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.yml instead 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

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.