ralphex

repository·master·Indexed 23 days ago

https://github.com/umputun/ralphex

An autonomous task execution engine and CLI tool that orchestrates coding agents such as Claude Code or codex to implement software features via structured markdown plans. It automates branch creation, task execution in fresh sessions to prevent context degradation, multi-phase code reviews, and commits. It supports isolated execution via git worktrees and Docker, and can integrate with AWS Bedrock.

Tokens
63.6K
Snippets
113
Records
340
Agent score
79%

What's inside ralphex

  1. Overview of ralphex

    master

    ralphex is a standalone CLI tool designed for autonomous plan execution using coding agents like Claude Code or codex. It runs from the root of a git repository and orchestrates complex implementation plans by breaking them into individual tasks.

    Unlike interactive sessions that can suffer from context degradation, ralphex executes each task in a fresh session with minimal context, ensuring the model remains sharp. It automates branch creation, task execution, multi-phase code reviews, and commits after each successful step.

  2. Use codex-as-claude to replace Claude Code in ralphex

    master
    The codex-as-claude script wraps the Codex CLI to produce Claude-compatible stream-json output. This allows the Codex CLI to function as a drop-in replacement for Claude Code during ralphex task and review phases by making Codex events compatible with ralphex's ClaudeExecutor.
  3. Monitor multiple ralphex sessions via the Web Dashboard

    master

    The ralphex web dashboard can be used to monitor multiple concurrent sessions by decoupling the dashboard from a single plan execution. The dashboard discovers active and completed sessions by scanning for progress-*.txt files.

    Key Capabilities:

    • Session Discovery: Automatically detects sessions via progress files.
    • State Detection: Uses file locking (flock) to distinguish between active (running) and completed sessions.
    • Real-time Streaming: Streams log lines from active sessions using file tailing.
    • Watch Mode: Supports recursive monitoring of directories to automatically discover new sessions as they start.
  4. Use Custom scripts for notifications

    master

    The custom channel allows you to pipe the full execution Result as a JSON object to a script on stdin. This is useful for integrating with any service that accepts JSON.

    Script Requirements:

    • Receives Result JSON on stdin.
    • Exit code 0 is treated as success; non-zero is treated as failure (logged as a warning).
    • The script's execution is subject to notify_timeout_ms.

    JSON Schema received by script:

    {
      "status": "success",
      "mode": "full",
      "plan_file": "docs/plans/add-auth.md",
      "branch": "add-auth",
      "duration": "12m 34s",
      "files": 8,
      "additions": 142,
      "deletions": 23
    }

    Note: The error field is only present when status is failure.

    notify_channels = custom
    notify_custom_script = ~/.config/ralphex/scripts/notify.sh
  5. Rules for valid ralphex plan files

    master

    All converted plans must strictly follow these structural rules to be compatible with the ralphex parser:

    • H1 Title: The file must start with # <Plan Title>.
    • Standard Sections: Sections must appear in this order:
      1. ## Overview
      2. ## Context
      3. ## Development Approach
      4. ## Testing Strategy
      5. ## Progress Tracking
      6. ## Technical Details (optional)
      7. ## Implementation Steps
      8. ## Post-Completion (optional)
    • Task Headers: Use the exact English format ### Task <N>: <title>. The keyword Task must be English, even if the rest of the plan is in another language.
    • Checkboxes: Use - [ ] or - [x]. These must appear only inside Task sections. Placing checkboxes in other sections (like Overview or Context) will cause the executor to incorrectly spawn extra iterations.
    • Mandatory Task Endings: Every Task must end with two specific checkboxes:
      • - [ ] write tests
      • - [ ] run project tests
    • Final Task: The last task must always be ### Task <last>: Verify acceptance criteria, which includes items to re-run the test suite, run the linter, and confirm requirements from the Overview.
  6. Behavior of ModeTasksOnly regarding branches and plans

    master

    When running in --tasks-only mode, ralphex behaves similarly to ModeFull regarding workspace management:

    • Branch Creation: A new branch is created because the task phase involves making commits.
    • Plan Management: Upon successful completion of the task phase, the plan file is automatically moved to the completed/ directory.
  7. How the Mercurial (hg) backend works via hg2git.sh

    master

    When using a Mercurial backend via a wrapper script like hg2git.sh, ralphex follows a 'single-diff model' using Mercurial's phases to mimic Git's branching and committing behavior:

    1. Branch Detection: ralphex uses symbolic-ref --short HEAD. The script maps the Mercurial phase to a branch name:
      • public phase $\rightarrow$ returns master (signals ralphex to create a new branch).
      • draft phase $\rightarrow$ returns the bookmark name or draft (signals ralphex to skip branch creation as it is already working on an unsent commit).
    2. Committing Logic:
      • The first commit from a public state triggers hg commit -m "msg", creating a new draft commit.
      • All subsequent commit calls trigger hg amend [files...]. This allows a single commit to grow with each task in a plan execution.
    3. Status Conversion: The script must convert Mercurial's 1-character status to Git's 2-character XY porcelain format (e.g., padding the single char) so that extractPathFromPorcelain() in the Go backend can parse it correctly.
  8. Maintain public API compatibility when refactoring Config

    master

    When refactoring pkg/config, ensure that you do not break the public API shape for external Go callers.

    Even if you introduce embedded sub-structs for internal organization, certain pattern fields (like error patterns) must remain flat exported fields on both Values and Config. This ensures that external code using composite literals like config.Config{ClaudeErrorPatterns: ...} continues to compile and function without modification.

  9. Architecture of the Processor Runner and Phase Engines

    master

    The ralphex processor execution is orchestrated by a Runner that coordinates a pipeline of specialized Phase Engines.

    Core Components

    • pkg/processor.Runner: Acts as a pipeline coordinator. It manages mode selection and phase ordering but does not own the specific logic for each phase. It holds unexported phase interfaces.
    • Phase Engines: Concrete types located in pkg/processor/phase. They implement specific stages of the execution lifecycle.
    • phase.Deps: A mechanism for handling dependencies that are set after construction (late-bound). Phases read from this holder at runtime, allowing the Runner to update dependencies via setters without causing nil pointer errors or requiring phases to call back into the Runner.
    • executionPolicy: A service that handles shared executor behavior, including runWithLimitRetry, runWithSessionTimeout, and idle-timeout tracking.
    • promptBuilder: A service that handles prompt rendering. Phases request final prompts from this builder rather than managing template replacement details themselves.
    • planLocator: Manages plan path resolution, shared by the promptBuilder and task-phase plan state checks.

    Dependency Injection and Lifecycle

    • Production: Standard constructors like New and NewWithExecutors build the Runner with default concrete phase engines.
    • Testing: A test-only phase injection helper is exposed via export_test.go to allow orchestration tests to inject mock phases.
    • Post-Construction Setters: The Runner supports existing setters that affect already-constructed runners:
      • SetInputCollector
      • SetGitChecker
      • SetBreakCh
      • SetPauseHandler
  10. How task numbering works in the web dashboard

    master

    The Ralphex web dashboard uses position-based matching to highlight tasks. Instead of relying on the integer number found in markdown headers (which can fail if tasks are non-integers like Task 2.5 or if the plan is edited mid-run), the system uses the task's 1-indexed position in the plan array.

    Data Flow:

    1. Plan Parsing: plan.ParsePlanFile() converts the markdown plan into a slice of Task objects.
    2. Runner Execution: The runner calls nextPlanTaskPosition() to find the 1-indexed position of the first task where status != TaskStatusDone.
    3. Event Broadcasting: The runner passes this position to NewTaskIterationSection(pos), which the BroadcastLogger includes in events as TaskNum.
    4. Frontend Rendering: The dashboard renders task elements with a data-task-num attribute corresponding to their position (index + 1). When a task starts, the frontend matches the incoming task_num against these elements to apply highlighting.
  11. How the Plan Draft Preview works

    master

    The Plan Draft Preview introduces a feedback loop during plan creation. Instead of Claude writing a plan file directly to disk, it emits a PLAN_DRAFT signal. This allows the user to review the proposed plan in the terminal before any files are actually changed.

    The Workflow

    1. Draft Generation: Claude generates a plan and wraps it in the PLAN_DRAFT signal markers.
    2. User Review: The plan is rendered in the terminal (using glamour for markdown styling).
    3. User Action: The user chooses one of three actions:
      • Accept: The plan is approved, and Claude proceeds to write the files and emit PLAN_READY.
      • Revise: The user provides free-form feedback. This feedback is logged to the progress file, and Claude is re-run with the feedback context to generate a new draft.
      • Reject: The process exits gracefully with an error, indicating the user rejected the plan.

    Signal Format

    Claude uses the following format to trigger the preview:

    <<<RALPHEX:PLAN_DRAFT>>>
    # Plan Title
    
    ## Overview
    ...
    
    ## Tasks
    ...
    <<<RALPHEX:END>>>