pentoai/ml-ralph
Sobre
Autonomous ML agent for running experiments using Claude.
Ferramentas de desenvolvimentoCrescimento medido de estrelas
- em 24 h
- 0
- em 7 dias
- 0
- em 15 dias
- +2
- em 1 mês
- Coletando histórico
Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.
README.md
Originalml-ralph
An autonomous ML research loop that does not take the agent's word for its results. ml-ralph runs the experiment loop in the background (planning, execution, analysis, learning extraction) and scores, reviews and gates every result itself.
You operate it from the CLI, from any MCP client (Claude Code, pi, an IDE) or in a small TUI. All three call the same operations, and the run is a background process: it keeps going when you disconnect.
Getting started
cd my-ml-project # a git repository with at least one commit
bunx @pentoai/ml-ralph init
bunx @pentoai/ml-ralph status
status prints a setup checklist and the one thing to do next. A project is ready when it has:
- a PRD in
.ml-ralph/prd.json(problem, goal, success criteria); - an eval contract:
.ml-ralph/eval/evaluate.pyand.ml-ralph/eval/contract.json(metric, seeds, thresholds, baseline score); - your approval:
ml-ralph approve; - optionally, a sealed holdout outside the project (
ml-ralph holdout set <path>) and budget caps. Without a holdout a run can promote candidates but never complete.
ml-ralph manual explains each step. Then:
ml-ralph start --max-iterations 10 # runs in the background
ml-ralph status # state, iteration, budget, next step
ml-ralph results # runner-verified scores and promotions
ml-ralph logs --follow # the agent's output
ml-ralph stop # ends the run and writes the report
ml-ralph continue # starts the last run again with its settings and the iterations it had left
ml-ralph tui # live view with the same actions
ml-ralph board <snapshot.json>... # one static page tracking several runs
ml-ralph submit # send the incumbent to Kaggle, keep the score from the agent
Let your agent operate it (MCP)
ml-ralph mcp is an MCP server on stdio, built on the MCP TypeScript SDK v2 (@modelcontextprotocol/server). It speaks the current spec revision (2026-07-28) and still serves clients that only speak the 2025 revisions. Register it once and ask your agent to set the project up, start a run and report back:
claude mcp add ml-ralph -- bunx @pentoai/ml-ralph mcp
| Tools | status, init, approve, set_holdout, start, stop, hint, results, events, output, report, jobs, stop_job, tail_job, resolve_contract_change |
| Resources | ml-ralph://manual, status, results, prd, contract, conclusions, kanban, report |
| Prompts | setup, monitor, report |
Tool inputs are typed (zod schemas published as JSON Schema), and read-only tools are annotated as such. Every tool takes an optional project_path; the default is the directory the server was started in (or --project <path>). The agent you operate ml-ralph with is the operator; the research itself is done by a separate Claude Code session the runner spawns. Control commands and tools (start, stop, approve, holdout set, hint, contract) are refused inside that research session.
Requirements
- Bun v1.0+
- git, and Python for your
evaluate.py - Claude Code CLI, installed and authenticated (it is the research agent)
How it is put together
CLI commands ─┐
MCP server ──┼─► operations ─► run store (~/.config/ml-ralph/runs/<project>/) ◄─ background run
TUI ──────────┘ (control/ops.ts) state.json · control/ · output.jsonl (RalphRunner → claude)
ml-ralph start spawns the run as a detached process. It writes its state and the agent's output to a run store outside the project and reads commands (stop, hint, contract decision, stop a job) from a queue there. The store is outside the project for the same reason the eval lock is: the research agent has full permissions in the project and must not be able to answer its own pause. See docs/ARCHITECTURE.md.
The cognitive framework
ml-ralph operates as a paranoid scientist. Its core assumption: results are probably misleading, data is probably corrupted, and conclusions should be broken before they're trusted. It allocates roughly 70% of effort to understanding and verification, 20% to strategy, and 10% to execution.
The agent works through a 4-phase cognitive cycle:
UNDERSTAND → STRATEGIZE → EXECUTE → REFLECT
↑ │
└──────────────────────────────────┘
Understand — Verify data integrity (row counts, label distributions, sample inspection). Run exploratory analysis. Research prior art. Build a mental model and explicitly list all assumptions. Nothing happens until this is done.
Strategize — Generate 3–5 competing hypotheses. For each: what's expected, why, and what will be learned. Think 5–6 steps ahead. Pick the path with the best learning-to-effort ratio. Run the smallest experiment that tests the hypothesis.
Execute — Run the experiment. Log metrics and observations as work happens, not after. Surprises are more valuable than confirmations.
Reflect — Verify results are real, not artifacts of bugs, leakage, or evaluation errors. Try to break your own result before trusting it. Then decide:
- Too good? → Verify harder
- Verified and promising? → Strategize next step
- Surprised or confused? → Go back to Understand
- Stuck after 2–3 experiments? → Strategic retreat to Understand
- All success criteria met and verified? → Hand in a candidate; the runner decides
Strategic retreat — going back to understand when stuck — is a first-class concept, not a failure. Understanding is progress.
Conclusions
.ml-ralph/conclusions.md keeps what the agent has learned as at most 300 words of scoped, revisable claims. ml-ralph init creates it (empty), and the runner creates it at start if an older project lacks one. Each iteration's prompt inlines it plus the last N log events (recent_events in config.json, default 30) instead of the whole log.jsonl, so the prompt stays flat as a run grows.
The agent may change the file only with a conclusions_changed event whose reason is contradiction, new_category, flipped_recommendation or refinement. If an iteration leaves it over 300 whitespace-separated words, or changed without such an event, the runner restores the previous version, logs conclusions_rejected with the reason and says why in the next prompt.
Two workers
ml-ralph start --workers 2 runs two iteration loops at once, each with its own claude process in its own git worktree (.ml-ralph/worktrees/worker-1 and worker-2, removed when the run ends). The default is 1; more than 2 is refused, and the project must be a git repository with at least one commit. The workers share the run budget (USD, GPU-hours and minutes are one total; max_experiments_per_iteration applies to each worker) and log.jsonl, where every event carries worker. They start once the eval is locked and wait for each other at the end of every iteration, where the runner merges their conclusions.md files by concatenation under [worker 1] / [worker 2] tags; both read the merge next. The runner then judges their candidates one at a time, so the second must beat the new best by the seed-noise margin, and ralph/best stays one tag. If one worker's claude crashes, a worker_crashed event is logged and the other worker carries on. A new run's worker branches start from the incumbent (ralph/best), and so does a one-worker run's project checkout. When the Claude account hits its usage limit, the run waits until the reset and repeats the iteration; it does not crash, and ml-ralph status shows when it carries on. A run that crashed leaves its worktrees behind; the next start removes them.
Commit before every eval
The runner keeps its copy of the eval lock hashes in ~/.config/ml-ralph/locks/, keyed by project path, so deleting .ml-ralph/eval/lock.json or the marker does not unlock anything. ml-ralph resume restores them from the store, ml-ralph unlock clears the lock so you can lock again on purpose, and ml-ralph rekey <old-path> moves the entry after you move the project directory. ml-ralph init --force never touches the store.
Every eval is tied to a commit, so a metric can be reproduced from code. ml-ralph eval records the HEAD SHA as sha in metrics.json and in the runner's eval event. If tracked files outside .ml-ralph/ have uncommitted changes, it exits non-zero with commit your changes before eval and scores nothing; the agent is told (in RALPH.md) to commit before each eval, and the runner never commits for it. Outside a git repository, eval warns, records sha: null and still scores.
Numeric sweeps go through ml-ralph tune --space space.json --trials N --sampler tpe|cmaes --command "<train cmd with {param}>": the agent chooses the space, Optuna (needs pip install optuna, plus cmaes for CMA-ES) owns the trials, and each trial is scored by the runner like ml-ralph eval. Trials count against the experiment, USD and wall-clock caps below. Tune never promotes; its best trial is only a candidate.
When the runner promotes a candidate it force-moves the git tag ralph/best to the promoted commit. A candidate is rejected if HEAD moved after its eval, since the score belongs to the older commit. If the tag cannot be moved, the runner logs tag_failed with the error and the promotion stands. ml-ralph results and the TUI show the short SHA next to each verified score, and — when the eval has none.
When a run completes
The runner alone decides promotion and completion; the agent only hands in candidates with <candidate_complete>, which it may refuse. After a promotion whose search score (from the runner's own eval and metrics.json) meets the contract's success_threshold in the contract's direction, the runner:
- checks that a
holdout_pathis configured for the project in~/.config/ml-ralph/config.json(it is read again at every promotion, so one added mid-run is used next time); - runs the independent verifier on the whole diff since the baseline commit;
- scores the sealed holdout once for that
eval_id.
The run ends with a run_complete event (eval id, search score, holdout score, verifier verdict) only if the verifier approves, the holdout score meets success_threshold and the search-holdout gap is within holdout_gap_threshold.
Otherwise the run continues. A failed check logs completion_rejected with reason verifier_rejected, holdout_failed or overfitting_gap; the agent's next prompt gets the verdict and one line of reason, with no scores. A check that could not run (verifier error or timeout, unreadable holdout, no holdout_path) logs completion_blocked with the error or reason holdout_not_configured, and the agent output (ml-ralph logs, the TUI) shows it (Completion blocked for <eval_id>: holdout_not_configured (...); the completion gate tests in src/infrastructure/ralph/runner.test.ts assert that line). The check runs again only on a later promotion.
Run budgets
By default a run is limited only by the iteration count. Add any of these optional keys to .ml-ralph/config.json to cap it further; an unset key is not enforced.
{
"max_wall_clock_minutes": 240,
"max_usd": 25,
"max_gpu_hours": 40,
"max_experiments_per_iteration": 3
}
max_wall_clock_minutes— minutes of wall-clock time for the run. A timer checks it during the iteration and stops the claude process when it is reached.max_usd— dollars spent, fromtotal_cost_usdin claude'sresultevents (an API-equivalent estimate, not a subscription bill). That field is the session's running total, so a session with severalresultevents (one per turn when the agent leaves a background task running) counts its last total once. Checked at each result event, so one iteration's overshoot is possible.max_gpu_hours— GPU-hours used by the run's jobs: the sum of--gpus× runtime over jobs started withml-ralph job start --gpus <n> ..., finished and running. The GPU count is self-declared (nothing is read fromnvidia-smi), so while this key is setjob startrefuses a call without--gpus, and refuses any start once the run has used the cap. The runner recomputes usage every 15 s while an iteration runs and after each one; at the cap it stops running jobs and ends the run. Usage is kept per job under.ml-ralph/budget/gpu-jobs/, so it survives job ends and restarts; a run that predates the key starts at 0.max_experiments_per_iteration—ml-ralph evalcalls per iteration. Once reached, further calls exit non-zero withexperiment cap reached for this iteration (<n>). The runner pins the cap it read at start in the claude environment (ML_RALPH_MAX_EXPERIMENTS, withML_RALPH_ITERATION), and eval applies the smaller of that andconfig.json; with a cap set and no iteration id, eval refuses, so it only runs inside the runner's agent session.
When max_wall_clock_minutes, max_usd or max_gpu_hours is reached the run ends with reason budget_exhausted (the event's cap is wall_clock, usd or gpu_hours), logged in log.jsonl. After each iteration the runner logs a budget_status event (usd_spent, elapsed_minutes, gpu_hours_used when max_gpu_hours is set, and the caps); an iteration with no total_cost_usd counts as $0 and logs budget_warning. Each iteration's prompt states the remaining USD and minutes, the GPU-hours used and left, and the experiment cap, and ml-ralph status and the TUI header show estimated spend and elapsed time against the caps (or no cap) and, with max_gpu_hours set, GPU-hours used vs the cap, starting from the recorded totals after a restart. An invalid cap blocks ml-ralph start, which names it.
The holdout guard is best effort: in host mode it catches the holdout and config paths (also as ~/, $HOME, ${HOME}, a glob, or a listing of their directories) in a tool call and cannot see setsid daemons, shell indirection, built-up paths or scripts. For real isolation use ml-ralph start --sandbox docker; see "Holdout access guard" in docs/ARCHITECTURE.md.
A restarted run keeps its run_id (in .ml-ralph/budget/run.json) and starts from the spend and elapsed time in its earlier budget_status events, so a restart does not reset the budget; the id is dropped only when the run ends with max_iterations. After budget_exhausted, a user stop, contract_changed or holdout_access it persists, so a restart inherits the spend and time already recorded. To continue after budget_exhausted, raise a cap in config.json; to start a fresh budget, delete .ml-ralph/budget/run.json. usd_spent includes the independent verifier's total_cost_usd (also recorded as cost_usd on its verifier_verdict event). A negative, zero or non-numeric cap stops the run at start with an error naming the key.
The run report
When a run ends (run_complete, budget_exhausted, max_iterations, contract_changed, eval_gate_failed, holdout_access, ml-ralph stop, or an error that stops the run) the runner writes .ml-ralph/reports/<run id>/report.md from its own records. It has:
- Problem:
problemfromprd.json. - Result: the end reason; the incumbent's eval id, search score (from the runner's
metrics.json), holdout score (not scoredunless the completion gate scored it) and commit SHA. With no promotion it saysno candidate was promoted. - Claims: one line per finding from
log.jsonl, each ending in[eval:<eval_id>]. Every number comes from the runner's ownevalevents; an agent'sexperimentevent is mentioned only as having been logged against a real eval, without its observations.auditClaimsinsrc/infrastructure/ralph/report.ts(used by its tests) flags a claim whose eval id is not in the log or that carries a number other than that eval's recorded mean or std.
Agents that decide their results have plateaued and stop experimenting do not burn the remaining iterations: after max_idle_iterations iterations in a row (default 3, 0 disables) with no ml-ralph eval, no ml-ralph tune and no running training job, the runner ends the run with end reason idle. A hint resets the count, so the usual next step is ml-ralph hint with something new to try, then ml-ralph continue (the last run's workers, sandbox and remaining iterations; --max-iterations N overrides them): a hint sent while no run is active goes into the next run's first iteration. With --workers 2, every hint reaches both workers. A new run's worker branches start at HEAD with the incumbent (ralph/best) merged in, so a run builds on the code it is meant to improve; a continued run picks its own worker branches up again.
If the report cannot be written, the runner logs report_failed and the run still ends. A run that ended with run_complete also gets an Ablations table: the runner reverts each commit between the baseline and ralph/best one at a time in a throwaway worktree, scores the result with the locked evaluator over the contract seeds, logs an ablation event per row and links each row to its eval_id. Ablations are evidence only and never promote. max_ablations in config.json (default 5, 0 disables) caps them; the rest read skipped: cap. They count against max_usd and max_wall_clock_minutes (skipped: budget). A revert that conflicts or an eval that fails shows as failed: <reason>.
Benchmarking ml-ralph
ml-ralph bench runs the fixed suite in bench/suite.json (a clean task, a majority-vote eval exploit and a train/test overlap, all CPU-only) in temporary directories and writes bench/results/<timestamp>.json with, per task, success (the holdout metric meets the task's target), holdout gap, USD and caught (the verifier flagged the planted exploit). It spends real money, each task under its own max_usd and max_minutes, and refuses to run without an authenticated claude. Compare two runs with ml-ralph bench --compare a.json b.json. Run it from a repository checkout (holdout data is not published). It has not been run live yet: a baseline results file is owed. See docs/FILE_LAYOUT.md#bench-bench.
Training jobs
The agent starts training with ml-ralph job start <cmd> (RALPH.md tells it to). The command runs in its own process group; its pid, command, start time and log path (.ml-ralph/runs/logs/<job id>.log) go to .ml-ralph/runs/active.json, and the entry is removed when the job exits. When a run starts, entries whose pid is no longer alive are removed. A single argument runs through the shell; several arguments run the program directly. When config.json sets critique_threshold_minutes, the job needs --est-minutes <n> --hypothesis-id <id>, and an estimate above the threshold is critiqued first (see docs/DATA_MODELS.md).
The TUI
ml-ralph tui (or ml-ralph with no arguments in a terminal) shows one screen: the run state and budget, the runner-verified results (or the setup checklist while the project is not ready), the training jobs, and the research log or the agent's output. Quitting it leaves the run running.
| Key | Action |
|---|---|
s |
Start a run, or stop the active one (asks first) |
+ / - |
Iteration limit for the next run |
h |
Send a hint for the next iteration (while a run is active) |
o |
Switch the right panel between the research log and the agent's output |
r / x |
While paused for a changed eval file: re-lock and continue, or end the run |
↑/↓ |
Select a training job |
t |
Stop the selected job (SIGTERM, then SIGKILL after 10 seconds); the run logs job_stopped and tells the agent's next prompt |
w |
Show the selected job's log, following it |
q |
Quit the TUI |
License
MIT
Explore projetos relacionados
Carregando…