From c6bee5abfb8d7d34c4df5ae9050086556bd68ba3 Mon Sep 17 00:00:00 2001 From: iamziyuzhao Date: Sun, 29 Nov 2026 00:09:06 -0500 Subject: [PATCH 1/7] RAX: its skill library as a template, its merge as the Evolver, its LIBERO sessions on Claude Code - hermit/adapter/templates/rax: RAX's skill library (README.md, INDEX.md, skills//), checked by RAX's own validate_tree. - hermit/agent/evolver/methods/rax: RAX's exploration session as the acting agent's task functions (actor.py: RAX's start prompt and workspace, its MCP bridge to the frontend on the host, its Claude Code settings and relaunch policy, the library's clone and skill_library_merge), the rax Evolver (RAX's merge of each session's library merges into the adapter; no model), and RAX's library code vendored unchanged (real/rainbow 36c926c) with its license and notice. - examples/libero/rax: LIBERO's forty tasks on RAX's LIBERO-PRO backend (libero-pro/native 1767412): the host service (RAX's operator script, workspace and frontend), the judge (RAX's formal batch), disjoint train, validation and test splits, a smoke and the paper's protocol. - docs/methods/rax.md, the methods index, the LIBERO README, the changelog; tests/methods/rax. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + docs/index.md | 1 + docs/methods/index.md | 2 + docs/methods/rax.md | 168 +++ examples/libero/.gitignore | 3 + examples/libero/README.md | 10 +- examples/libero/rax/README.md | 92 ++ examples/libero/rax/eval_official.yaml | 56 + examples/libero/rax/eval_val.yaml | 57 + examples/libero/rax/formal.py | 50 + examples/libero/rax/judge.py | 85 ++ examples/libero/rax/launch.sh | 76 ++ examples/libero/rax/rows.py | 92 ++ examples/libero/rax/run.yaml | 66 + examples/libero/rax/service.py | 424 +++++++ examples/libero/rax/smoke.yaml | 57 + examples/libero/rax/task-info/README.md | 17 + .../adapter/templates/rax/.hermit/EVOLVER.md | 18 + .../templates/rax/.hermit/adapter.yaml | 23 + hermit/adapter/templates/rax/.hermit/check.py | 30 + hermit/adapter/templates/rax/ADAPTER.md | 18 + hermit/adapter/templates/rax/INDEX.md | 4 + hermit/adapter/templates/rax/README.md | 21 + hermit/adapter/templates/rax/exports.yaml | 4 + hermit/agent/evolver/methods/rax/actor.py | 326 +++++ hermit/agent/evolver/methods/rax/evolver.py | 27 + hermit/agent/evolver/methods/rax/evolver.yaml | 8 + hermit/agent/evolver/methods/rax/library.py | 259 ++++ .../evolver/methods/rax/library_server.py | 108 ++ hermit/agent/evolver/methods/rax/merge.py | 85 ++ hermit/agent/evolver/methods/rax/stop_hook.py | 67 + .../evolver/methods/rax/upstream/LICENSE | 202 +++ .../agent/evolver/methods/rax/upstream/NOTICE | 16 + .../rax/upstream/continual-learning.SKILL.md | 325 +++++ .../methods/rax/upstream/skill_library.py | 354 ++++++ tests/README.md | 2 +- tests/core/test_selection.py | 4 +- tests/methods/rax/test_rax.py | 1099 +++++++++++++++++ tests/selection.py | 2 + 39 files changed, 4262 insertions(+), 4 deletions(-) create mode 100644 docs/methods/rax.md create mode 100644 examples/libero/rax/README.md create mode 100644 examples/libero/rax/eval_official.yaml create mode 100644 examples/libero/rax/eval_val.yaml create mode 100644 examples/libero/rax/formal.py create mode 100644 examples/libero/rax/judge.py create mode 100755 examples/libero/rax/launch.sh create mode 100644 examples/libero/rax/rows.py create mode 100644 examples/libero/rax/run.yaml create mode 100644 examples/libero/rax/service.py create mode 100644 examples/libero/rax/smoke.yaml create mode 100644 examples/libero/rax/task-info/README.md create mode 100644 hermit/adapter/templates/rax/.hermit/EVOLVER.md create mode 100644 hermit/adapter/templates/rax/.hermit/adapter.yaml create mode 100644 hermit/adapter/templates/rax/.hermit/check.py create mode 100644 hermit/adapter/templates/rax/ADAPTER.md create mode 100644 hermit/adapter/templates/rax/INDEX.md create mode 100644 hermit/adapter/templates/rax/README.md create mode 100644 hermit/adapter/templates/rax/exports.yaml create mode 100644 hermit/agent/evolver/methods/rax/actor.py create mode 100644 hermit/agent/evolver/methods/rax/evolver.py create mode 100644 hermit/agent/evolver/methods/rax/evolver.yaml create mode 100644 hermit/agent/evolver/methods/rax/library.py create mode 100644 hermit/agent/evolver/methods/rax/library_server.py create mode 100644 hermit/agent/evolver/methods/rax/merge.py create mode 100644 hermit/agent/evolver/methods/rax/stop_hook.py create mode 100644 hermit/agent/evolver/methods/rax/upstream/LICENSE create mode 100644 hermit/agent/evolver/methods/rax/upstream/NOTICE create mode 100644 hermit/agent/evolver/methods/rax/upstream/continual-learning.SKILL.md create mode 100644 hermit/agent/evolver/methods/rax/upstream/skill_library.py create mode 100644 tests/methods/rax/test_rax.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ad973dc2..983de248 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -143,6 +143,14 @@ Changes are grouped by software version. Entries under Unreleased describe work ### Added +- RAX ([arXiv:2610.22496](https://arxiv.org/abs/2610.22496), `docs/methods/rax.md`): the `rax` template (RAX's skill + library: `INDEX.md` and `skills//` with `SKILL.md`, `code/` and `evidence/`, checked by RAX's own + `validate_tree`), the `rax` Evolver (RAX's merge of each session's library merges into the adapter, no model), and + RAX's exploration session as task functions (`hermit/agent/evolver/methods/rax/actor.py`: RAX's start prompt and + workspace, RAX's MCP bridge to its frontend on the host, its relaunch policy as a Claude Code Stop hook, the + library's clone and RAX's `skill_library_merge`). RAX's library code is vendored unchanged with its license. + `examples/libero/rax/`: LIBERO's forty tasks on RAX's LIBERO-PRO backend (its host service, judge and formal + batch), with disjoint train, validation and test splits, a smoke and the paper's protocol. - `examples/officeqa_harbor/`: OfficeQA as Harbor's task set (harbor-datasets' `datasets/officeqa`, pinned) in the OfficeQA paper's evaluation: each question in its own Harbor environment, the paper's agent prompt, the final message's `` scored by the paper's `reward.py` (the OfficeQA repository's at its commit) at a 0.0% diff --git a/docs/index.md b/docs/index.md index 705a1706..1e2493e7 100644 --- a/docs/index.md +++ b/docs/index.md @@ -76,6 +76,7 @@ methods/harness2 methods/continual_harness methods/reharness methods/aspire +methods/rax methods/meta_harness_adapter methods/ace methods/ahe_adapter diff --git a/docs/methods/index.md b/docs/methods/index.md index 9bc3f910..89913d1d 100644 --- a/docs/methods/index.md +++ b/docs/methods/index.md @@ -23,6 +23,7 @@ template–method combinations meaningful. | Evolve whole adapters round by round under regularizers against overfitting the evolve set: an annealed edit budget, the edit history, exploration when stalled, a pre-evaluation leakage critic, a noise-adjusted floor and a cost rule | [RRSI Adapter](rrsi_adapter.md) | `rrsi-adapter` | A training split (the evolve set, k rows per task), a proposer CLI (Codex, Claude Code or Pi), the `rrsi` dependency group, a domain module with the benchmark's texts | | Learn the framework contract offline | [Quick Start](../get-started/quickstart.md) | Prompt-only with a teaching learner | Included toy tasks | | Grow a library of verified skill entries from robot tasks, each proposal re-solved by a fresh actor before it is admitted, with the coordinator choosing the next task | [ASPIRE](aspire.md) | `aspire` | A coordinator CLI (Codex, Claude Code or Pi), verifier task rows in `data.val`, an acting agent that delivers the adapter | +| Carry executable robot skills with their evidence from one exploration session to the next, each merged into a git skill library by a checked merge, with no learner model | [RAX](rax.md) | `rax` | RAX's checkout and its host service (a GPU for the simulators), Claude Code acting with RAX's task functions | A learner model endpoint above can be your Claude subscription, and a learner CLI can run on it, with no API key: [Claude subscription](../guides/claude-subscription.md) says which roles go which way. @@ -48,6 +49,7 @@ task-specific service overhead. Call counts vary with evidence, candidates, and | ReHarness | Per instance, one reflection call, one revision call per retrieved reflection (up to k) and one embedding call; no candidate rollouts or validation | Reflection bank in the adapter; source trajectories and per-instance retrieval and revision records in `state/` | Current adapter: the bank after the last instance | | Meta-Harness Adapter | One proposer session per round writing k candidates; each candidate is a full rollout of the search set, one step per candidate | Every candidate's files, hypothesis, base and per-task scores in `state/` | Best mean on the search set | | ASPIRE | Per task, one coordinator session and, when it proposes entries, a verifier rollout (a fresh actor on the task's verifier row) | The coordinator's curriculum and changelog notes in `state/` | Current adapter: the library after the last task | +| RAX | None: the Evolver replays each session's library merges with RAX's merge, without a model | None (the library is the adapter) | Current adapter: the library after the last session | | RRSI Adapter | Per round: the analyst with a digester per rendered trace (a session per turn), m proposer sessions with the critic's review and repairs, a smoke on the domain's smoke tasks per screened candidate; each candidate is a full rollout of the evolve set (k rows per task), one step per candidate | Every candidate's files and digest, the edit history, the attribution and the frontier in `state/` (upstream's files under `state/rrsi/`) | The incumbent H_T, admitted above the noise floor and within the cost rule | `use_gate: false` in SkillOpt removes the ordinary improvement requirement, **not** the validation calls. diff --git a/docs/methods/rax.md b/docs/methods/rax.md new file mode 100644 index 00000000..9b1ca46f --- /dev/null +++ b/docs/methods/rax.md @@ -0,0 +1,168 @@ +# RAX + +RAX (Robot Agent eXploration; [Scaling Online Exploration for Robot Agents, +arXiv:2610.22496](https://arxiv.org/abs/2610.22496), [project](https://robot-agent-exploration.com/), +[code](https://github.com/robot-agent-exploration/rax)) lets a coding agent learn a robot task by exploring it. In one +session, Claude Code drives the robot through RAX's tools (actions, cameras, depth, a vision-language model), solves the +task by hand, writes a controller, rehearses the controller unattended and submits it; the submitted controller is then +evaluated alone, without the agent, on held-out scenes. Across sessions, RAX keeps a skill library (§3.4): a git +repository of executable skills with their evidence, into which a session merges a skill only through a harness tool +that checks its format and evidence, and from which later sessions start. + +In Hermit the acting agent is RAX's exploration session, run by RAX's own code; the adapter is RAX's skill library; +the Evolver is RAX's merge. There is no learner model: the agents write the library, and the harness checks and +merges it. + +## Setup + +```yaml +template: rax # RAX's skill library: README.md, INDEX.md, skills// +data: # LIBERO's forty tasks, one session per row (rows.py) + {tasks: tasks, view: rows.py:task_row, train: splits/train.txt, test: splits/test.txt, step_size: 1, shuffle: false} +agent: + base: claude # Claude Code, the paper's agent on LIBERO + model: {name: claude-opus-5-5, login: claude, effort: xhigh} + params: # RAX's session as the acting agent's task functions + prompt: hermit.agent.evolver.methods.rax.actor:prompt + prepare: hermit.agent.evolver.methods.rax.actor:prepare + answer: hermit.agent.evolver.methods.rax.actor:answer + collect: hermit.agent.evolver.methods.rax.actor:collect + rax_root: $RAX_ROOT + claude: {web_search: false, args: [--mcp-config, .rax-mcp.json, --strict-mcp-config], env: {MCP_TOOL_TIMEOUT: "1728300000", ...}} +environment: # the task sandbox: RAX's agent Python, bridge and start prompt + read: [$RAX_ROOT/runtime/envs/host, $RAX_ROOT/harness/mcp_bridge.py, $RAX_ROOT/auto_research_agent/START_PROMPT.md] + env: [RAX_SERVICE_URL] +judge: {path: judge.py} # on the host: RAX's formal batch of the submitted bundle +evolver: {name: rax} +sandbox: {enabled: true, enforce: required} +``` + +[`examples/libero/rax/`](https://github.com/Infini-AI-Lab/hermit/tree/main/examples/libero/rax) holds the configs, the +splits and the host service; its README gives RAX's setup and the commands. + +## The template + +`rax` is RAX's skill library as RAX's `services/skill_library.py` lays it out (robot-agent-exploration/rax +`real/rainbow` 36c926c, vendored unchanged in `hermit/agent/evolver/methods/rax/upstream/` with RAX's license and +notice): `README.md` (RAX's, for this robot), `INDEX.md` (one row per skill) and `skills//` with `SKILL.md` +(frontmatter `name`, `description`, `status` draft, verified or deprecated, `robot`, `entry`; RAX's sections), `code/` +(an entry `main(ctx, ...)` returning `{ok, measured, why}`) and `evidence/` (`runs.jsonl`, at least one image; a +`verified` skill has two unattended successful runs with images). `INDEX.md` and `skills/**` are learnable; the rest is +fixed. The template has no `skills/` (a package keeps no dotfile): the library's first commit adds RAX's empty +`skills/.gitkeep`, as RAX's `ensure_library` starts a library. The template's check runs RAX's `validate_tree` over +every skill, as RAX's merge does over a branch's changed ones, and refuses links. + +What reaches the acting session: `ADAPTER.md` in its context, and through the RAX task functions the library's clone +`skill-library/` on the session's branch, RAX's `continual-learning` agent skill and RAX's `skill_library_merge` tool. +`ADAPTER.md` holds RAX's two library paragraphs of `real/rainbow`'s `AGENTS.md` (the reading one with its lead-in +shortened, "Teach later sessions" verbatim) between two of the port's: where the clone is, and where a LIBERO run's +frames are (`runtime/autonomous_controller/runs//frames/`, where RAX's skill, written for its real robots, says +`runtime/frames/`). Without an adapter (`--adapter none`) the session has none of these: it is RAX's LIBERO session as +published. No existing template fits: none holds a repository of skills that sessions merge into through a checked +merge. + +## The session + +RAX's trusted side runs on the host, in the example's service (`examples/libero/rax/service.py`, on RAX's host +Python): for each rollout, RAX's operator script makes the session's configuration from the task row +(`scripts/configure_auto_research.py`), RAX's `prepare_workspace` makes its workspace (RAX's template, skills, +`TASK.md`, the three demonstration images), and RAX's frontend serves its robot, episode, bundle and Gemini tools on a +Unix socket. The frontend runs in a mount namespace of its own (bubblewrap) where the session's run tree is a +directory beside the rollout's workspace, so the session reads its frames and traces there +(`runtime/autonomous_controller`) and nothing else of RAX's session directory. + +The session runs in the task sandbox (`hermit/agent/evolver/methods/rax/actor.py`): `prepare` registers with the +service, writes RAX's workspace beside the deployment, and wires Claude Code as RAX's Claude Code launcher does: +`CLAUDE.md` reads `AGENTS.md`, `.claude/skills` is `.agents/skills`, RAX's bridge (`harness/mcp_bridge.py`) to the +socket as the MCP server `auto_research`, RAX's agent environment for its commands (RAX's Python first, the robot +socket, offline package tools, thread limits) and RAX's relaunch policy as a Stop hook. With an adapter it builds the +session's library repository from the adapter's files, clones it with RAX's `checkout`, and serves +`skill_library_merge` (`library_server.py`: RAX's name, description, schema and refusal, and RAX's `merge` against +that repository). The prompt is RAX's `START_PROMPT.md` in code mode. `collect` ends the session at the service and +writes what the session merged into its library (a git bundle of the repository's main past its first commit, made in +a fresh repository from copied objects) and the session's notes and code into the log. The judge, on the host, runs +RAX's formal batch of the submitted bundle (the supervisor's `run_submission`, `formal.py`) on the row's formal +layouts: the share of successful episodes, LIBERO's own binary check, errors counted as failures. + +## The step + +One step is one task's session. + +```{mermaid} +flowchart TD + A[the adapter: the library] -->|deployed; prepare builds the session's repository and clone| S[RAX session in the task sandbox: Claude Code with RAX's frontend tools on the host] + S -->|skill_library_merge: RAX's merge into its repository| R[the session's repository] + S -->|submit| J[judge on the host: RAX's formal batch of the bundle on the row's held-out states] + R -->|collect: a bundle of main past the base| M[the step's learning material: library.json and library.bundle in the run's log] + M --> E[rax Evolver: a fresh repository of the adapter, the same base commit] + E -->|RAX's merge of each session's bundle, every changed skill checked again| E2[merged main] + E2 -->|INDEX.md and skills/ written back| L[the next adapter] + L --> K{template check: RAX's validate_tree} +``` + +1. The Trainer runs the step's session with the current library. The agent reads `skill-library/INDEX.md`, reuses + what matches, and merges its new or improved skills with `skill_library_merge` (as `draft` once automated, again + when verified, and before the session ends); RAX's merge answers with problems to fix, conflicts, or the merge. +2. The judge scores the submitted controller; the score is the task's. +3. The Evolver (`merge.py`, a program in the evolver sandbox) builds a repository from the adapter (one commit of its + library files, with a fixed identity and date, so it is the commit the session started from), fetches each + session's bundle onto `session/` and runs RAX's merge, which checks every changed skill again. A session that + started from another library, or whose bundle is not what it recorded, is not taken in. +4. The merged main's `INDEX.md` and `skills/` are the next adapter, checked by the template's check. + +The final adapter is the library after the last session. A step of several sessions merges them in order; a session +whose changes conflict with an earlier one of the same step is not taken in (RAX would ask that agent to merge +`origin/main`), so the configs run one session a step. Hermit's check copies an adapter of at most 256 MB: a library +past that (RAX allows 25 MB a skill, saved frames included) fails the check, and the Trainer reverts the step's merges. + +## Parameters + +```{literalinclude} ../../hermit/agent/evolver/methods/rax/evolver.yaml +:language: yaml +``` + +The task functions read `agent.params.rax_root` (RAX's checkout), `service_env` (the variable that holds the service's +URL, default `RAX_SERVICE_URL`) and `bin` (the CLI). The session's settings are RAX's configuration of the task row +(its exploration layouts and episodes, its formal layouts) and the service's (`--exploration-envs` 2, `--subagents` +0: one per environment, `--formal-workers` 4, `--key-file` for Gemini). + +## The authors' implementation against this one + +| Dimension | RAX (robot-agent-exploration/rax) | This port | Why | +|---|---|---|---| +| Code | `libero-pro/native` 1767412 (LIBERO); the skill library of `real/rainbow` 36c926c | the same commits: RAX's operator script, workspace, frontend, supervisor, simulators, formal batch and skill library, unchanged | — | +| Agent | Claude Code, Claude Opus 5.5 at xhigh, its own home, its servers alone (`--strict-mcp-config`); denied: the web tools, the subagent tools at a subagent cap of 0, edits of the workspace's `.claude/` and `.mcp.json`; its commands in Claude Code's own sandbox (writes in the workspace and the socket's directory) | the same model, effort, flags and deny rules (the project's `.claude/settings.json`, with `.rax-mcp.json` guarded too), on Hermit's Claude Code agent; its commands in the task sandbox (bubblewrap), so a command, unlike a file tool, can still write `.claude/`, and what it writes there runs in the same sandbox | the task sandbox is the boundary | +| Prompt and workspace | `START_PROMPT.md`; `prepare_workspace` | the same, byte for byte; with an adapter, the library's clone, RAX's continual-learning skill and the two library paragraphs of `real/rainbow`'s `AGENTS.md` (`ADAPTER.md`) | the library is `real/rainbow`'s, which `libero-pro/native` lacks | +| Robot tools | RAX's frontend, through RAX's bridge on a socket | the same, on the host; the run tree beside the workspace, which the agent can write (RAX's frontend reads it without following links) | the task sandbox shows only declared paths | +| Relaunch | the launcher runs the CLI again (`--resume`) with `CONTINUE_PROMPT` while exploration is open, at most 3 times | a Stop hook continues the same CLI with the same prompt, without its clause about stopped background workers (here they run on) | Hermit runs one CLI per call | +| Error relaunch, adaptation stage | relaunch after a provider error; up to 5 adaptation episodes on swap layouts (collection 6) | not ported: Hermit retries only a session the model never served; no adaptation | scope | +| Agent pause | the agent CLI and its processes are stopped (SIGSTOP) while a bundle is copied and rehearsed | not paused: the main turn waits on the call, but background commands and subagents run on; the bundle copied is the registered snapshot | the CLI's processes are in the task sandbox's process namespace, which the host's frontend cannot signal | +| Bundles | run at the agent's workspace path, in a fresh bubblewrap sandbox and simulator per episode | run at RAX's session workspace path (not the Hermit workspace's); the same sandbox | RAX's supervisor names that path | +| Exploration | ≤ 20 episodes on fresh layouts (`env.seed(1000 + i)`), two environments, 600 s + 5 s per step | the same; each split's layouts its own (train 100-119, val 200-219, test 0-19) | disjoint splits | +| Evaluation | each session's bundle on official init states 0-49 and on LIBERO-Pro's swap states 0-49 | one split per score: train on official 0-42, val on official 43-49, test on swap 0-49 (official 0-49 for the paper's table, `eval_official.yaml`) | held-out splits for a learned library | +| Gemini | Gemini 3.8 Flash via OpenRouter, $10 per session | the same tool, on the host; no session cap (removed upstream before the pinned commit); each session's spend recorded (`gemini_usd`) | the pinned code | +| Library | one repository per robot on the host; a session merges into it directly | each session merges into its own repository; the Evolver merges the sessions' merges with the same code | the session runs in the task sandbox; the learner's update is the Evolver's | +| Library on LIBERO | the paper's LIBERO results use no library (independent sessions); the library is shown on the real RB-Y1 | the library across LIBERO's forty tasks | the reproduction's question; `--adapter none` is the paper's setting | +| Session clock | none | Hermit's cap, 48 h (`claude.timeout_s`) | a run must end | + +## Boundaries + +The session never sees its formal layouts, their scores or another session's: the judge plays them on the host, and +the Evolver reads only what each session merged (no scores, no evaluation frames). The test split's swap states are +neither played nor scored by any training or validation session; `TASK.md` says, as RAX's does for every LIBERO-PRO +session, that formal layouts may swap objects. The library is the only thing a session leaves the next, and every +skill in it passed RAX's checks twice (in the session and in the Evolver). RAX's evidence is the agent's own record: +the checks hold its format, not that the runs happened. + +The service trusts a session only with its workspace and task: it registers the one workspace the framework makes for a +rollout, once (again only for a retry of a session that spent nothing), so a session cannot start a second session or a +fresh budget. A session `prepare` registered but could not set up is ended at once; one whose `collect` cannot reach the +service is ended by the judge. Gemini's calls (RAX's frontend on the host, OpenRouter) are outside Hermit's model layer +and its usage accounting; their cost is in each session's facts and score (`gemini_usd`). The session's Claude Code +calls go through Hermit's Claude Code agent (Model: the Claude login's model; Base Agent: Claude Code; Acting Agent: the +CLI agent with RAX's task functions), with its login plan, timeout and usage. The Evolver calls no model. + +## Example + +[`examples/libero/rax/`](https://github.com/Infini-AI-Lab/hermit/tree/main/examples/libero/rax): LIBERO's forty tasks +on RAX's LIBERO-PRO backend, with the train, validation and test splits above, a smoke and the paper's protocol. diff --git a/examples/libero/.gitignore b/examples/libero/.gitignore index 62859799..6b07a1de 100644 --- a/examples/libero/.gitignore +++ b/examples/libero/.gitignore @@ -2,3 +2,6 @@ runs/ # ASPIRE's tasks and splits, written by aspire/tasks.sh at launch aspire/tasks/ aspire/splits/ +# RAX's tasks and splits, written by rax/launch.sh (rax/rows.py) +rax/tasks/ +rax/splits/ diff --git a/examples/libero/README.md b/examples/libero/README.md index 64f8f7dd..b45db469 100644 --- a/examples/libero/README.md +++ b/examples/libero/README.md @@ -17,8 +17,10 @@ on held-out seeds by the task's own success check. | `utils/launch.sh` | Starts a method folder's run: the simulator service and hermit | | [`aspire/`](aspire/) | The ASPIRE method (its session's task functions, verifier and coordinator are ASPIRE's own; `tasks.sh` adds its verifiers to the tasks). `run.yaml` (Object, Spatial, Goal, Long: 40 tasks), `run_90.yaml` (LIBERO-90), `run_pro.yaml` (LIBERO-Pro: 80), `run_pro_long.yaml` (LIBERO-Long-Pro), `run_luna.yaml` (`run.yaml` on Luna), `run_sample_luna.yaml` (six of the forty on Luna, for a run of a day or two), `smoke*.yaml`, `launch.sh` | | [`prompt_only/`](prompt_only/) | The prompt-only template: one `ADAPTER.md` the built-in Codex Evolver revises after each task, with the method-neutral prompt. `run.yaml`, `run_pro.yaml`, `smoke.yaml`, `smoke_luna.yaml`, `launch.sh` | +| [`rax/`](rax/) | The RAX method on RAX's own LIBERO-PRO backend, not on the engine below: a Claude Code exploration session per task with RAX's robot tools, scored by RAX's formal batch on LIBERO's fixed initial states or LIBERO-Pro's swap states; RAX's skill library as the adapter. `run.yaml` (train, 40 tasks), `eval_val.yaml`, `eval_official.yaml`, `smoke.yaml`, its own `launch.sh`; its README gives RAX's setup and the splits | -The `*_luna.yaml` configs run GPT-5.6-Luna on the machine's ChatGPT login; the others GLM 5.3 Flash on Fireworks. +The `*_luna.yaml` configs run GPT-5.6-Luna on the machine's ChatGPT login; the others GLM 5.3 Flash on Fireworks +(`rax/` runs Claude Code on the machine's Claude login). ## The engine and the protocol @@ -45,6 +47,11 @@ pinned, the judge can score the held-out seeds 1-50 on them. ASPIRE notes that s distinct for every task: where a task's placement leaves little room, a held-out seed can give a development seed's layout. +`rax/` is the exception: it runs on RAX's own backend (LIBERO's official environment in RAX's harness), explores +seeded resets (`env.seed(1000 + i)`) and is scored on LIBERO's fixed initial states (official, or LIBERO-Pro's +swap states), so its numbers are comparable with results on LIBERO's fixed states and not with this engine's +seeded scenes. Its README states its splits. + A method's number is measured the same way whatever its prompt: the workspace, `bin/sim`, the seeds, the scored program (`fix_code.py`) and the judge are the engine's, and nothing of a method is in them. ASPIRE's configs give the session ASPIRE's own task functions (`hermit.agent.evolver.methods.aspire.actor`: the fix-loop subagent and the @@ -87,3 +94,4 @@ ASPIRE_SIM_GPU=0 ASPIRE_CONFIG=run_pro.yaml ./launch.sh # LIBERO-Pro is a folder of configs beside these: `utils/agent/task.py` as its prompt and the engine's workspace, or its own (and a `tasks.sh` if it adds rows of its own, as ASPIRE's verifiers). Run one method folder at a time on a checkout and an `ASPIRE_OUT`: they share the task rows, the staged docs and the service's ledger, which each launch writes. +`rax/` has its own launcher and variables (`RAX_ROOT`, `RAX_SIM_GPU`, ...), which its README describes. diff --git a/examples/libero/rax/README.md b/examples/libero/rax/README.md new file mode 100644 index 00000000..05852662 --- /dev/null +++ b/examples/libero/rax/README.md @@ -0,0 +1,92 @@ +# RAX on LIBERO + +[RAX](../../../docs/methods/rax.md) ([arXiv:2610.22496](https://arxiv.org/abs/2610.22496), +[code](https://github.com/robot-agent-exploration/rax)) on LIBERO's forty tasks (Spatial, Object, Goal and Long), on +RAX's own LIBERO-PRO backend: the official LIBERO environment, RAX's robot tools and episodes, and RAX's formal +evaluation on LIBERO's stored init states. Each task is one RAX exploration session in code mode: Claude Code explores +fresh layouts of the task (at most 20 episodes, two environments), writes a controller, rehearses and submits it, and +the judge plays the submitted controller alone on held-out init states. Across the sessions, RAX's skill library (the +`rax` template) carries verified, executable skills from one task to the next, merged with RAX's own merge. + +| File | What it is | +|---|---| +| `rows.py` | The task rows (`tasks/`, task directories in Harbor's format) and splits (`splits/`), written by `launch.sh` | +| `run.yaml` | Training: the train split, Claude Opus 5.5 at xhigh, the `rax` template and Evolver; `hermit eval` runs the test split | +| `eval_val.yaml` | The validation split as `hermit eval`'s test split, to compare the training run's checkpoints | +| `eval_official.yaml` | The paper's protocol (official init states 0-49), for RAX as published (`--adapter none`) | +| `smoke.yaml` | One task, two episodes, Claude Haiku 5.5, and its evaluation on another row | +| `launch.sh` | Writes the rows, starts the RAX service, runs hermit | +| `service.py` | RAX's trusted side on the host: each session's configuration, workspace and frontend (RAX's code) | +| `judge.py`, `formal.py` | The score: RAX's formal batch of the submitted bundle on the row's formal layouts | +| `task-info/` | What a task and its record are, for the learner | + +## Data splits + +Every split but the smokes holds the forty tasks; a row is one session. A session explores fresh seeded resets of the +original task (RAX's collection 0: layout *i* is `env.seed(1000 + i)` then `reset()`, never a stored init state) and is +scored on stored init states it never plays. + +| Split | Rows | Exploration layouts | Scored on | Used by | +|---|---|---|---|---| +| train | `train-` | 100-119 | official LIBERO, init states 0-42 (collection 1) | `run.yaml`: the training rollouts, the Evolver's material | +| val | `val-` | 200-219 | official LIBERO, init states 43-49 (collection 1) | `eval_val.yaml`: choosing a checkpoint | +| test | `test-` | 0-19 | LIBERO-Pro swap, init states 0-49 (collection 2) | `run.yaml`'s `hermit eval`: the reported result | +| official | `official-` | 0-19 | official LIBERO, init states 0-49 | `eval_official.yaml`: the paper's protocol, no library | +| smoke | `smoke-libero_spatial_0` | 300-301 | official LIBERO, init states 0-1 | `smoke.yaml`: its training | +| smoke_test | `smoke_test-libero_spatial_0` | 302-303 | LIBERO-Pro swap, init states 0-1 | `smoke.yaml`: its evaluation | + +Train, val, test and the smokes explore disjoint layouts (`official` explores test's, RAX's own 0-19), training and +validation are scored on disjoint official states, and the test split's swap states (objects exchange their initial +regions) are neither played nor scored by any training or validation session. The learner never sees a score's episodes: +the Evolver reads only the sessions' own library merges. `official` shares its states with train and val, so it is a +reproduction of the paper's table, not a test of a trained library. RAX's optional second stage (up to five adaptation +episodes on swap layouts, collection 6) is not a split here. + +## Setup + +RAX's checkout at the pinned commit, set up as its own README and `docs/LIBERO_PRO_BACKEND.md` say (an NVIDIA GPU +for the simulators, bubblewrap, git): + +```bash +git clone https://github.com/robot-agent-exploration/rax && cd rax +git checkout 1767412c5300b9358059ae6a39740c3c28d2b8b9 # branch libero-pro/native +bash scripts/setup_host_env.sh # runtime/envs/host: the harness's and agent's Python +bash scripts/bootstrap_sources.sh # LIBERO-PRO/ at its pinned commit +bash scripts/setup_libero_pro_env.sh # runtime/envs/libero_pro: the simulator's +runtime/envs/host/bin/python scripts/setup_libero_pro_data.py +for suite in spatial object goal 10; do for i in $(seq 0 9); do # three demonstration images per task + runtime/envs/host/bin/python scripts/setup_libero_pro_demos.py --gpu 0 --task libero_${suite}_$i +done; done +runtime/envs/host/bin/python scripts/libero_pro_doctor.py --gpu 0 --task libero_spatial_0 +``` + +The sessions run on the machine's Claude login ([Claude subscription](../../../docs/guides/claude-subscription.md): +`claude setup-token`, then `CLAUDE_CODE_OAUTH_TOKEN`). RAX's Gemini perception tool (`gemini_generate`, which the +paper's sessions had) needs an OpenRouter key file (`RAX_KEY_FILE`); without one the sessions run without it. + +## Run + +From this folder: + +```bash +export RAX_ROOT=/path/to/rax RAX_SIM_GPU=0 RAX_KEY_FILE=~/.codex/secrets/openrouter_api_key +RAX_CONFIG=smoke.yaml ./launch.sh # the smoke +./launch.sh # train: forty sessions, one per step +RAX_CONFIG=eval_val.yaml ./launch.sh eval --adapter rax-libero/ckpt-step-20 # validation, per checkpoint +./launch.sh eval --adapter rax-libero/ckpt-step-20 # test, the chosen checkpoint +./launch.sh eval --adapter root # test, the empty library +RAX_CONFIG=eval_official.yaml ./launch.sh eval --adapter none # the paper's protocol +``` + +`--adapter none` runs RAX's sessions as published (no library, no `skill_library_merge`); `--adapter root` gives +every session the empty library, its clone and the merge tool. Runs go to `RAX_OUT` (default `../runs/rax`): the +trainer's records, the sessions' logs (`actor-logs/`: the CLI's stream, the session's notes and code, its library +bundle), the service's ledger and log (`rax-service/`, `rax-service.log`). RAX's own session directories (its state, +bundles, run trees and formal reports) stay under `$RAX_ROOT/runtime/auto-research/`, named in the ledger. One launch +at a time on a `RAX_OUT`: its service holds a lock in `rax-service/`, and a service started after one that was killed +first ends the sessions that one left open. + +A session runs for hours (the paper reports a median of 0.7 to 1.8 hours of agent time per DexJoCo session, Table +17; LIBERO's sessions have two environments and up to 20 episodes), and each score is a formal batch of 43 (train), 7 +(val) or 50 (test) episodes, four at a time. A run has one session at a time (`agent.concurrency: 1`): the library is +sequential, each session starting from the one the last session left. diff --git a/examples/libero/rax/eval_official.yaml b/examples/libero/rax/eval_official.yaml new file mode 100644 index 00000000..c40a04d0 --- /dev/null +++ b/examples/libero/rax/eval_official.yaml @@ -0,0 +1,56 @@ +# The paper's LIBERO protocol (Appendix C.7, its LIBERO table): run.yaml with each task's session scored on official +# LIBERO's fifty init states (exploration layouts 0-19, RAX's own). Those states are the training and validation +# splits' (0-42 and 43-49), so this is no test of a trained library: it runs RAX as published, with no library: +# RAX_CONFIG=eval_official.yaml ./launch.sh eval --adapter none +data: + tasks: tasks # rows.py's task directories, each read as its row + view: rows.py:task_row + train: splits/train.txt + test: splits/official.txt # official LIBERO init states 0-49 + step_size: 1 # one session a step: each starts from the library the last one left, as in RAX + shuffle: false # LIBERO's order: Spatial, Object, Goal, then Long +task_info: task-info +agent: + base: claude + concurrency: 1 + model: {name: claude-opus-5-5, login: claude, effort: xhigh} # the paper's agent + params: + prompt: hermit.agent.evolver.methods.rax.actor:prompt + prepare: hermit.agent.evolver.methods.rax.actor:prepare + answer: hermit.agent.evolver.methods.rax.actor:answer + collect: hermit.agent.evolver.methods.rax.actor:collect + rax_root: $RAX_ROOT # RAX's checkout (launch.sh passes it expanded) + claude: + web_search: false # RAX's agent works offline (its DENIED_TOOLS: WebFetch, WebSearch) + timeout_s: 172800 # Hermit's cap on a session (RAX sets none): 20 episodes and the work between + args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] # RAX's: only the session's servers (prepare writes them) + env: # RAX's Claude Code session (harness/claude_cli/auto_research.py agent_environment) + MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: (CALL_SECONDS + 300) ms + BASH_MAX_TIMEOUT_MS: "1728000000" + DISABLE_AUTOUPDATER: "1" + CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: "0" + CLAUDE_CODE_AUTO_COMPACT_WINDOW: "250000" + ENABLE_PROMPT_CACHING_1H: "1" + CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: 1h +environment: # the task sandbox: RAX's agent Python, MCP bridge and start prompt, nothing else + read: + - $RAX_ROOT/runtime/envs/host + - $RAX_ROOT/harness/mcp_bridge.py + - $RAX_ROOT/auto_research_agent/START_PROMPT.md + env: [RAX_SERVICE_URL] # the host's RAX service (launch.sh): its 127.0.0.1 port is forwarded +judge: + path: judge.py # on the host: RAX's formal batch of the submitted bundle on the row's layouts +template: rax +evolver: + name: rax # RAX's merge of each session's skill-library merges; no learner model +sandbox: + enabled: true + enforce: required +trainer: + run_name: rax-libero-official + epochs: 1 + save_freq: {steps: 10, epochs: 1} # rax-libero/ckpt-step-10, -20, -30: the checkpoints eval_val.yaml compares + call_timeout_min: 60 # the Evolver's merge + budget: {usd: null, hours: 2000} +eval: + repeats: 1 diff --git a/examples/libero/rax/eval_val.yaml b/examples/libero/rax/eval_val.yaml new file mode 100644 index 00000000..ee79fb1a --- /dev/null +++ b/examples/libero/rax/eval_val.yaml @@ -0,0 +1,57 @@ +# Validation of RAX on LIBERO: run.yaml with the validation split as `hermit eval`'s test split (the forty tasks, each +# scored on official LIBERO init states 43-49, exploration layouts 200-219), to choose among the training run's +# checkpoints without the test split. launch.sh evaluates in the training run's tree, by its tags: +# RAX_CONFIG=eval_val.yaml ./launch.sh eval --adapter rax-libero/ckpt-step-20 (or rax-libero/final, root, none) +# Its results go under rax-libero-val/eval//, apart from the test split's. +data: + tasks: tasks # rows.py's task directories, each read as its row + view: rows.py:task_row + train: splits/train.txt + test: splits/val.txt # the validation split + step_size: 1 # one session a step: each starts from the library the last one left, as in RAX + shuffle: false # LIBERO's order: Spatial, Object, Goal, then Long +task_info: task-info +agent: + base: claude + concurrency: 1 + model: {name: claude-opus-5-5, login: claude, effort: xhigh} # the paper's agent + params: + prompt: hermit.agent.evolver.methods.rax.actor:prompt + prepare: hermit.agent.evolver.methods.rax.actor:prepare + answer: hermit.agent.evolver.methods.rax.actor:answer + collect: hermit.agent.evolver.methods.rax.actor:collect + rax_root: $RAX_ROOT # RAX's checkout (launch.sh passes it expanded) + claude: + web_search: false # RAX's agent works offline (its DENIED_TOOLS: WebFetch, WebSearch) + timeout_s: 172800 # Hermit's cap on a session (RAX sets none): 20 episodes and the work between + args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] # RAX's: only the session's servers (prepare writes them) + env: # RAX's Claude Code session (harness/claude_cli/auto_research.py agent_environment) + MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: (CALL_SECONDS + 300) ms + BASH_MAX_TIMEOUT_MS: "1728000000" + DISABLE_AUTOUPDATER: "1" + CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: "0" + CLAUDE_CODE_AUTO_COMPACT_WINDOW: "250000" + ENABLE_PROMPT_CACHING_1H: "1" + CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: 1h +environment: # the task sandbox: RAX's agent Python, MCP bridge and start prompt, nothing else + read: + - $RAX_ROOT/runtime/envs/host + - $RAX_ROOT/harness/mcp_bridge.py + - $RAX_ROOT/auto_research_agent/START_PROMPT.md + env: [RAX_SERVICE_URL] # the host's RAX service (launch.sh): its 127.0.0.1 port is forwarded +judge: + path: judge.py # on the host: RAX's formal batch of the submitted bundle on the row's layouts +template: rax +evolver: + name: rax # RAX's merge of each session's skill-library merges; no learner model +sandbox: + enabled: true + enforce: required +trainer: + run_name: rax-libero-val + epochs: 1 + save_freq: {steps: 10, epochs: 1} # rax-libero/ckpt-step-10, -20, -30: the checkpoints eval_val.yaml compares + call_timeout_min: 60 # the Evolver's merge + budget: {usd: null, hours: 2000} +eval: + repeats: 1 diff --git a/examples/libero/rax/formal.py b/examples/libero/rax/formal.py new file mode 100644 index 00000000..1296bb0a --- /dev/null +++ b/examples/libero/rax/formal.py @@ -0,0 +1,50 @@ +"""A finished session's formal batch, as RAX's launcher runs it once the exploring agent has exited +(services/agent_formal/checkpoint.py `after_exploration`, code mode): RAX's supervisor of the session, with its Gemini +router when the session has external perception, plays the submitted bundle on the session's formal layouts +(`run_submission`: each episode a fresh process in a fresh sandbox and environment, no agent, no retry). RAX's freeze of +the agent beforehand is for agent formal and adaptation, which this port does not run. Prints the batch's outcome. +Run with RAX's host Python from RAX's checkout (the judge does): + + $RAX_ROOT/runtime/envs/host/bin/python formal.py --root [--key-file ] +""" +import argparse +import json +from pathlib import Path + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--root", type=Path, required=True, help="the session's RAX directory") + ap.add_argument("--key-file", type=Path, help="RAX's --key-file (the Gemini router's OpenRouter key)") + args = ap.parse_args() + from services.agent_formal.checkpoint import _outcome + from services.controller.backend import make_backend + from services.controller.frontend import load_configuration + from services.controller.gemini import GeminiRouter, load_key + from services.controller.storage import persist + from services.controller.supervisor import Supervisor + config = load_configuration(args.root / "configuration.json") + key = load_key(args.key_file) if config.external_perception else None + supervisor = Supervisor(config, lambda: make_backend(config), GeminiRouter(key) if key else None) + try: + submission = supervisor.state.get("submission") + if not submission: + outcome = {"status": "no_submission"} + else: + if not supervisor.submission_done(): + supervisor.run_submission() + outcome = _outcome(supervisor.state.get("formal_batch"), supervisor.state, submission["bundle"]) + batch = supervisor.state.get("formal_batch") or {} + outcome = {**(outcome or {"status": "no_result"}), + **{k: batch.get(k) for k in ("error_count", "unsuccessful_count", "interrupted_count") + if k in batch}, + "eval_seed": config.formal_collection, "first_layout": config.formal_seed, + "episodes": config.formal_episodes} + persist(args.root / "hermit-formal.json", outcome) + finally: + supervisor.close() + print(json.dumps(outcome)) + + +if __name__ == "__main__": + main() diff --git a/examples/libero/rax/judge.py b/examples/libero/rax/judge.py new file mode 100644 index 00000000..82a1d21c --- /dev/null +++ b/examples/libero/rax/judge.py @@ -0,0 +1,85 @@ +"""The judge, on the host: RAX's formal batch of the session's submitted bundle on the task row's formal layouts, which +the session never played (RAX's operator configuration holds them out of exploration), scored as RAX scores it: the +share of the row's episodes that succeeded (LIBERO's own success check, binary), errors and missing episodes counted +as failures. The batch is RAX's own, after the session (formal.py: the supervisor's run_submission, with Gemini when +the session had it); a session that submitted no bundle scores 0. The feedback names only the count and the layouts. + +The session is the one the RAX service's ledger names for the run's workspace (the facts `collect` returned name the +workspace; the ledger, outside every sandbox, names the session). Variables (launch.sh exports them): RAX_ROOT (the +checkout), RAX_STATE (the service's directory: ledger.json), RAX_SERVICE_URL (to end a session `collect` did not end), +RAX_KEY_FILE (the Gemini router's key, optional), RAX_FORMAL_TIMEOUT_S (default 86400).""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import subprocess +import urllib.request + +HERE = Path(__file__).resolve().parent + + +def _ledger() -> dict: + path = Path(os.environ["RAX_STATE"]) / "ledger.json" + return json.loads(path.read_text()) if path.is_file() else {} + + +def _finish(workspace: str) -> None: + url = os.environ.get("RAX_SERVICE_URL") + if not url: + return + request = urllib.request.Request(url.rstrip("/") + "/finish", data=json.dumps({"workspace": workspace}).encode(), + method="POST", headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=600) as response: + response.read() + + +def _formal(root: str) -> dict: + rax = Path(os.environ["RAX_ROOT"]).resolve() + command = [str(rax / "runtime" / "envs" / "host" / "bin" / "python"), str(HERE / "formal.py"), "--root", root] + if os.environ.get("RAX_KEY_FILE"): + command += ["--key-file", os.environ["RAX_KEY_FILE"]] + env = {k: v for k, v in os.environ.items() if not k.startswith("RAX_")} # as RAX's launcher starts its services + env["PYTHONPATH"] = str(rax) + done = subprocess.run(command, cwd=rax, env=env, capture_output=True, text=True, + timeout=float(os.environ.get("RAX_FORMAL_TIMEOUT_S", 86400))) + if done.returncode: + raise RuntimeError(f"RAX's formal batch failed: {(done.stderr or done.stdout).strip()[-1000:]}") + return json.loads(done.stdout.strip().splitlines()[-1]) + + +def score(task: dict, output) -> dict: + facts = (output.extra or {}).get("task") or {} + episodes = int(task["formal_episodes"]) + label = str(task.get("score_label") or "the formal layouts") + workspace = str(facts.get("workspace") or "") + entry = _ledger().get(workspace) + if entry is None or entry.get("task") != task["id"]: + return {"score": 0.0, "feedback": f"0/{episodes} on {label}: no RAX session of this task for the run", + "episodes": episodes} + if not entry.get("finished"): + _finish(workspace) + entry = _ledger().get(workspace) or entry + if not entry.get("submitted_bundle"): + return {"score": 0.0, "feedback": f"0/{episodes} on {label}: the session submitted no bundle", + "episodes": episodes, "successes": 0} + outcome = _formal(entry["root"]) + if outcome.get("success_count") is not None: + successes = int(outcome["success_count"]) + else: + successes = 1 if outcome.get("task_complete") else 0 + status = outcome.get("status") + note = "" if status == "completed" else f"; the batch is {status}" + return {"score": successes / episodes, "feedback": f"{successes}/{episodes} on {label}{note}", + "successes": successes, "episodes": episodes, "batch": outcome, + "gemini_usd": _gemini_usd(Path(entry["root"]))} + + +def _gemini_usd(root: Path) -> float | None: + """The session's Gemini spend after its formal batch (RAX's gemini_spend, nanodollars): the exploration's and the + bundle's calls, made by RAX on the host, outside the framework's usage accounting.""" + try: + state = json.loads((root / "state.json").read_text()) + except (OSError, ValueError): + return None + return round(int((state.get("gemini_spend") or {}).get("reported") or 0) / 1_000_000_000, 6) diff --git a/examples/libero/rax/launch.sh b/examples/libero/rax/launch.sh new file mode 100755 index 00000000..fb55a259 --- /dev/null +++ b/examples/libero/rax/launch.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# Train, or evaluate, RAX on LIBERO (README.md): this folder's configs with RAX's own LIBERO-PRO backend. Run it on +# the host that holds RAX's checkout and a GPU for its simulators. From this folder: +# +# RAX_ROOT=/path/to/rax RAX_SIM_GPU=0 ./launch.sh # train run.yaml (train split, 40 sessions) +# RAX_CONFIG=smoke.yaml ./launch.sh # the smoke: one task, two episodes +# ./launch.sh eval --adapter final # the test split with the trained library +# ./launch.sh eval --adapter root # the same with the empty library +# RAX_CONFIG=eval_val.yaml ./launch.sh eval --adapter rax-libero/ckpt-step-20 # the validation split +# RAX_CONFIG=eval_official.yaml ./launch.sh eval --adapter none # the paper's LIBERO protocol, RAX as published +# +# Variables: RAX_ROOT (RAX's checkout, libero-pro/native, set up as README.md says), RAX_SIM_GPU (the simulators' +# GPU, an ordinal or UUID: RAX's --sim-gpu), RAX_KEY_FILE (an OpenRouter key file for RAX's Gemini perception tool; +# without it the sessions have none), RAX_OUT (the runs, default runs/ beside this folder), RAX_PORT (the service, +# default 8130), RAX_CONFIG (default run.yaml), RAX_TREE (the adapter tree under $RAX_OUT/trees: the config's name; +# run for eval_*.yaml), HERMIT_PYTHON (default python). The Claude Code sessions run on the +# machine's Claude login (CLAUDE_CODE_OAUTH_TOKEN, docs/guides/claude-subscription.md). +# +# The launcher writes the task rows and splits (rows.py: tasks/, splits/), starts RAX's host service on RAX's host +# Python (service.py: the sessions' frontends, simulators and formal batches; stopped when the run ends) and runs +# hermit, whose judge (judge.py) plays each session's submitted bundle on its row's formal layouts. +set -euo pipefail +HERE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +: "${RAX_ROOT:?set RAX_ROOT to RAX's checkout (robot-agent-exploration/rax, branch libero-pro/native)}" +: "${RAX_SIM_GPU:?set RAX_SIM_GPU to the simulators' GPU (an ordinal or UUID)}" +RAX_ROOT="$(cd "$RAX_ROOT" && pwd)" +RAX_PYTHON="$RAX_ROOT/runtime/envs/host/bin/python" +[[ -x "$RAX_PYTHON" ]] || { echo "$RAX_PYTHON: set RAX up first (README.md: setup_host_env.sh, ...)" >&2; exit 1; } +# The RAX commit this example was written against; another one is run, but named. +PINNED=1767412c5300b9358059ae6a39740c3c28d2b8b9 +ACTUAL="$(git -C "$RAX_ROOT" rev-parse HEAD 2>/dev/null || echo unknown)" +[[ "$ACTUAL" == "$PINNED" ]] || echo "note: RAX_ROOT is at $ACTUAL, not the pinned $PINNED" >&2 +if [[ -n "${RAX_KEY_FILE:-}" ]]; then + RAX_KEY_FILE="$(cd "$(dirname "$RAX_KEY_FILE")" && pwd)/$(basename "$RAX_KEY_FILE")" + [[ -f "$RAX_KEY_FILE" ]] || { echo "RAX_KEY_FILE $RAX_KEY_FILE is no file" >&2; exit 1; } +else + echo "note: no RAX_KEY_FILE: the sessions have no Gemini perception tool (the paper's sessions had one)" >&2 +fi +CONFIG="${RAX_CONFIG:-run.yaml}" +HERMIT="${HERMIT_PYTHON:-python}" +[[ "$HERMIT" != */* || "$HERMIT" == /* ]] || HERMIT="$PWD/$HERMIT" # a relative path: from here, as given +cd "$HERE" +"$HERMIT" rows.py --out . # tasks/ and splits/: the rows every config reads + +OUT="${RAX_OUT:-$HERE/../runs/rax}" +mkdir -p "$OUT" +OUT="$(cd "$OUT" && pwd)" +case "$(cd "$OUT" && pwd -P)/" in # RAX's checkout is shown to the sandboxes in part; the runs never + "$(cd "$RAX_ROOT" && pwd -P)"/*) echo "RAX_OUT ($OUT) lies inside RAX_ROOT: keep the runs elsewhere" >&2; exit 2 ;; +esac + +# RAX's host service: the sessions' frontends and simulators, on the host, on RAX's host Python +PORT="${RAX_PORT:-8130}" +NONCE="$$-$RANDOM-$(date +%s%N)" # this launch's service answers /health with it, another run's not +"$RAX_PYTHON" "$HERE/service.py" --port "$PORT" --rax-root "$RAX_ROOT" --tasks "$HERE/tasks" \ + --workspaces "$OUT/actor-logs" --state "$OUT/rax-service" --sim-gpu "$RAX_SIM_GPU" --nonce "$NONCE" \ + ${RAX_KEY_FILE:+--key-file "$RAX_KEY_FILE"} > "$OUT/rax-service.log" 2>&1 & +SERVICE=$! +trap 'kill "$SERVICE" 2>/dev/null || true; wait "$SERVICE" 2>/dev/null || true' EXIT +ours() { curl -sf "http://127.0.0.1:$PORT/health" 2>/dev/null | grep -qF "\"nonce\": \"$NONCE\""; } +for _ in $(seq 1 30); do + ours && break + kill -0 "$SERVICE" 2>/dev/null || { echo "the RAX service failed (port taken?): $OUT/rax-service.log" >&2; exit 1; } + sleep 1 +done +ours || { echo "the RAX service did not come up on port $PORT: $OUT/rax-service.log" >&2; exit 1; } +# The sessions reach the service (environment.env); the judge reads the ledger and runs RAX's formal batches +export RAX_ROOT RAX_SERVICE_URL="http://127.0.0.1:$PORT" RAX_STATE="$OUT/rax-service" RAX_KEY_FILE="${RAX_KEY_FILE:-}" + +MODE=train +if [[ "${1:-}" == train || "${1:-}" == eval ]]; then MODE="$1"; shift; fi +# The adapter tree: a config's own; eval_*.yaml evaluate run.yaml's (its tags: rax-libero/final, rax-libero/ckpt-*) +TREE="$(basename "$CONFIG" .yaml)" +[[ "$TREE" != eval_* ]] || TREE=run +"$HERMIT" -m hermit.cli "$MODE" --config "$CONFIG" "agent.params.rax_root=$RAX_ROOT" \ + "agent.params.logs=$OUT/actor-logs" "trainer.output_dir=$OUT" "trainer.tree_dir=$OUT/trees/${RAX_TREE:-$TREE}" "$@" diff --git a/examples/libero/rax/rows.py b/examples/libero/rax/rows.py new file mode 100644 index 00000000..37dc38d1 --- /dev/null +++ b/examples/libero/rax/rows.py @@ -0,0 +1,92 @@ +"""LIBERO's forty tasks (RAX's catalog: Spatial, Object, Goal and Long, libero_10) as RAX sessions, in task directories +(Harbor's format; each read back as its row by `task_row`, this folder's data.view), and the splits this folder's +configs read. A row is one RAX session in code mode: its exploration layouts and episodes, and the formal layouts the +judge plays its submitted bundle on. + +| split | its rows | exploration (collection 0: layout i is env.seed(1000 + i), then reset) | formal (the judge) | +|---|---|---|---| +| train | train-, 40 | layouts 100-119 | official LIBERO, init states 0-42 (collection 1) | +| val | val-, 40 | layouts 200-219 | official LIBERO, init states 43-49 (collection 1) | +| test | test-, 40 | layouts 0-19 (RAX's own) | LIBERO-Pro swap, init states 0-49 (collection 2) | +| official | official-, 40 | layouts 0-19 (RAX's own) | official LIBERO, init states 0-49 (the paper's table) | +| smoke | smoke-libero_spatial_0 | layouts 300-301 | official LIBERO, init states 0-1 | +| smoke_test | smoke_test-libero_spatial_0 | layouts 302-303 | LIBERO-Pro swap, init states 0-1 | + +Exploration never plays a stored init state of any collection (RAX's collection 0 is fresh seeded resets of the +original task), and train, val, test and the smokes explore disjoint layouts (official explores test's: RAX's own). +Training and validation are scored only on official LIBERO's states, and on disjoint ones; test only on LIBERO-Pro's +swap states, which no training or validation session plays or is scored on. Twenty episodes is the paper's +exploration budget (Appendix C.7); RAX's optional second stage on swap layouts (collection 6) is not a split here. +`official` is the paper's protocol, for RAX as published: its states are the training and validation splits'. + + python rows.py --out . (launch.sh) +""" +from __future__ import annotations + +import argparse +from pathlib import Path +import sys + +SUITES = ("libero_spatial", "libero_object", "libero_goal", "libero_10") +TASKS = [f"{suite}_{i}" for suite in SUITES for i in range(10)] +EPISODES = 20 +SPLITS = { + "train": {"exploration_start": 100, "formal_collection": 1, "formal_first": 0, "formal_episodes": 43, + "score_label": "official LIBERO init states 0-42"}, + "val": {"exploration_start": 200, "formal_collection": 1, "formal_first": 43, "formal_episodes": 7, + "score_label": "official LIBERO init states 43-49"}, + "test": {"exploration_start": 0, "formal_collection": 2, "formal_first": 0, "formal_episodes": 50, + "score_label": "LIBERO-Pro swap init states 0-49"}, + "official": {"exploration_start": 0, "formal_collection": 1, "formal_first": 0, "formal_episodes": 50, + "score_label": "official LIBERO init states 0-49"}, +} +SMOKE = { # one task, two episodes: a training row and a test row of its own (hermit refuses a task in both) + "smoke": {"exploration_start": 300, "formal_collection": 1, "formal_first": 0, "formal_episodes": 2, + "score_label": "official LIBERO init states 0-1"}, + "smoke_test": {"exploration_start": 302, "formal_collection": 2, "formal_first": 0, "formal_episodes": 2, + "score_label": "LIBERO-Pro swap init states 0-1"}, +} + + +def task_row(task: dict) -> dict: + """A task directory's row as it was written: its id and its [metadata] (every config's data.view).""" + if "instruction" not in task: + return dict(task) + return {"id": task["id"], **(task.get("metadata") or {})} + + +def rows() -> dict[str, list[dict]]: + out = {split: [{"id": f"{split}-{t}", "task": t, "split": split, "episodes": EPISODES, "exploration_collection": 0, + **settings} for t in TASKS] for split, settings in SPLITS.items()} + for split, settings in SMOKE.items(): + out[split] = [{"id": f"{split}-libero_spatial_0", "task": "libero_spatial_0", "split": split, "episodes": 2, + "exploration_collection": 0, **settings}] + return out + + +def instruction(row: dict) -> str: + last = row["formal_first"] + row["formal_episodes"] - 1 + return (f"LIBERO task {row['task']}: one RAX exploration session in code mode, {row['episodes']} exploration " + f"episodes on fresh layouts {row['exploration_start']}-{row['exploration_start'] + row['episodes'] - 1}; " + f"the submitted bundle is scored on {row['score_label']} (collection {row['formal_collection']}, " + f"layouts {row['formal_first']}-{last}).") + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--out", type=Path, default=Path(".")) + args = ap.parse_args() + sys.path.insert(0, str(Path(__file__).resolve().parents[3])) # the checkout's hermit, when run from here + from hermit.task.directory import write_task + out = args.out.resolve() + for split, group in rows().items(): + for row in group: + write_task(out / "tasks" / row["id"], instruction(row), + metadata={k: v for k, v in row.items() if k != "id"}, + environment={"network_mode": "no-network"}) + (out / "splits").mkdir(parents=True, exist_ok=True) + (out / "splits" / f"{split}.txt").write_text("".join(r["id"] + "\n" for r in group)) + + +if __name__ == "__main__": + main() diff --git a/examples/libero/rax/run.yaml b/examples/libero/rax/run.yaml new file mode 100644 index 00000000..b6352782 --- /dev/null +++ b/examples/libero/rax/run.yaml @@ -0,0 +1,66 @@ +# RAX on LIBERO (arXiv:2610.22496): one RAX exploration session per task in code mode, as the paper runs its LIBERO +# sessions (Appendix C.7: Claude Code with Claude Opus 5.5 at xhigh effort, two exploration environments, at most 20 +# exploration episodes on fresh layouts, three terminal-state demonstration images, Gemini perception when +# RAX_KEY_FILE is given), with RAX's continual learning (§3.4) across the sessions: the skill library (template rax) +# that each session clones, uses and merges into, and that the rax Evolver carries to the next session with RAX's own +# merge. Started by launch.sh (README.md). +# +# Data (rows.py, written by launch.sh into tasks/ and splits/), the forty tasks of LIBERO's Spatial, Object, Goal and +# Long suites in every split, each a session that explores fresh seeded layouts of the original task (RAX's +# collection 0) and is scored on held-out stored init states it never plays: +# train scored on official LIBERO init states 0-42 (exploration layouts 100-119): the training rollouts +# val scored on official LIBERO init states 43-49 (layouts 200-219): eval_val.yaml, to choose among checkpoints +# test scored on LIBERO-Pro's swap init states 0-49 (layouts 0-19, RAX's own): this config's `hermit eval` +# RAX has no validation step of its own, so the Evolver is given no validation split. +data: + tasks: tasks # rows.py's task directories, each read as its row + view: rows.py:task_row + train: splits/train.txt + test: splits/test.txt + step_size: 1 # one session a step: each starts from the library the last one left, as in RAX + shuffle: false # LIBERO's order: Spatial, Object, Goal, then Long +task_info: task-info +agent: + base: claude + concurrency: 1 + model: {name: claude-opus-5-5, login: claude, effort: xhigh} # the paper's agent + params: + prompt: hermit.agent.evolver.methods.rax.actor:prompt + prepare: hermit.agent.evolver.methods.rax.actor:prepare + answer: hermit.agent.evolver.methods.rax.actor:answer + collect: hermit.agent.evolver.methods.rax.actor:collect + rax_root: $RAX_ROOT # RAX's checkout (launch.sh passes it expanded) + claude: + web_search: false # RAX's agent works offline (its DENIED_TOOLS: WebFetch, WebSearch) + timeout_s: 172800 # Hermit's cap on a session (RAX sets none): 20 episodes and the work between + args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] # RAX's: only the session's servers (prepare writes them) + env: # RAX's Claude Code session (harness/claude_cli/auto_research.py agent_environment) + MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: (CALL_SECONDS + 300) ms + BASH_MAX_TIMEOUT_MS: "1728000000" + DISABLE_AUTOUPDATER: "1" + CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: "0" + CLAUDE_CODE_AUTO_COMPACT_WINDOW: "250000" + ENABLE_PROMPT_CACHING_1H: "1" + CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: 1h +environment: # the task sandbox: RAX's agent Python, MCP bridge and start prompt, nothing else + read: + - $RAX_ROOT/runtime/envs/host + - $RAX_ROOT/harness/mcp_bridge.py + - $RAX_ROOT/auto_research_agent/START_PROMPT.md + env: [RAX_SERVICE_URL] # the host's RAX service (launch.sh): its 127.0.0.1 port is forwarded +judge: + path: judge.py # on the host: RAX's formal batch of the submitted bundle on the row's layouts +template: rax +evolver: + name: rax # RAX's merge of each session's skill-library merges; no learner model +sandbox: + enabled: true + enforce: required +trainer: + run_name: rax-libero + epochs: 1 + save_freq: {steps: 10, epochs: 1} # rax-libero/ckpt-step-10, -20, -30: the checkpoints eval_val.yaml compares + call_timeout_min: 60 # the Evolver's merge + budget: {usd: null, hours: 2000} +eval: + repeats: 1 diff --git a/examples/libero/rax/service.py b/examples/libero/rax/service.py new file mode 100644 index 00000000..c2417c8e --- /dev/null +++ b/examples/libero/rax/service.py @@ -0,0 +1,424 @@ +"""RAX's trusted side as a host service, for the sessions in the task sandbox (the RAX task functions: +hermit/agent/evolver/methods/rax/actor.py). + +The task sandbox has no GPU and must not see RAX's session directories, so RAX's frontend (the agent's robot, episode, +bundle and Gemini tools), its supervisor and the LIBERO simulators run here, as RAX's own launcher runs them +(robot-agent-exploration/rax libero-pro/native 1767412, on its host environment's Python). The service trusts nothing a +session sends but its workspace and its task's id: the session's settings are the task row's (--tasks, read here) and +the launcher's, and only the one workspace the framework makes for a rollout registers, once: +//-/workspaces/-/work, where //- is the +rollout's directory, made outside the sandbox and named for its task. + + POST /register {workspace, task} by the task's `prepare`, before the agent starts. RAX's operator script makes + the session's configuration (scripts/configure_auto_research.py: the row's task, exploration + layouts and episodes, and its formal layouts, which the judge plays after the session); RAX's + prepare_workspace makes its directory and workspace under RAX's artifact root, outside every + sandbox; the workspace comes back as a tar for `prepare` to write. RAX's frontend starts on a socket + in the run's own directory (/rax/sock), with the session's run tree, which the frontend writes + and the agent reads, bound from /rax/published onto /published in the frontend's own + mount namespace (bubblewrap): the agent sees that tree and nothing else of the session's directory. + A rollout has one session: a workspace registers again (the framework's retry of a session the + model never served) only while its session has spent nothing, and then starts afresh. + POST /finish {workspace} by the task's `collect` (and the judge): RAX's frontend stopped, as RAX's launcher + stops it when the agent ends; the session's state read from its directory. + GET /health + +One service a state directory (a lock in it). A service started where an earlier one ended without stopping its +sessions (killed) ends them first: their frontends, if still running, stopped (`abandoned` in the ledger). + +The ledger (each workspace's session and its state) is kept in --state, outside every sandbox; the judge reads it. +Every refusal is a 200 with {ok: false, error}. Started by launch.sh: + + $RAX_ROOT/runtime/envs/host/bin/python service.py --port 8130 --rax-root $RAX_ROOT --tasks tasks \ + --workspaces --state --sim-gpu 0 [--key-file ] +""" +from __future__ import annotations + +import argparse +import base64 +import fcntl +import io +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +from pathlib import Path +import re +import select +import signal +import subprocess +import sys +import tarfile +import threading +import time +import tomllib +import uuid + +HOME_NAME = "agent-home" # RAX's CLI home of the session, unused here (the CLI is Hermit's) +STOP_SECONDS = 120 # RAX's SERVER_STOP_SECONDS +SOCKET = "robot.sock" +PUBLISHED_PARTS = ("runs", "episode_reviews") # RAX's PUBLISHED_PARTS +NANODOLLARS = 1_000_000_000 # RAX's billing unit (services/controller/billing.py) + + +def rows_of(tasks: Path) -> dict[str, dict]: + """Every task's row by id: a task directory's task.toml [metadata] (rows.py writes them), with its id.""" + rows = {} + for toml in sorted(Path(tasks).glob("*/task.toml")): + data = tomllib.loads(toml.read_text()) + rows[toml.parent.name] = {"id": toml.parent.name, **(data.get("metadata") or {})} + return rows + + +def _json(path: Path) -> dict: + try: + value = json.loads(Path(path).read_text()) + except (OSError, ValueError): + return {} + return value if isinstance(value, dict) else {} + + +def gemini_usd(state: dict) -> float: + """What a session's Gemini calls cost, as RAX's supervisor reports it (gemini_spend, in nanodollars): RAX's + frontend makes them on the host, outside the framework's model layer.""" + return round(int((state.get("gemini_spend") or {}).get("reported") or 0) / NANODOLLARS, 6) + + +def spent(root: Path) -> bool: + """Whether a RAX session has spent anything: an episode started (or charged in its parallel pool), a bundle + registered, a result, a submission.""" + state, pool = _json(Path(root) / "state.json"), _json(Path(root) / "exploration" / "state.json") + return bool(state.get("exploration_started") or state.get("bundles") or state.get("results") + or state.get("submission") or pool.get("episodes")) + + +class Ledger: + """Each workspace's session (its RAX directory, its state), on disk: whole or not at all.""" + + def __init__(self, path: Path): + self.path, self.lock = Path(path), threading.RLock() + self.data = json.loads(self.path.read_text()) if self.path.is_file() else {} + + def save(self) -> None: + part = self.path.with_suffix(".part") + part.write_text(json.dumps(self.data, indent=1)) + part.replace(self.path) + + +class Frontend: + """One session's RAX frontend under bubblewrap: the bwrap process, the frontend's own pid (bwrap's --info-fd) and + the short link to its socket's directory.""" + + def __init__(self, process: subprocess.Popen, pid: int | None, link: Path): + self.process, self.pid, self.link = process, pid, link + + def stop(self) -> None: + """RAX's end_process: SIGTERM to the frontend (it stops its episodes and simulators), SIGKILL after + STOP_SECONDS. The frontend itself gets the signal, never bwrap, which would leave it no time to stop.""" + try: + if self.process.poll() is None: + try: + os.kill(self.pid or self.process.pid, signal.SIGTERM) + self.process.wait(STOP_SECONDS) + except subprocess.TimeoutExpired: + os.killpg(self.process.pid, signal.SIGKILL) + self.process.wait(30) + except ProcessLookupError: + self.process.wait(30) + finally: + self.link.unlink(missing_ok=True) + + +def _is_frontend(pid, root: str) -> bool: + """Whether a process is still RAX's frontend of the session at `root` (its command line names its configuration).""" + try: + parts = Path(f"/proc/{int(pid)}/cmdline").read_bytes().decode(errors="replace").split("\0") + except (OSError, ValueError, TypeError): + return False + return "services.controller.frontend" in parts and str(Path(root) / "configuration.json") in parts + + +class Service: + def __init__(self, args, rows: dict): + self.args, self.rows = args, rows + self.rax = args.rax_root.resolve() + self.workspaces = [w.resolve() for w in args.workspaces] + # One service a state directory: a second launch on the same runs would share (and end) the first's sessions + self.held = open(args.state / "service.lock", "a") + try: + fcntl.flock(self.held, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + self.held.close() + raise RuntimeError(f"another RAX service uses {args.state}: one launch at a time on a RAX_OUT") from None + self.ledger = Ledger(args.state / "ledger.json") + self.frontends: dict[str, Frontend] = {} + self.registering = threading.Lock() # one registration at a time + self.links = args.socket_links.resolve() + self.links.mkdir(parents=True, exist_ok=True, mode=0o700) + sys.path.insert(0, str(self.rax)) + self._reap() + + def _reap(self) -> None: + """What a service before this one left open (it ended without stopping its sessions: killed, or its machine + restarted): each unfinished session's frontend, if still running, is stopped, and the session ended.""" + for key, entry in list(self.ledger.data.items()): + if entry.get("finished"): + continue + pid = entry.get("frontend_pid") + if _is_frontend(pid, entry["root"]): + os.kill(int(pid), signal.SIGTERM) + deadline = time.monotonic() + STOP_SECONDS + while _is_frontend(pid, entry["root"]) and time.monotonic() < deadline: + time.sleep(0.2) + if _is_frontend(pid, entry["root"]): + os.kill(int(pid), signal.SIGKILL) + self._end(entry, None, abandoned=True) + + def _end(self, entry: dict, frontend: Frontend | None, **mark) -> dict: + """A session ended: its frontend stopped (RAX's frontend ends its episodes and simulators), its facts read from + its directory and kept in the ledger.""" + if frontend is not None: + frontend.stop() + state = _json(Path(entry["root"]) / "state.json") + configuration = _json(Path(entry["root"]) / "configuration.json") + submission = state.get("submission") or {} + facts = {"session": entry["session"], "submitted_bundle": submission.get("bundle"), + "submitted_sha256": submission.get("sha256"), + "rehearsals": sum(r.get("mode") == "rehearsal" for r in state.get("results", [])), + "exploration_used": state.get("exploration_started", 0), + "exploration_budget": len(configuration.get("exploration_seeds") or []), + "gemini_usd": gemini_usd(state)} + with self.ledger.lock: + entry.update(finished=entry.get("finished") or time.time(), **facts, **mark) + self.ledger.save() + return facts + + # ----- checks ----- + + def _session_dirs(self, body: dict) -> tuple[Path, Path, Path, dict]: + """(workspace, its RAX directory, its rollout, the task's row) of a registration, or a refusal.""" + given = Path(str(body.get("workspace", ""))) + row = self.rows.get(str(body.get("task"))) + if row is None: + raise ValueError(f"no task {body.get('task')!r} in this service's tasks") + workspace = given.resolve() + # the names the framework gives the rollout (hermit.isolate._safe) and its session in it (acting/workspace.py) + outer = re.escape(re.sub(r"[^A-Za-z0-9._-]+", "_", row["id"])[:60] or "task") + r"-[0-9a-f]+" + inner = re.escape(re.sub(r"[^A-Za-z0-9_.-]", "_", row["id"])[:80]) + r"-[0-9a-f]+" + for served in self.workspaces: + parts = workspace.relative_to(served).parts if workspace.is_relative_to(served) else () + if (len(parts) == 5 and re.fullmatch(outer, parts[1]) and parts[2] == "workspaces" + and re.fullmatch(inner, parts[3]) and parts[4] == "work"): + rollout = served / parts[0] / parts[1] + break + else: + raise ValueError(f"{given} is not the workspace of a rollout of task {row['id']} this service serves") + if workspace != given.absolute() or not workspace.is_dir(): + raise ValueError(f"{given} is not a directory of its own (no link on its path)") + mine = workspace.parent / "rax" + for part in ("", "published", *(f"published/{p}" for p in PUBLISHED_PARTS), "sock"): + path = mine / part + if path.is_symlink() or not path.is_dir(): + raise ValueError(f"{path} must be a directory the task's prepare made") + return workspace, mine, rollout, row + + # ----- RAX ----- + + def _configure(self, row: dict) -> Path: + """RAX's operator script: a fresh session configuration of the row, its path (operator-input.json).""" + a = self.args + command = [sys.executable, "scripts/configure_auto_research.py", "--task", str(row["task"]), + "--sim-gpu", str(a.sim_gpu), "--episodes", str(row["episodes"]), + "--exploration-collection", str(row.get("exploration_collection", 0)), + "--exploration-start-seed", str(row["exploration_start"]), + "--exploration-envs", str(a.exploration_envs), "--subagents", str(a.subagents), + "--agent-cli", "claude", "--agent-effort", a.agent_effort, + "--external-perception", "on" if a.key_file else "off", + "--formal-eval-seed", str(row["formal_collection"]), "--formal-seed", str(row["formal_first"]), + "--formal-episodes", str(row["formal_episodes"]), "--formal-workers", str(a.formal_workers)] + done = subprocess.run(command, cwd=self.rax, capture_output=True, text=True, timeout=900, + env={**os.environ, "PYTHONPATH": str(self.rax)}) + if done.returncode: + raise RuntimeError(f"configure_auto_research: {(done.stderr or done.stdout).strip()[-800:]}") + return Path(done.stdout.strip().splitlines()[-1]).resolve() + + def _workspace(self, operator_input: Path): + """RAX's prepare_workspace for the configuration: the session's directory, configuration.json, run tree and + workspace (RAX's template, skills, TASK.md, demonstrations). Returns (config, workspace tar).""" + from harness.codex_cli.auto_research import prepare_workspace + from services.controller.frontend import load_configuration + config = load_configuration(operator_input) + made = prepare_workspace(config, HOME_NAME) + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:") as archive: + root = Path(made["workspace"]) + for path in sorted(root.rglob("*")): + relative = path.relative_to(root).as_posix() + if path.is_symlink() or relative.startswith("runtime/autonomous_controller"): + continue # the run tree: `prepare` links the agent's own view + archive.add(path, arcname=relative, recursive=False) + return config, base64.b64encode(buffer.getvalue()).decode() + + def _start_frontend(self, config, workspace: Path, mine: Path) -> Frontend: + """RAX's start_frontend (harness/codex_cli/auto_research.py), in a mount namespace where the session's run tree + is the run's own published/, and with the socket in the run's sock/ (reached through a short link: a socket's + path is at most 107 bytes). No agent pid file: the sandboxed CLI's processes are not this host's to pause.""" + link = self.links / uuid.uuid4().hex[:12] + link.symlink_to(mine / "sock", target_is_directory=True) + socket = mine / "sock" / SOCKET + socket.unlink(missing_ok=True) + info_read, info_write = os.pipe() + args = ["bwrap", "--dev-bind", "/", "/", "--bind", str(mine / "published"), str(config.root / "published"), + "--info-fd", str(info_write), "--", + sys.executable, "-m", "services.controller.frontend", + "--config", str(config.root / "configuration.json"), + "--workspace", str(workspace), "--socket", str(link / SOCKET)] + if self.args.key_file: + args += ["--key-file", str(self.args.key_file)] + env = {k: v for k, v in os.environ.items() if not k.startswith("RAX_")} + env["PYTHONPATH"] = str(self.rax) + with open(config.root / "frontend.log", "ab") as log: + process = subprocess.Popen(args, cwd=self.rax, env=env, stdout=log, stderr=log, start_new_session=True, + pass_fds=(info_write,)) + os.close(info_write) + data = b"" + try: # bwrap writes {"child-pid": ...} and closes it + while select.select([info_read], [], [], 10)[0]: + chunk = os.read(info_read, 4096) + if not chunk: + break + data += chunk + finally: + os.close(info_read) + try: + pid = int(json.loads(data)["child-pid"]) + except (ValueError, KeyError, TypeError): + pid = None + frontend = Frontend(process, pid, link) + deadline = time.monotonic() + self.args.frontend_timeout + while not socket.exists(): + if process.poll() is not None or pid is None or time.monotonic() >= deadline: + frontend.stop() + tail = (config.root / "frontend.log").read_bytes()[-1500:].decode(errors="replace") + raise RuntimeError(f"RAX's frontend did not start: {tail}") + time.sleep(0.05) + return frontend + + # ----- routes ----- + + def register(self, body: dict) -> dict: + workspace, mine, rollout, row = self._session_dirs(body) + key = str(workspace) + with self.registering: + with self.ledger.lock: + others = [k for k, e in self.ledger.data.items() if e.get("rollout") == str(rollout) and k != key] + previous = self.ledger.data.get(key) + if others: + raise ValueError(f"the rollout {rollout.name} has a RAX session already") + if previous is not None and spent(Path(previous["root"])): + raise ValueError("this workspace's RAX session has started; a session is never started again") + if previous is not None: + with self.ledger.lock: + old = self.frontends.pop(key, None) + if old is not None: + old.stop() # the call run again: its first session ends here + operator_input = self._configure(row) + config, archive = self._workspace(operator_input) + frontend = self._start_frontend(config, workspace, mine) + from services.mcp_contract import Contract + with self.ledger.lock: + self.frontends[key] = frontend + self.ledger.data[key] = {"task": row["id"], "rax_task": row["task"], "rollout": str(rollout), + "root": str(config.root), "session": config.root.name, + "started": time.time(), "finished": None, "frontend_pid": frontend.pid, + "superseded": ([*previous.get("superseded", []), previous["root"]] + if previous else [])} + self.ledger.save() + return {"ok": True, "workspace": archive, "session": config.root.name, "cpus": config.training.cpus, + "subagents": Contract.from_config(config).subagent_cap} + + def finish(self, body: dict) -> dict: + key = str(Path(str(body.get("workspace", ""))).resolve()) + with self.ledger.lock: + entry = self.ledger.data.get(key) + frontend = self.frontends.pop(key, None) + if entry is None: + return {"ok": False, "error": "no session registered for this workspace"} + return {"ok": True, **self._end(entry, frontend)} + + def stop(self) -> None: + """The service's end (launch.sh's trap): every session still open is ended.""" + with self.ledger.lock: + open_ = [(self.ledger.data.get(k), f) for k, f in self.frontends.items()] + self.frontends.clear() + for entry, frontend in open_: + if entry is not None: + self._end(entry, frontend) + else: + frontend.stop() + + +def handler(service: Service): + class Handler(BaseHTTPRequestHandler): + def _reply(self, body: dict) -> None: + data = json.dumps(body).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): # the nonce: launch.sh knows its own service by it + self._reply({"ok": self.path == "/health", "nonce": service.args.nonce}) + + def do_POST(self): + try: + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + route = {"/register": service.register, "/finish": service.finish}.get(self.path) + self._reply(route(body) if route else {"ok": False, "error": f"no route {self.path}"}) + except Exception as exc: # a bad request is the session's error, not the service's end + self._reply({"ok": False, "error": f"{type(exc).__name__}: {exc}"}) + + def log_message(self, *args): + pass + return Handler + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--host", default="127.0.0.1") + ap.add_argument("--port", type=int, default=8130) + ap.add_argument("--rax-root", type=Path, required=True, help="RAX's checkout (libero-pro/native), set up") + ap.add_argument("--tasks", type=Path, required=True, help="the task directories (rows.py)") + ap.add_argument("--workspaces", type=Path, action="append", required=True, + help="a directory whose rollouts this service serves (agent.params.logs; repeatable)") + ap.add_argument("--state", type=Path, required=True, help="the ledger's directory, outside every sandbox") + ap.add_argument("--sim-gpu", required=True, help="the simulators' GPU (ordinal or UUID): RAX's --sim-gpu") + ap.add_argument("--key-file", type=Path, help="RAX's --key-file: the OpenRouter key of its Gemini router " + "(gemini_generate, external perception); none: perception off") + ap.add_argument("--agent-effort", default="xhigh", choices=("xhigh", "max"), + help="RAX's --agent-effort (its configuration's; the session's own is the config's)") + ap.add_argument("--exploration-envs", type=int, default=2, help="RAX's --exploration-envs (the paper's 2)") + ap.add_argument("--subagents", type=int, default=0, help="RAX's --subagents (0: one per environment)") + ap.add_argument("--formal-workers", type=int, default=4, help="RAX's --formal-workers") + ap.add_argument("--socket-links", type=Path, default=Path.home() / ".cache" / "rax-hermit" / "s", + help="a directory of short links to the sessions' socket directories") + ap.add_argument("--frontend-timeout", type=float, default=60.0) + ap.add_argument("--nonce", default="") + args = ap.parse_args() + args.state.mkdir(parents=True, exist_ok=True) + if len(str(args.socket_links.resolve() / ("0" * 12) / SOCKET)) > 100: + sys.exit(f"--socket-links {args.socket_links}: too long for a socket path (at most 107 bytes)") + try: + service = Service(args, rows_of(args.tasks)) + except RuntimeError as exc: + sys.exit(str(exc)) + + def _bye(sig, frame): # launch.sh's trap: the sessions go with the service + service.stop() + sys.exit(0) + signal.signal(signal.SIGTERM, _bye) + ThreadingHTTPServer((args.host, args.port), handler(service)).serve_forever() + + +if __name__ == "__main__": + main() diff --git a/examples/libero/rax/smoke.yaml b/examples/libero/rax/smoke.yaml new file mode 100644 index 00000000..ce373df5 --- /dev/null +++ b/examples/libero/rax/smoke.yaml @@ -0,0 +1,57 @@ +# Smoke of run.yaml: the same session, service, judge and Evolver on one task with Claude Haiku 5.5: training on +# smoke-libero_spatial_0 (two exploration episodes on layouts 300-301, scored on official LIBERO init states 0-1), its +# evaluation on smoke_test-libero_spatial_0 (layouts 302-303, scored on LIBERO-Pro swap states 0-1). It checks RAX's +# setup, the service, the robot tools in the sandbox, the library's clone and merge, and the formal batch before a +# long run: +# RAX_CONFIG=smoke.yaml ./launch.sh then RAX_CONFIG=smoke.yaml ./launch.sh eval --adapter final +data: + tasks: tasks # rows.py's task directories, each read as its row + view: rows.py:task_row + train: splits/smoke.txt + test: splits/smoke_test.txt + step_size: 1 # one session a step: each starts from the library the last one left, as in RAX + shuffle: false # LIBERO's order: Spatial, Object, Goal, then Long +task_info: task-info +agent: + base: claude + concurrency: 1 + model: {name: claude-haiku-5-5, login: claude, effort: medium} + params: + prompt: hermit.agent.evolver.methods.rax.actor:prompt + prepare: hermit.agent.evolver.methods.rax.actor:prepare + answer: hermit.agent.evolver.methods.rax.actor:answer + collect: hermit.agent.evolver.methods.rax.actor:collect + rax_root: $RAX_ROOT # RAX's checkout (launch.sh passes it expanded) + claude: + web_search: false # RAX's agent works offline (its DENIED_TOOLS: WebFetch, WebSearch) + timeout_s: 10800 # Hermit's cap on the smoke's session + args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] # RAX's: only the session's servers (prepare writes them) + env: # RAX's Claude Code session (harness/claude_cli/auto_research.py agent_environment) + MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: (CALL_SECONDS + 300) ms + BASH_MAX_TIMEOUT_MS: "1728000000" + DISABLE_AUTOUPDATER: "1" + CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: "0" + CLAUDE_CODE_AUTO_COMPACT_WINDOW: "250000" + ENABLE_PROMPT_CACHING_1H: "1" + CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: 1h +environment: # the task sandbox: RAX's agent Python, MCP bridge and start prompt, nothing else + read: + - $RAX_ROOT/runtime/envs/host + - $RAX_ROOT/harness/mcp_bridge.py + - $RAX_ROOT/auto_research_agent/START_PROMPT.md + env: [RAX_SERVICE_URL] # the host's RAX service (launch.sh): its 127.0.0.1 port is forwarded +judge: + path: judge.py # on the host: RAX's formal batch of the submitted bundle on the row's layouts +template: rax +evolver: + name: rax # RAX's merge of each session's skill-library merges; no learner model +sandbox: + enabled: true + enforce: required +trainer: + run_name: rax-libero-smoke + epochs: 1 + call_timeout_min: 30 # the Evolver's merge + budget: {usd: null, hours: 8} +eval: + repeats: 1 diff --git a/examples/libero/rax/task-info/README.md b/examples/libero/rax/task-info/README.md new file mode 100644 index 00000000..e9480ed7 --- /dev/null +++ b/examples/libero/rax/task-info/README.md @@ -0,0 +1,17 @@ +# LIBERO with RAX + +Each task is one LIBERO task of RAX's catalog (`libero_spatial_0`..`9`, `libero_object_*`, `libero_goal_*`, +`libero_10_*`) run as one RAX exploration session in code mode (robot-agent-exploration/rax libero-pro/native): a +Franka Panda in LIBERO's official environment, driven through RAX's MCP tools (`libero_step`, 7-D OSC_POSE delta rows +at 20 Hz; `libero_observe`, agentview and wrist RGB-D; `libero_pixel_to_position`; the episode and bundle tools). The +agent explores fresh seeded layouts, solves the task by hand, writes a controller (`code//controller.py`), +registers, rehearses and submits it; the judge plays the submitted bundle alone on the row's held-out formal layouts +(official LIBERO init states, or LIBERO-Pro's swap states) and scores the share of successful episodes (LIBERO's own +success check). The row's fields: `task`, `split`, `episodes`, `exploration_start`, `formal_collection`, +`formal_first`, `formal_episodes`, `score_label`. + +A task's record (learning_material/current/tasks/.json) carries, under `pipeline_extra.task`, the session's facts: +whether it submitted a bundle, its rehearsals, the exploration episodes it used, what its Gemini calls cost +(`gemini_usd`), and what it merged into its skill library (`library`: the bundle in the run's log, `library.json`). The +log (`trajectories//`) keeps the CLI's stream, the session's notes and code (`session/memory/`, `session/code/`) and +the library bundle. diff --git a/hermit/adapter/templates/rax/.hermit/EVOLVER.md b/hermit/adapter/templates/rax/.hermit/EVOLVER.md new file mode 100644 index 00000000..07ef079d --- /dev/null +++ b/hermit/adapter/templates/rax/.hermit/EVOLVER.md @@ -0,0 +1,18 @@ +# RAX adapter: structure + +The adapter is RAX's skill library (arXiv:2610.22496, §3.4; robot-agent-exploration/rax real/rainbow 36c926c, +`services/skill_library.py`), with the format RAX's merge enforces: + +| path | what it is | +|---|---| +| `INDEX.md` | one table row per skill: `\| [slug](skills/slug/SKILL.md) \| status \| what it does \| when to use \|` | +| `skills//SKILL.md` | frontmatter `name` (the folder), `description`, `status` (draft, verified or deprecated), `robot`, `entry`; sections When to use, Preconditions, Procedure, Code, Checks (with `### Perception checkpoints`), Failure modes, Evidence | +| `skills//code/*.py` | the entry defines `main(ctx, ...)` returning `{ok, measured, why}` | +| `skills//evidence/runs.jsonl` | one JSON object per run, with session, date, commit, outcome, unattended, conditions, checks, images | +| `skills//evidence/images/` | jpg or png, at most 400 kB each; at least one per skill | + +- `verified` needs at least 2 unattended successful runs with images. A skill is never deleted: it is set to + `deprecated`, with why. A skill is at most 25 MB, and a file at most 2 MB. +- The `rax` Evolver writes the library only through RAX's merge of what the step's sessions merged; a learner that + edits it by hand keeps to the same rules (`.hermit/check.py` runs RAX's checks on every skill). +- Fixed: `.hermit/`, `ADAPTER.md`, `README.md`, `exports.yaml`. diff --git a/hermit/adapter/templates/rax/.hermit/adapter.yaml b/hermit/adapter/templates/rax/.hermit/adapter.yaml new file mode 100644 index 00000000..9b92aafd --- /dev/null +++ b/hermit/adapter/templates/rax/.hermit/adapter.yaml @@ -0,0 +1,23 @@ +# The RAX adapter (arXiv:2610.22496, §3.4): RAX's skill library, the memory that carries verified, executable robot +# skills across sessions and tasks. Its format and rules are RAX's (services/skill_library.py, real/rainbow 36c926c: +# hermit/agent/evolver/methods/rax/upstream/). The acting session clones it as skill-library/ and merges its skills +# with RAX's own merge (its skill_library_merge tool); the Evolver takes each session's merges into the library with +# that merge again. +template: + id: rax + version: "1.0" + contract: "2" + name: RAX skill library +structure: + learnable: + - path: INDEX.md # one table row per skill + format: {text: true, max_bytes: 200000} + - path: skills/** # skills//{SKILL.md, code/, evidence/}: RAX's per-file limit + format: {max_bytes: 2000000} + fixed: + - ADAPTER.md # where the library is in a session, and RAX's two rules of using it + - README.md # the library's README, as RAX writes it for this robot + - exports.yaml +check: .hermit/check.py:check +# A session needs its clone (skill-library/), which the RAX task functions make; `hermit deploy` cannot. +plugin-portable: false diff --git a/hermit/adapter/templates/rax/.hermit/check.py b/hermit/adapter/templates/rax/.hermit/check.py new file mode 100644 index 00000000..e031c07f --- /dev/null +++ b/hermit/adapter/templates/rax/.hermit/check.py @@ -0,0 +1,30 @@ +"""Template check for `rax` adapters: the library follows RAX's format, as RAX's merge checks a session branch +(services/skill_library.py `validate_tree`, real/rainbow 36c926c: hermit/agent/evolver/methods/rax/upstream/), here +for every skill of the library rather than a branch's changed ones. No link anywhere in the library.""" +from __future__ import annotations + +from pathlib import Path + + +def check(adapter_path: str) -> list[dict]: + from hermit.agent.evolver.methods.rax import library + from hermit.agent.evolver.methods.rax.upstream import skill_library as rax + + adapter = Path(adapter_path).resolve() + if not (adapter / "INDEX.md").is_file() or not (adapter / "README.md").is_file(): + # Never pass an adapter this check cannot see (under bubblewrap, /tmp is an empty tmpfs). skills/ may be + # absent: an empty library (the template has none; the library's first commit adds RAX's skills/.gitkeep). + return [{"path": "INDEX.md", "problem": f"no rax adapter at {adapter} (INDEX.md or README.md missing or not " + f"visible)"}] + try: + files = library.library_files(adapter) + except rax.LibraryError as exc: + return [{"path": "skills", "problem": str(exc)}] + problems, _ = rax.validate_tree(adapter, [f for f in files if f != "README.md"]) + return [{"path": _path(p), "problem": p} for p in problems] + + +def _path(problem: str) -> str: + """The library path a RAX problem names (`skills/: ...` or INDEX.md), for the Trainer's repair.""" + head = problem.split(":", 1)[0] + return head if head.startswith("skills/") else "INDEX.md" if "INDEX.md" in problem else "skills" diff --git a/hermit/adapter/templates/rax/ADAPTER.md b/hermit/adapter/templates/rax/ADAPTER.md new file mode 100644 index 00000000..413d9358 --- /dev/null +++ b/hermit/adapter/templates/rax/ADAPTER.md @@ -0,0 +1,18 @@ +# The skill library + +`skill-library/` in your workspace is a git clone of this robot's skill library, on your own session branch: the +skills earlier sessions (any task) learned on this robot. The copy of the library under `hermit/rax/` is only the +library as this session started; edit and commit in `skill-library/`. Paths in this section are relative to your +workspace. + +After you read `TASK.md` and call `status`, read `skill-library/INDEX.md`: skills earlier sessions learned on this +robot, with code and evidence. Reuse the ones that match before inventing your own +([continual-learning](.agents/skills/continual-learning/SKILL.md)). + +**Teach later sessions.** Put every reusable procedure that worked into the skill library as an executable, checked +skill with its evidence and images, or improve the library skill you used; commit on your branch and merge it with +`skill_library_merge`. Do this as soon as a skill is automated (as `draft`), again when it is verified, and always +before the session ends. Follow [continual-learning](.agents/skills/continual-learning/SKILL.md). + +On this robot a skill's frames are under `runtime/autonomous_controller/runs//frames/`, and a run is unattended +when its code ran from start to end with no help from you, as in a rehearsal. diff --git a/hermit/adapter/templates/rax/INDEX.md b/hermit/adapter/templates/rax/INDEX.md new file mode 100644 index 00000000..3c1a96ca --- /dev/null +++ b/hermit/adapter/templates/rax/INDEX.md @@ -0,0 +1,4 @@ +# Skill index + +| Skill | Status | What it does | When to use | +|---|---|---|---| diff --git a/hermit/adapter/templates/rax/README.md b/hermit/adapter/templates/rax/README.md new file mode 100644 index 00000000..d8078c89 --- /dev/null +++ b/hermit/adapter/templates/rax/README.md @@ -0,0 +1,21 @@ +# libero-panda skill library + +Skills agents learned on this robot, kept across sessions. Agents read and use them, and +add or improve them on their session branch; the harness tool `skill_library_merge` +checks the format and evidence and merges into `main`. The protocol is the agent skill +`continual-learning`; the rules the merge enforces: + +- `INDEX.md`: one row per skill, `| [slug](skills/slug/SKILL.md) | status | what it does | when to use |`. +- `skills//SKILL.md` begins with frontmatter (`name` = the folder name, `description`, + `status`: draft | verified | deprecated, `robot`, `entry`: the code file, e.g. + `code/run.py`) and has the sections `## When to use`, `## Preconditions`, `## Procedure`, `## Code`, `## Checks`, `## Failure modes`, `## Evidence`. +- The entry is Python defining `main(ctx, ...)` (ctx: `api.runtime.Context`) that returns + `{"ok": bool, "measured": {...}, "why": str}`. +- `evidence/runs.jsonl`: one JSON object per run of the code with `session`, `date`, `commit`, `outcome`, `unattended`, `conditions`, `checks`, `images`; `images` are + paths under `evidence/images/` (jpg / png, at most 400 kB each). +- `## Checks` holds a `### Perception checkpoints` table: for each checkpoint the step, the + perception subagent, frames, question, expected answer, pass criterion and action on + fail (or "None"). +- At least one image per skill. `verified` needs at least 2 unattended successful + runs. A branch may only change `INDEX.md` and files under `skills/`. +- Never delete another session's skill: set its status to `deprecated` and say why. diff --git a/hermit/adapter/templates/rax/exports.yaml b/hermit/adapter/templates/rax/exports.yaml new file mode 100644 index 00000000..b148a7b7 --- /dev/null +++ b/hermit/adapter/templates/rax/exports.yaml @@ -0,0 +1,4 @@ +# What the acting agent receives: ADAPTER.md, where the library is in a session and RAX's two rules of using it. The +# library's own files reach the session as its clone, skill-library/, and RAX's skill_library_merge tool is the +# session's (the RAX task functions' prepare: hermit/agent/evolver/methods/rax/actor.py), as both are RAX's harness's. +context: ADAPTER.md diff --git a/hermit/agent/evolver/methods/rax/actor.py b/hermit/agent/evolver/methods/rax/actor.py new file mode 100644 index 00000000..5e0a4df7 --- /dev/null +++ b/hermit/agent/evolver/methods/rax/actor.py @@ -0,0 +1,326 @@ +"""RAX's exploration session (arXiv:2610.22496 §3 and Appendix C.7; robot-agent-exploration/rax libero-pro/native +1767412, pinned by the example's launch.sh) as the acting agent's task functions (agent.params.prompt, prepare, +answer, collect), for Claude Code, the paper's agent on LIBERO. They run in the task sandbox with the session; RAX's +trusted side, its frontend (the robot, episode and bundle tools), supervisor and simulators, runs on the host in the +example's service (examples/libero/rax/service.py), reached at the forwarded 127.0.0.1 port in RAX_SERVICE_URL +(environment.env). + + prepare registers the session: the service makes RAX's configuration of the task row (scripts/ + configure_auto_research.py) and RAX's workspace for it (harness/codex_cli/auto_research.py + prepare_workspace), and starts RAX's frontend on a socket in this run's own directory, with RAX's run + tree (published/) there too, where the session reads it as runtime/autonomous_controller. It writes RAX's + workspace here beside the deployment and wires the session as RAX's Claude Code launcher does + (harness/claude_cli/auto_research.py): CLAUDE.md reads AGENTS.md, .claude/skills is .agents/skills, the + frontend's MCP server through RAX's bridge (harness/mcp_bridge.py), RAX's agent environment for the + session's commands (harness/agent_host.py `environment`), and RAX's relaunch policy as a Stop hook + (stop_hook.py). With an adapter (the `rax` template), it makes the session's library repository of the + adapter's files and RAX's clone of it, skill-library/, adds RAX's continual-learning skill (library.py) + and serves RAX's skill_library_merge tool (library_server.py), as RAX's harness does for a workspace with a + library. Without one (`--adapter none`) the session is RAX's on LIBERO as published. + prompt RAX's START_PROMPT.md as its launcher gives it in code mode (`startup_prompt`) + answer the agent's last message + collect ends the session at the service (RAX's frontend stopped, as RAX stops it when the agent ends), and + returns the session's facts (the judge scores its submitted bundle with RAX's formal batch); writes what + the session merged into its library (library.export) and the session's notes and code into the log + +RAX's own checkout comes from agent.params.rax_root (its START_PROMPT.md, bridge and agent environment must be declared +readable: environment.read). The config gives the Claude Code session RAX's frontend server on the command line +(`claude.args: [--mcp-config, .rax-mcp.json]`, the file `prepare` writes) and RAX's session variables (`claude.env`). +""" +from __future__ import annotations + +import base64 +import io +import json +import os +from pathlib import Path +import re +import shlex +import shutil +import sys +import tarfile +import urllib.request + +from hermit.agent.evolver.methods.rax import library + +HERE = Path(__file__).resolve().parent +SOCKET_DIR = Path("/tmp/rax") # in the task sandbox, whose /tmp is its own: the session's socket directory +SOCKET = SOCKET_DIR / "robot.sock" # (a Unix socket's path is at most 107 bytes) +MCP_SERVER = "auto_research" # RAX's name of the frontend's MCP server +LIBRARY_SERVER = "skill_library" # skill_library_merge's server (RAX's frontend serves it with the robot's) +CLAUDE_MCP = ".rax-mcp.json" # the session's servers (claude.args: --mcp-config .rax-mcp.json) +PUBLISHED_PARTS = ("runs", "episode_reviews") # RAX's PUBLISHED_PARTS: the run tree the frontend writes +NOTES = ("memory", "code") # the session's notes and controller code, kept in the log +DENIED_TOOLS = ("WebFetch", "WebSearch") # RAX's Claude Code launcher's +SUBAGENT_TOOLS = ("Agent", "Task") # ...and these when the session's subagent cap is 0 ('Task': the old name) +PROTECTED = (".claude", ".mcp.json", CLAUDE_MCP) # RAX's protected(): the workspace's files that configure Claude Code +NOTE_FILE_BYTES = 1_000_000 +NOTE_BYTES = 20_000_000 + + +def _service(params: dict) -> str: + name = str(params.get("service_env") or "RAX_SERVICE_URL") + url = os.environ.get(name) + if not url: + raise RuntimeError(f"{name} is not set: the RAX service's URL (examples/libero/rax/launch.sh starts it)") + return url.rstrip("/") + + +def _post(url: str, body: dict, timeout: float = 1800.0) -> dict: + request = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST", + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=timeout) as response: + reply = json.loads(response.read()) + if not reply.get("ok"): + raise RuntimeError(f"RAX service {url.rsplit('/', 1)[-1]}: {reply.get('error')}") + return reply + + +def rax_root(params: dict) -> Path: + value = params.get("rax_root") + if not value: + raise ValueError("agent.params.rax_root: RAX's checkout (libero-pro/native, examples/libero/rax/launch.sh)") + return Path(os.path.expandvars(str(value))).expanduser().resolve() + + +def agent_python(rax: Path) -> Path: + """RAX's agent Python (its host environment, runtime/envs/host) by its real path, as agent_host.agent_python.""" + return (rax / "runtime" / "envs" / "host" / "bin" / "python").resolve() + + +def own(work: Path) -> Path: + """This run's RAX directory beside the workspace (/rax): the socket, the run tree, the library repository.""" + return Path(work).resolve().parent / "rax" + + +def session_name(work: Path) -> str: + """The session's name, its library branch's (session/): the run directory's, -.""" + name = re.sub(r"[^A-Za-z0-9_.-]", "_", Path(work).resolve().parent.name)[:120].lstrip("._-") + return name or "session" + + +# ---------- prompt ---------- + +def start_prompt(path: Path) -> str: + """RAX's START_PROMPT.md as its workspace renders it in code mode (agent formal off: its one block left out; + RAX's renderer drops a false block whole) and `startup_prompt` reads it (stripped).""" + text = re.sub(r"\{%\s*if agent_formal\s*%\}.*?\{%\s*endif\s*%\}", "", Path(path).read_text(), flags=re.S) + if any(mark in text for mark in ("{%", "{{", "{#")): + raise ValueError(f"{path}: a template construct this port does not render (pin RAX at the commit it reads)") + return text.strip() + + +def prompt(task: dict, params: dict) -> str: + return start_prompt(rax_root(params) / "auto_research_agent" / "START_PROMPT.md") + + +# ---------- prepare ---------- + +def _extract(data: str, work: Path) -> list[str]: + """RAX's workspace (a tar from the service) written into the session's workspace: regular files and directories + only, inside it; AGENTS.md before the deployment's own, if it wrote one (returned: the files it wrote).""" + names = [] + with tarfile.open(fileobj=io.BytesIO(base64.b64decode(data)), mode="r:") as archive: + for member in archive.getmembers(): + target = (work / member.name).resolve() + if not target.is_relative_to(work) or target == work or not (member.isfile() or member.isdir()): + raise ValueError(f"RAX workspace entry {member.name!r}: not a file or directory inside the workspace") + if member.isdir(): + target.mkdir(parents=True, exist_ok=True) + continue + target.parent.mkdir(parents=True, exist_ok=True) + content = archive.extractfile(member).read() + if member.name == "AGENTS.md" and target.is_file() and not target.is_symlink(): + content = content.rstrip(b"\n") + b"\n\n" + target.read_bytes() + target.unlink(missing_ok=True) + target.write_bytes(content) + target.chmod(0o755 if member.mode & 0o111 else 0o644) + names.append(member.name) + return names + + +def agent_environment(work: Path, rax: Path, cpus: float, cli: str | None) -> dict: + """The session's commands' environment as RAX's agent_host.environment gives it, beside what the CLI has: RAX's + agent Python first on PATH (the agent's scripts run on it), the workspace on PYTHONPATH, the robot socket, offline + package tools, math-library thread pools sized to the session's CPUs (RAX's training limits).""" + path = [str(agent_python(rax).parent), *([str(Path(cli).resolve().parent)] if cli else []), "/usr/local/bin", + "/usr/bin", "/bin"] + threads = str(max(1, -(-int(float(cpus) * 1000) // 1000))) + return {"PATH": ":".join(dict.fromkeys(path)), "RAX_MCP_SOCKET": str(SOCKET), "PYTHONPATH": str(work), + "PYTHONDONTWRITEBYTECODE": "1", "PIP_NO_INDEX": "1", "HF_HUB_OFFLINE": "1", + **{k: threads for k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", + "NUMEXPR_NUM_THREADS", "VECLIB_MAXIMUM_THREADS")}} + + +def servers(rax: Path, work: Path, with_library: bool) -> dict: + """The session's MCP servers: RAX's frontend as RAX's launcher names it (its bridge, on the agent's Python in + isolated mode, to the socket), and, with a library, skill_library_merge's (on the framework's Python).""" + out = {MCP_SERVER: {"type": "stdio", "command": str(agent_python(rax)), + "args": ["-I", str(rax / "harness" / "mcp_bridge.py"), str(SOCKET)]}} + if with_library: + from hermit.hosts.inputs import PACKAGE_ROOT + out[LIBRARY_SERVER] = {"type": "stdio", "command": sys.executable, + "args": ["-m", "hermit.agent.evolver.methods.rax.library_server", "--workspace", + str(work)], + "env": {"PYTHONPATH": PACKAGE_ROOT}} + return out + + +def stop_hook() -> dict: + """RAX's relaunch policy as the session's Stop hook (stop_hook.py), on the framework's Python in isolated mode.""" + return {"type": "command", "timeout": 60, + "command": f"{shlex.quote(sys.executable)} -I {shlex.quote(str(HERE / 'stop_hook.py'))}"} + + +def permissions(work: Path, subagents: int) -> dict: + """RAX's deny rules of the session (harness/claude_cli/auto_research.py `settings`, `agent_command`): its denied + tools, the subagent tools when the session's cap is 0, and edits of the files that configure Claude Code (absolute + paths written //like/this, as RAX writes them). They hold under bypassPermissions too.""" + rule = lambda tool, path: f"{tool}(/{path})" + guarded = [Path(work).resolve() / name for name in PROTECTED] + return {"deny": [*DENIED_TOOLS, *(SUBAGENT_TOOLS if subagents == 0 else ()), + *(rule("Edit", path) for path in guarded), *(rule("Edit", f"{path}/**") for path in guarded)]} + + +def wire_claude(work: Path, rax: Path, env: dict, with_library: bool, subagents: int = 0) -> None: + """RAX's Claude Code workspace (harness/claude_cli/auto_research.py `claude_workspace`: CLAUDE.md reads AGENTS.md, + .claude/skills is .agents/skills) with the deployment's context after it, and the session's settings: its servers + in CLAUDE_MCP, and in the project's settings the commands' environment, RAX's deny rules and the Stop hook.""" + claude = work / ".claude" + claude.mkdir(exist_ok=True) + context = work / "CLAUDE.md" + deployed = context.read_text() if context.is_file() and not context.is_symlink() else "" + context.unlink(missing_ok=True) + context.write_text("@AGENTS.md\n" + (f"\n{deployed}" if deployed.strip() else "")) + skills = claude / "skills" + if skills.is_symlink() or skills.is_file(): + skills.unlink() + elif skills.is_dir(): # the deployment's skills (the rax template has none) join RAX's + for entry in sorted(skills.iterdir()): + target = work / ".agents" / "skills" / entry.name + if not target.exists(): + target.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(entry), target) + shutil.rmtree(skills) + skills.symlink_to("../.agents/skills", target_is_directory=True) + (work / CLAUDE_MCP).write_text(json.dumps({"mcpServers": servers(rax, work, with_library)}, indent=2) + "\n") + settings = claude / "settings.json" + value = json.loads(settings.read_text()) if settings.is_file() and not settings.is_symlink() else {} + value.setdefault("env", {}).update(env) + deny = value.setdefault("permissions", {}).setdefault("deny", []) + deny += [r for r in permissions(work, subagents)["deny"] if r not in deny] + value.setdefault("hooks", {}).setdefault("Stop", []).append({"hooks": [stop_hook()]}) + settings.unlink(missing_ok=True) + settings.write_text(json.dumps(value, indent=2) + "\n") + + +def prepare(task: dict, work: Path, params: dict) -> list: + backend = str(params.get("backend") or "") + if backend != "claude": + raise ValueError(f"the RAX session runs on Claude Code (agent.base: claude, the paper's agent on LIBERO), " + f"not {backend or 'this agent'}") + work = Path(work).resolve() + rax, mine = rax_root(params), own(work) + if SOCKET_DIR.exists() and not SOCKET_DIR.is_symlink(): + # In the task sandbox /tmp is the session's own (an empty tmpfs): anything there but a link of a run before + # this one is not this session's, and is never removed. + raise RuntimeError(f"{SOCKET_DIR} exists and is not this session's link: the RAX session runs in the task " + "sandbox (sandbox.enabled), whose /tmp is its own") + shutil.rmtree(mine, ignore_errors=True) # a retry of the call starts its session afresh + for part in (*(f"published/{p}" for p in PUBLISHED_PARTS), "sock"): + (mine / part).mkdir(parents=True, mode=0o700) + url = _service(params) + reply = _post(url + "/register", {"workspace": str(work), "task": task["id"]}) + try: + _wire(task, work, params, rax, mine, reply) + except BaseException: + # No session follows (the call fails, and `collect` is not run): RAX's frontend is stopped now + try: + _post(url + "/finish", {"workspace": str(work)}, timeout=600.0) + except Exception: # noqa: BLE001 - the failure that brought us here wins + pass + raise + return [] + + +def _wire(task: dict, work: Path, params: dict, rax: Path, mine: Path, reply: dict) -> None: + """prepare's part after the registration: RAX's workspace, the run tree, the socket, the library, Claude Code.""" + _extract(reply["workspace"], work) + expected = start_prompt(rax / "auto_research_agent" / "START_PROMPT.md") + given = work / "START_PROMPT.md" + if given.is_file() and given.read_text().strip() != expected: + raise RuntimeError("RAX's workspace renders START_PROMPT.md otherwise than this port's prompt: re-pin RAX") + link = work / "runtime" / "autonomous_controller" # RAX's run tree, as its workspace names it + link.parent.mkdir(parents=True, exist_ok=True) + link.unlink(missing_ok=True) + link.symlink_to(mine / "published", target_is_directory=True) + SOCKET_DIR.unlink(missing_ok=True) # a link of a run before this one (checked above) + SOCKET_DIR.parent.mkdir(parents=True, exist_ok=True) + SOCKET_DIR.symlink_to(mine / "sock", target_is_directory=True) + record = {"name": session_name(work), "task": task["id"], "service_session": reply.get("session")} + copy = work / "hermit" / "rax" # the adapter, as the deployment copied it + with_library = copy.is_dir() + if with_library: + repository = mine / "library" / library.ROBOT + record.update(repository=str(repository), base=library.build(copy, repository)) + library.checkout(repository, record["name"], work) + skill = work / ".agents" / "skills" / "continual-learning" / "SKILL.md" + skill.parent.mkdir(parents=True, exist_ok=True) + skill.write_text(library.continual_learning_skill()) + (mine / "session.json").write_text(json.dumps(record, indent=1) + "\n") + cli = shutil.which(str(params.get("bin") or "claude")) + env = agent_environment(work, rax, float(reply.get("cpus") or 4), cli) + wire_claude(work, rax, env, with_library, int(reply.get("subagents") or 0)) + + +# ---------- answer and collect ---------- + +def answer(last_message: str, task: dict) -> dict: + """The agent's last message (RAX's final report); the judge scores the submitted bundle, not this.""" + return {"answer": last_message} + + +def _keep_notes(work: Path, log: Path) -> dict: + """The session's notes and code (memory/, code/) in the log: regular files up to NOTE_FILE_BYTES each and + NOTE_BYTES in all, never through a link.""" + kept, total = 0, 0 + for name in NOTES: + top = work / name + if top.is_symlink() or not top.is_dir(): + continue + for directory, dirs, files in os.walk(top, followlinks=False): + here = Path(directory) + dirs[:] = sorted(d for d in dirs if not (here / d).is_symlink() and d != "__pycache__") + for file in sorted(files): + path = here / file + if path.is_symlink() or not path.is_file(): + continue + size = path.stat().st_size + if size > NOTE_FILE_BYTES or total + size > NOTE_BYTES: + continue + target = log / "session" / path.relative_to(work) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, target) + kept, total = kept + 1, total + size + return {"files": kept, "bytes": total} + + +def collect(task: dict, work: Path, log: Path, params: dict) -> dict: + work, log = Path(work).resolve(), Path(log) + try: + reply = _post(_service(params) + "/finish", {"workspace": str(work)}) + except Exception as exc: # noqa: BLE001 - the judge ends it from the ledger + reply = {"finish_error": f"{type(exc).__name__}: {exc}"[:500]} + facts = {"workspace": str(work), **{k: reply.get(k) for k in ("session", "submitted_bundle", "rehearsals", + "exploration_used", "exploration_budget", + "gemini_usd")}, + **({"finish_error": reply["finish_error"]} if "finish_error" in reply else {})} + record_path = own(work) / "session.json" + record = json.loads(record_path.read_text()) if record_path.is_file() else {} + if record.get("repository") and record.get("base"): + exported = library.export(Path(record["repository"]), record["base"], log) + exported["name"] = record.get("name") + (log / library.RECORD).write_text(json.dumps(exported, indent=1) + "\n") + facts["library"] = {k: exported.get(k) for k in ("base", "head", "bundle", "error")} + facts["notes"] = _keep_notes(work, log) + return facts diff --git a/hermit/agent/evolver/methods/rax/evolver.py b/hermit/agent/evolver/methods/rax/evolver.py new file mode 100644 index 00000000..a0d5ce09 --- /dev/null +++ b/hermit/agent/evolver/methods/rax/evolver.py @@ -0,0 +1,27 @@ +"""RaxEvolver: RAX's continual learning (arXiv:2610.22496 §3.4) as an Evolver on the `rax` template. + +In RAX a session commits skills on its branch of the robot's skill library and calls the harness tool +`skill_library_merge`, which checks every changed skill (format, compiling entry, evidence, images, `uses`) and merges +the branch into the library's main, where the next session finds it (services/skill_library.py, real/rainbow 36c926c). +There is no learner model: the agents write the library, the harness only checks and merges. + +On the Trainer, a session's merges go into a library repository of its own (the RAX task functions, library.py), and +this Evolver takes each of the step's sessions into the adapter with the same merge: it rebuilds the step's library +from the adapter (the commit every session of the step started from), fetches each session's bundle onto a branch, +and runs RAX's `merge`, which checks every changed skill again; a session whose changes conflict with an earlier one +of the same step is not taken in (RAX would ask that agent to merge origin/main and try again). The merged main is the +next adapter. The step runs as a program in the evolver sandbox (merge.py, the CommandEvolver contract), with git; +it reads the learning material and writes only the adapter and its output.""" +from __future__ import annotations + +import dataclasses +import sys + +from hermit.agent.evolver.agent import CommandEvolver +from hermit.agent.evolver.base import StepContext, StepResult + + +class RaxEvolver(CommandEvolver): + def step(self, ctx: StepContext) -> StepResult: + command = [sys.executable, "-m", "hermit.agent.evolver.methods.rax.merge"] + return super().step(dataclasses.replace(ctx, params={**ctx.params, "command": command})) diff --git a/hermit/agent/evolver/methods/rax/evolver.yaml b/hermit/agent/evolver/methods/rax/evolver.yaml new file mode 100644 index 00000000..032ce1bc --- /dev/null +++ b/hermit/agent/evolver/methods/rax/evolver.yaml @@ -0,0 +1,8 @@ +description: >- + RAX's continual learning (arXiv:2610.22496 §3.4; robot-agent-exploration/rax real/rainbow 36c926c): no learner + model. Each step takes in what the step's sessions merged into their clones of the skill library, with RAX's own + merge (every changed skill's format and evidence checked again, then a git merge into the library's main), as RAX's + harness merges a session's branch; the merged library is the next adapter. +class: evolver.py:RaxEvolver +needs: [] # the library's clone and merge tool are the RAX task functions' (actor.py) +params: {} diff --git a/hermit/agent/evolver/methods/rax/library.py b/hermit/agent/evolver/methods/rax/library.py new file mode 100644 index 00000000..f33c9ab4 --- /dev/null +++ b/hermit/agent/evolver/methods/rax/library.py @@ -0,0 +1,259 @@ +"""RAX's skill library (arXiv:2610.22496 §3.4) as a Hermit adapter, merged by RAX's own code. + +The adapter holds the library tree of RAX's `services/skill_library.py` (README.md, INDEX.md, skills//...), and +that module (upstream/skill_library.py: robot-agent-exploration/rax real/rainbow 36c926c, unchanged) does the work on +both sides of a training step, as it does in RAX between sessions: + +- before a session (`prepare`, in the task sandbox): `build` makes a library repository of the adapter's files, and + RAX's `checkout` clones it into the workspace as `skill-library/`, on the session's branch; +- in the session: the agent's `skill_library_merge` tool is RAX's `merge` against that repository: the same format and + evidence checks, the same replies, and later commits of the same session see what it merged; +- after it (`collect`): `export` writes what the session merged (a git bundle of the repository's main past its first + commit) into the run's log, without running git in a repository the agent could write; +- the Evolver (`merge.py`, in the evolver sandbox): `build` makes the same repository of the step's adapter, and RAX's + `merge` takes in each session's bundle on a branch of its own, checking every changed skill again; the merged tree + is the next adapter (`write_tree`). + +Every repository starts from one commit of the adapter's library files with a fixed author, date and file mode, so a +session and the Evolver that start from the same adapter start from the same commit: RAX's merge base. Only the +library's files are in it (README.md, INDEX.md and skills/); RAX's merge refuses a change outside INDEX.md and skills/. +""" +from __future__ import annotations + +from contextlib import contextmanager +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +from types import SimpleNamespace + +from hermit.agent.evolver.methods.rax.upstream import skill_library as rax + +ROBOT = "libero-panda" # the library's robot: RAX keeps one library per robot, named by its directory +ROBOT_NAME = "LIBERO Franka Panda" # {{ robot.name }} of the continual-learning skill (RAX's facts of a robot) +ROOT_FILES = ("INDEX.md", "README.md") +SKILLS = "skills" +KEEP = "skills/.gitkeep" # RAX's ensure_library commits it, so every clone has skills/ (git keeps no empty + # directory, and a package keeps no dotfile: the template has no skills/) +BASE_MESSAGE = "The skill library this session started from" +# The first commit's identity: fixed, so the same files give the same commit in every session and in the Evolver +BASE_IDENTITY = {"GIT_AUTHOR_NAME": "rax harness", "GIT_AUTHOR_EMAIL": "harness@rax.local", + "GIT_AUTHOR_DATE": "2000-01-01T00:00:00+0000", "GIT_COMMITTER_NAME": "rax harness", + "GIT_COMMITTER_EMAIL": "harness@rax.local", "GIT_COMMITTER_DATE": "2000-01-01T00:00:00+0000"} +BUNDLE = "library.bundle" +RECORD = "library.json" +NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,120}$") # a session's name: its branch is session/ + + +def git(*args: str, cwd: Path, data: bytes | None = None, env: dict | None = None) -> str: + """git with RAX's environment (no system or user configuration, no prompt), output as text.""" + done = subprocess.run(["git", *args], cwd=cwd, input=data, capture_output=True, timeout=600, + env={**os.environ, **rax.GIT_ENV, **(env or {})}) + if done.returncode: + raise rax.LibraryError(f"git {' '.join(args)}: {(done.stderr or done.stdout).decode(errors='replace')[:500]}") + return done.stdout.decode() + + +def config(name: str) -> SimpleNamespace: + """The part of RAX's session configuration its library code reads: the session's name (its branch is + session/) and the robot.""" + if not NAME.match(name): + raise ValueError(f"{name!r} is not a session name RAX's branch can carry") + return SimpleNamespace(root=Path("/sessions") / name, robot=ROBOT) + + +@contextmanager +def located(repository: Path): + """RAX finds the library at $RAX_SKILL_LIBRARY/: point it at `repository` for the block.""" + repository = Path(repository) + if repository.name != ROBOT: + raise ValueError(f"a library repository is named after its robot ({ROBOT}), not {repository.name}") + before = os.environ.get(rax.ENVIRONMENT) + os.environ[rax.ENVIRONMENT] = str(repository.parent) + try: + yield repository + finally: + if before is None: + os.environ.pop(rax.ENVIRONMENT, None) + else: + os.environ[rax.ENVIRONMENT] = before + + +def library_files(tree: Path) -> list[str]: + """The library's files in `tree` (an adapter, or its copy in a workspace): README.md, INDEX.md and every file under + skills/ (none when there is no skills/: an empty library), as sorted POSIX paths. A link anywhere is refused: none + is ever read through.""" + tree = Path(tree) + found = [] + for name in ROOT_FILES: + path = tree / name + if path.is_symlink() or not path.is_file(): + raise rax.LibraryError(f"{name} must be a file of the library") + found.append(name) + skills = tree / SKILLS + if skills.is_symlink() or (skills.exists() and not skills.is_dir()): + raise rax.LibraryError("skills/ must be a directory of the library") + for directory, dirs, files in os.walk(skills, followlinks=False): # nothing when skills/ is absent + here = Path(directory) + for entry in [*dirs, *files]: + if (here / entry).is_symlink(): + raise rax.LibraryError(f"{(here / entry).relative_to(tree)}: links are not allowed in the library") + found += [(here / f).relative_to(tree).as_posix() for f in files] + return sorted(found) + + +def build(tree: Path, repository: Path) -> str: + """A new repository at `repository` (named ROBOT) whose main is one commit of the library's files in `tree`, with + an empty skills/.gitkeep when `tree` has none (as RAX's ensure_library starts a library): every file 100644, the + fixed identity and date, so the same files give the same commit. Returns the commit.""" + repository = Path(repository) + if repository.exists() or repository.is_symlink(): + raise rax.LibraryError(f"{repository} exists: a library repository is made fresh") + files = library_files(tree) + repository.mkdir(parents=True) + git("init", "-q", "-b", "main", cwd=repository) + git("config", "user.name", "rax harness", cwd=repository) # as RAX's ensure_library: its merges commit + git("config", "user.email", "harness@rax.local", cwd=repository) + shas = git("hash-object", "-w", "--no-filters", "--stdin-paths", cwd=repository, + data="".join(str(Path(tree) / f) + "\n" for f in files).encode()).split() + blobs = dict(zip(files, shas)) + if KEEP not in blobs: + blobs[KEEP] = git("hash-object", "-w", "--stdin", cwd=repository, data=b"").strip() + git("update-index", "--add", "--index-info", cwd=repository, + data="".join(f"100644 {sha}\t{f}\n" for f, sha in sorted(blobs.items())).encode()) + tree_id = git("write-tree", cwd=repository).strip() + commit = git("commit-tree", tree_id, "-m", BASE_MESSAGE, cwd=repository, env=BASE_IDENTITY).strip() + git("update-ref", "refs/heads/main", commit, cwd=repository) + git("reset", "-q", "--hard", "main", cwd=repository) + return commit + + +def checkout(repository: Path, name: str, workspace: Path) -> dict: + """RAX's checkout: the library cloned into `workspace`/skill-library on branch session/.""" + with located(repository): + return rax.checkout(config(name), workspace) + + +def merge(repository: Path, name: str, workspace: Path, message: str) -> dict: + """RAX's merge (its harness tool `skill_library_merge`): the session branch of `workspace`/skill-library checked and + merged into the repository's main.""" + with located(repository): + return rax.merge(config(name), workspace, message) + + +def _head(git_dir: Path, ref: str) -> str | None: + """A branch's commit read from a repository's files as data (its loose ref, else packed-refs), as RAX's merge reads + a clone's branch: no git runs there.""" + loose = git_dir / "refs" / "heads" / ref + if loose.is_file() and not loose.is_symlink(): + value = loose.read_text().strip() + return value if re.fullmatch(r"[0-9a-f]{40}", value) else None + packed = git_dir / "packed-refs" + if packed.is_file() and not packed.is_symlink(): + for line in packed.read_text().splitlines(): + if line.endswith(f" refs/heads/{ref}"): + value = line.split()[0] + return value if re.fullmatch(r"[0-9a-f]{40}", value) else None + return None + + +def export(repository: Path, base: str, out: Path) -> dict: + """What a session merged into its library repository (which the agent could write): its main past `base`, as a git + bundle in `out`. The repository's objects are copied without links (RAX's _copy_objects) into a fresh repository + with no configuration or hooks of the agent's, and the bundle is made there. Returns the record the Evolver + reads.""" + record = {"base": base, "head": None, "bundle": None} + git_dir = Path(repository) / ".git" + head = _head(git_dir, "main") if git_dir.is_dir() and not git_dir.is_symlink() else None + record["head"] = head + if head is None: + record["error"] = "the library repository has no main branch" + return record + if head == base: + return record # nothing merged: no bundle + with tempfile.TemporaryDirectory(prefix="rax-export-") as scratch: + bare = Path(scratch) / "library.git" + bare.mkdir() + rax._copy_objects(git_dir / "objects", bare / "objects") + (bare / "refs" / "heads").mkdir(parents=True) + (bare / "refs" / "heads" / "main").write_text(head + "\n") + (bare / "HEAD").write_text("ref: refs/heads/main\n") + (bare / "config").write_text("[core]\n\trepositoryformatversion = 0\n\tbare = true\n") + try: + ancestor = git("merge-base", "--is-ancestor", base, head, cwd=bare) is not None + except rax.LibraryError: + ancestor = False + if not ancestor: + record["error"] = "the library's main does not descend from the commit the session started from" + return record + Path(out).mkdir(parents=True, exist_ok=True) + git("bundle", "create", "-q", str(Path(out).resolve() / BUNDLE), "main", f"^{base}", cwd=bare) + record["bundle"] = BUNDLE + return record + + +def take_in(repository: Path, bundle: Path, record: dict, name: str, message: str) -> dict: + """The Evolver's side: a session's bundle, fetched as data into a fresh clone of the Evolver's repository on branch + session/, merged by RAX's merge (every changed skill checked again). Returns RAX's reply.""" + with tempfile.TemporaryDirectory(prefix="rax-take-in-") as scratch: + workspace = Path(scratch) / "workspace" + clone = workspace / rax.LIBRARY_DIR + workspace.mkdir() + git("clone", "-q", "--no-hardlinks", str(Path(repository).resolve()), str(clone), cwd=workspace) + git("fetch", "-q", "--no-tags", str(Path(bundle).resolve()), f"refs/heads/main:refs/heads/session/{name}", + cwd=clone) + fetched = git("rev-parse", f"refs/heads/session/{name}", cwd=clone).strip() + if fetched != record.get("head"): + return {"merged": False, "reason": f"the bundle's main is {fetched}, not the recorded {record.get('head')}"} + return merge(repository, name, workspace, message) + + +def write_tree(repository: Path, adapter: Path) -> list[str]: + """The repository's main as the adapter's library: INDEX.md and skills/ replaced by main's (README.md is the + template's, which no merge changes). Returns the library files now in the adapter.""" + adapter = Path(adapter) + with tempfile.TemporaryDirectory(prefix="rax-tree-") as scratch: + tree = Path(scratch) / "tree" + tree.mkdir() + archive = subprocess.run(["git", "archive", "--format=tar", "main"], cwd=repository, capture_output=True, + timeout=600, env={**os.environ, **rax.GIT_ENV}) + if archive.returncode: + raise rax.LibraryError("git archive failed: " + archive.stderr.decode(errors="replace")[:300]) + subprocess.run(["tar", "-x", "-C", str(tree)], input=archive.stdout, check=True, timeout=600) + files = library_files(tree) + if (adapter / SKILLS).is_symlink(): + (adapter / SKILLS).unlink() + shutil.rmtree(adapter / SKILLS, ignore_errors=True) + if (tree / SKILLS).is_dir(): # main may hold no skills/ (a session deleted its .gitkeep) + shutil.copytree(tree / SKILLS, adapter / SKILLS) + shutil.copyfile(tree / "INDEX.md", adapter / "INDEX.md") + return files + + +def read_record(directory: Path) -> dict | None: + """The export record `collect` wrote into a run's log (RECORD), or None.""" + path = Path(directory) / RECORD + if path.is_symlink() or not path.is_file(): + return None + try: + value = json.loads(path.read_text()) + except ValueError: + return None + return value if isinstance(value, dict) else None + + +def readme() -> str: + """The library's README as RAX's ensure_library writes it for this robot (its id: RAX's config.robot).""" + return rax.README.format(robot=ROBOT, sections=", ".join(f"`## {s}`" for s in rax.SECTIONS), + run_keys=", ".join(f"`{k}`" for k in rax.RUN_KEYS), + image_kb=rax.MAX_IMAGE_BYTES // 1000, verified=rax.VERIFIED_MIN_RUNS) + + +def continual_learning_skill() -> str: + """RAX's continual-learning agent skill (real/rainbow), rendered for this robot: its one variable is the robot's + name (`{{ robot.name }}`).""" + text = (Path(__file__).resolve().parent / "upstream" / "continual-learning.SKILL.md").read_text() + return text.replace("{{ robot.name }}", ROBOT_NAME) diff --git a/hermit/agent/evolver/methods/rax/library_server.py b/hermit/agent/evolver/methods/rax/library_server.py new file mode 100644 index 00000000..7cc7fccf --- /dev/null +++ b/hermit/agent/evolver/methods/rax/library_server.py @@ -0,0 +1,108 @@ +"""skill_library_merge: RAX's harness tool of that name (services/controller/frontend.py, real/rainbow 36c926c), served +to the session as an MCP server of its own beside RAX's frontend, in the task sandbox. RAX's frontend offers it when the +workspace has a clone of the skill library (skill-library/.git), and answers it with RAX's `merge` of the session's +branch into the library's main (upstream/skill_library.py, through library.merge): `merged: true` with the merged +commit, or the format and evidence `problems` to fix, or the `conflicts` to resolve. The tool's name, description, +schema, refusal and replies are RAX's; the MCP exchange is RAX's frontend's (newline-delimited JSON-RPC on stdio). + +The library repository is this session's (/rax/library/, made by the RAX task functions' `prepare` and +named in /rax/session.json); what the session merged reaches the adapter through the rax Evolver, which runs the +same merge again (merge.py). The RAX task functions start it, in the session's MCP configuration (actor.py): + + -m hermit.agent.evolver.methods.rax.library_server --workspace +""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys + +PROTOCOL_VERSION = "2025-06-18" # RAX's frontend's +NAME = "skill_library_merge" +TOOL = {"name": NAME, + "description": "Merge your session branch of the skill library (the clone in skill-library/) into the " + "library's main, so later sessions get your skills. Only committed changes count (git add, git " + "commit first). The harness checks the format and evidence of every skill you changed (see the " + "continual-learning skill) and merges; it returns problems to fix, or conflicts to resolve by " + "merging origin/main, or the merged commit.", + "inputSchema": {"type": "object", "properties": { + "message": {"type": "string", "maxLength": 500, + "description": "What this merge adds or changes, one line."}}, + "required": ["message"], "additionalProperties": False}} + + +def session(workspace: Path) -> dict: + """The session's library record (/rax/session.json): its name and library repository.""" + record = json.loads((workspace.parent / "rax" / "session.json").read_text()) + if not record.get("repository") or not record.get("name"): + raise ValueError("this RAX session has no skill library (it ran without the rax adapter)") + return record + + +def call(workspace: Path, arguments: dict) -> dict: + """RAX's handler: one-line message only, then RAX's merge of the session's branch.""" + from hermit.agent.evolver.methods.rax import library + + if not isinstance(arguments, dict) or set(arguments) - {"message"} or not str(arguments.get("message", "")).strip(): + raise ValueError("skill_library_merge takes message (one line)") + record = session(workspace) + return library.merge(Path(record["repository"]), str(record["name"]), workspace, str(arguments["message"])) + + +def handle(workspace: Path, request) -> dict | None: + """One JSON-RPC request, as RAX's frontend answers it (`handle`, `call`); None for a notification.""" + if not isinstance(request, dict): + return {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid request"}} + ident = request.get("id") + try: + if request.get("jsonrpc") != "2.0": + raise ValueError("Invalid JSON-RPC") + method = request.get("method") + if method == "initialize": + result = {"protocolVersion": PROTOCOL_VERSION, "capabilities": {"tools": {}}, + "serverInfo": {"name": "skill_library", "version": "1.0"}} + elif isinstance(method, str) and method.startswith("notifications/"): + return None + elif method == "ping": + result = {} + elif method == "tools/list": + result = {"tools": [TOOL]} + elif method == "tools/call": + params = request.get("params") or {} + if params.get("name") != NAME: + raise PermissionError("Unknown tool") + try: + value = call(workspace, params.get("arguments", {})) + result = {"content": [{"type": "text", "text": json.dumps(value, allow_nan=False)}]} + except Exception as exc: # the agent's error to read, as RAX's frontend returns one + error = {"type": type(exc).__name__, "message": str(exc)[-4000:], "operation": NAME} + result = {"isError": True, "content": [{"type": "text", "text": json.dumps({"error": error})}]} + else: + raise PermissionError("Unsupported method") + return {"jsonrpc": "2.0", "id": ident, "result": result} + except Exception as exc: + return {"jsonrpc": "2.0", "id": ident, "error": {"code": -32000, "message": f"{type(exc).__name__}: {exc}"}} + + +def main(argv=None) -> None: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--workspace", type=Path, required=True, help="the session's workspace") + args = ap.parse_args(argv) + workspace = args.workspace.resolve() + for line in sys.stdin: + if not line.strip(): + continue + try: + request = json.loads(line) + except ValueError: + reply = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}} + else: + reply = handle(workspace, request) + if reply is not None: + sys.stdout.write(json.dumps(reply) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/hermit/agent/evolver/methods/rax/merge.py b/hermit/agent/evolver/methods/rax/merge.py new file mode 100644 index 00000000..6bd14782 --- /dev/null +++ b/hermit/agent/evolver/methods/rax/merge.py @@ -0,0 +1,85 @@ +"""The RAX Evolver's step (evolver.py) as the program a CommandEvolver runs: HA_CONTEXT names the workspace; the +adapter is changed in place and output/step_result.json says what was taken in. + +For each task of the step (learning_material/current, in the step's order): the export record `collect` wrote into the +run's log (library.json) and its bundle; RAX's merge of the bundle's main into the step's library (library.take_in). +The step's library is rebuilt from the adapter first (library.build): the commit each session started from, unless +the adapter changed since (a session that started elsewhere is not taken in).""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import shutil +import sys + +from hermit.agent.evolver.methods.rax import library + + +def tasks(step: Path) -> list[tuple[str, dict]]: + """The step's task records (tasks/.json), in the order its summary names the tasks (then any other).""" + from hermit.isolate import _safe # the material's file name of a task id + + records = {p.stem: p for p in sorted((step / "tasks").glob("*.json")) if p.is_file() and not p.is_symlink()} + try: + order = [str(t) for t in json.loads((step / "summary.json").read_text()).get("tasks") or []] + except (OSError, ValueError): + order = [] + named = [(t, _safe(t)) for t in order if _safe(t) in records] + named += [(stem, stem) for stem in records if stem not in {s for _, s in named}] + return [(t, json.loads(records[stem].read_text())) for t, stem in named] + + +def take_in(step: Path, repository: Path, base: str, task_id: str, record: dict) -> dict: + """One session's merges into the step's library, as RAX's merge replies (merged, problems or conflicts).""" + trajectory = record.get("trajectory") + log = (step / trajectory).resolve() if trajectory else None + if log is None or not log.is_relative_to(step.resolve()) or not log.is_dir(): + return {"task": task_id, "merged": False, "reason": "no log of the run"} + exported = library.read_record(log) + if exported is None: + return {"task": task_id, "merged": False, "reason": "no library record (a run without the rax adapter)"} + if exported.get("error"): + return {"task": task_id, "merged": False, "reason": exported["error"]} + if exported.get("base") != base: + return {"task": task_id, "merged": False, + "reason": f"the session started from library {exported.get('base')}, not this step's {base}"} + if not exported.get("bundle"): + return {"task": task_id, "merged": False, "reason": "the session merged nothing into its library"} + bundle = (log / str(exported["bundle"])).resolve() + if not bundle.is_relative_to(log) or not bundle.is_file(): + return {"task": task_id, "merged": False, "reason": "the session's bundle is missing"} + name = str(exported.get("name") or task_id) + try: + reply = library.take_in(repository, bundle, exported, name, f"the merges of task {task_id}'s session") + except (library.rax.LibraryError, ValueError, OSError) as exc: + return {"task": task_id, "merged": False, "reason": str(exc)[:500]} + keep = ("merged", "reason", "problems", "conflicts", "skills", "changed_files", "head", "library_main") + return {"task": task_id, **{k: reply[k] for k in keep if k in reply}} + + +def main() -> int: + info = json.loads(Path(os.environ["HA_CONTEXT"]).read_text()) + places = {k: Path(v) for k, v in info["workspace"].items()} + adapter, output = places["adapter"], places["output"] + step = (places["learning_material"] / "current").resolve() + repository = places["scratch"] / "rax-library" / library.ROBOT + shutil.rmtree(repository, ignore_errors=True) # a resumed step builds its library again + base = library.build(adapter, repository) + results = [take_in(step, repository, base, task_id, record) for task_id, record in tasks(step)] + merged = [r for r in results if r.get("merged")] + if merged: + library.write_tree(repository, adapter) + skills = sorted({s for r in merged for s in r.get("skills") or []}) + summary = (f"took in {len(merged)} of {len(results)} sessions' merges: {', '.join(skills) or 'no skill'}" + if merged else f"no change: none of the {len(results)} sessions' merges was taken in") + output.mkdir(parents=True, exist_ok=True) + (output / "step_result.json").write_text(json.dumps( + {"status": "done", "summary": summary[:300], "rationale": "RAX's merge of each session's skill-library merges", + "extra": {"sessions": results, "base": base}}, indent=1)) + print(summary) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/hermit/agent/evolver/methods/rax/stop_hook.py b/hermit/agent/evolver/methods/rax/stop_hook.py new file mode 100644 index 00000000..3d4ebc99 --- /dev/null +++ b/hermit/agent/evolver/methods/rax/stop_hook.py @@ -0,0 +1,67 @@ +"""RAX's relaunch policy as the session's Stop hook (harness/codex_cli/auto_research.py `run_agent`, libero-pro/native +1767412): while exploration is open, a session whose turn ends goes on with RAX's CONTINUE_PROMPT, at most +MAX_RELAUNCHES times. RAX runs the CLI again on the same conversation; a Stop hook keeps the same CLI going, so the +prompt leaves out RAX's clause that the turn's background workers were stopped (here they keep running). + +Exploration is open as RAX's frontend says: its `status` names a `next_step` once exploration is closed (the bundle +submitted, or the episode budget spent with nothing running). The robot socket is the session's (RAX_MCP_SOCKET, by +the RAX task functions /tmp/rax/robot.sock). Anything that fails lets the turn end, as RAX ends a run it cannot +continue. Standard library only: the RAX task functions' `prepare` installs it as the session's Stop hook (Claude +Code's .claude/settings.json in the workspace), run by the framework's Python in isolated mode (-I: nothing of the +workspace is imported) in the session's workspace, and it keeps its count beside the workspace (/rax/relaunches). +""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import socket +import sys + +MAX_RELAUNCHES = 3 +CONTINUE_PROMPT = ("Your previous turn ended while exploration is still open, and your open episodes kept running. " + "Call status, reread memory/PROGRESS.md, and continue from the live state until exploration is " + "closed.") +SOCKET = "/tmp/rax/robot.sock" + + +def status(path: str, timeout: float = 30.0) -> dict: + """RAX's `status` over the session's robot socket (newline-delimited JSON-RPC, as api/runtime.py speaks it).""" + with socket.socket(socket.AF_UNIX) as conn: + conn.settimeout(timeout) + conn.connect(path) + reader, writer = conn.makefile("r"), conn.makefile("w") + for ident, method, params in ((1, "initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "rax-stop-hook", "version": "1"}}), + (2, "tools/call", {"name": "status", "arguments": {}})): + writer.write(json.dumps({"jsonrpc": "2.0", "id": ident, "method": method, "params": params}) + "\n") + writer.flush() + reply = json.loads(reader.readline(32 * 1024 * 1024)) + if "error" in reply: + raise RuntimeError(json.dumps(reply["error"])[:300]) + text = next(c["text"] for c in reply["result"]["content"] if c.get("type") == "text") + return json.loads(text) + + +def main() -> int: + try: + json.load(sys.stdin) # the host's hook input: nothing in it is needed + except ValueError: + pass + workspace = Path.cwd().resolve() # a hook runs where the session started: its workspace + count_file = workspace.parent / "rax" / "relaunches" + try: + count = int(count_file.read_text().strip() or 0) if count_file.is_file() else 0 + value = status(os.environ.get("RAX_MCP_SOCKET") or SOCKET) + except Exception as exc: # no robot to ask: the turn ends + print(f"rax stop hook: {type(exc).__name__}: {exc}", file=sys.stderr) + return 0 + if "next_step" in value or count >= MAX_RELAUNCHES: + return 0 + count_file.write_text(f"{count + 1}\n") + print(json.dumps({"decision": "block", "reason": CONTINUE_PROMPT})) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/hermit/agent/evolver/methods/rax/upstream/LICENSE b/hermit/agent/evolver/methods/rax/upstream/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/hermit/agent/evolver/methods/rax/upstream/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/hermit/agent/evolver/methods/rax/upstream/NOTICE b/hermit/agent/evolver/methods/rax/upstream/NOTICE new file mode 100644 index 00000000..be5c4d09 --- /dev/null +++ b/hermit/agent/evolver/methods/rax/upstream/NOTICE @@ -0,0 +1,16 @@ +RAX: Scaling Online Exploration for Robot Agents +Copyright 2026 RAX contributors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this work except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, this work +is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS +OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +Third-party code, simulator software, assets, model weights and datasets +retain their respective copyright notices and license terms. diff --git a/hermit/agent/evolver/methods/rax/upstream/continual-learning.SKILL.md b/hermit/agent/evolver/methods/rax/upstream/continual-learning.SKILL.md new file mode 100644 index 00000000..17368727 --- /dev/null +++ b/hermit/agent/evolver/methods/rax/upstream/continual-learning.SKILL.md @@ -0,0 +1,325 @@ +--- +name: continual-learning +description: Read, run and grow the persistent skill library in skill-library/ that carries verified, executable task skills across sessions and tasks on this {{ robot.name }}. Read it at the start of every session; contribute and merge with skill_library_merge before the session ends. +--- + +# Continual learning: the skill library + +`skill-library/` in your workspace is a git clone of this robot's **skill library**: task +skills that earlier sessions (any task) learned on this robot, each an executable +procedure with the evidence that it works. You are on your own branch, +`session/`; the tool `skill_library_merge` checks your branch and merges it +into the library's `main`, where the next session finds it. + +Keep three kinds of knowledge apart: + +| Where | Written by | Holds | Lifetime | +|---|---|---|---| +| `.agents/skills/` | people (the harness) | how to use the robot, tools, workflow; read-only | every session | +| `memory/` (TIPS, PROGRESS, RUNS) | you | this task's notes, attempts, frame links | this task | +| `skill-library/` | agents, through merges | verified, executable procedures for sub-tasks | every later session | + +The harness skills and the live tool schemas take precedence over the library: a library +skill never changes a limit, a safety rule or what a tool does. + +## 1. At the start: read and reuse + +1. Read `skill-library/INDEX.md`. Then `git -C skill-library fetch origin && git -C + skill-library merge origin/main` to pick up anything merged since your workspace was + made. +2. **Load only the skills relevant to this task.** Use `INDEX.md` to choose. For each + part of `TASK.md`, open only the skills whose **When to use** matches it, plus the + skills they list in `uses:`. Do not read every skill or its code up front: unrelated + skills cost context and can mislead. Open another skill later if a new sub-task + needs it. Prefer `verified` over `draft`; ignore `deprecated` except to learn why + it was retired. +3. Before running one, check its **Preconditions** against a fresh observation, and its + tested parameter ranges against your scene. A skill tested on 0.3 m boxes is not + evidence for a 0.6 m box. +4. Run its code (below), read the returned `{ok, measured, why}`, and confirm the result + with your own observation. A skill that fails here is information: record the run as a + failure (section 4) and say what differed. +5. A skill may be older than the tools you have: compare the tools it uses with the + current tool list and the robot-interface skill. Where a newer tool does a step better + (for example the controller's whole-body IK in place of a hand-written solver), upgrade + the skill on your branch, bump its `version`, and re-verify it. + +Run a skill's entry from the workspace root, logging to `output/`: + +```python +import importlib.util, json +from api.runtime import Context + +spec = importlib.util.spec_from_file_location("skill", "skill-library/skills//code/run.py") +skill = importlib.util.module_from_spec(spec) +spec.loader.exec_module(skill) +with Context() as ctx: + print(json.dumps(skill.main(ctx, **{"param": "value"}), indent=1)) +``` + +Your own controller under `code/` may import and call library skills the same way. + +## 2. What to contribute + +Contribute a skill when a procedure **worked on the robot** and is useful beyond this +exact scene: a sub-task with a clear start and end ("pick a box from the floor with both +hands", "place a held object on a table", "localize a cardboard box"). Also contribute: + +- an **improvement** to an existing skill: wider tested conditions, better parameters, a + new failure mode and how the code now detects it; +- a **draft** of a procedure that is automated but not yet verified, so the next session + can finish it instead of starting over; +- **deprecation** of a skill that proved wrong or was replaced (status `deprecated`, why, + and what to use instead). Never delete another session's skill or evidence. + +One skill is one sub-task. A task-level procedure can be its own skill that calls other +skills. Name folders by what they do, in lower-case words with hyphens +(`pick-box-floor-two-hands`). + +## 3. Make skills modular, so new tasks can compose them + +Write every skill so that a later session can reuse its pieces for a task nobody has +seen yet: "pick a box from the floor" should serve "put the box on a shelf", "hand the box +to a person" and "stack two boxes" without being rewritten. + +**Cut the task into primitives.** A task is a chain of manipulation primitives, each its +own skill or its own function inside one: perception (`localize-box`: frame -> pose and +size), positioning (`stance-for-object`: drive and turn to a reach pose), grasping +(`bimanual-squeeze-grasp`), transport (`torso-lift`, `carry-close`), placing +(`place-on-surface`), release and retreat (`release-retreat`). Split at the points where +the robot is in a stable, describable state; do not split in the middle of a contact. + +**Give each primitive a contract**, stated in its SKILL.md (`## Code`) and its docstring: + +- inputs as parameters, in base-frame metres / radians / named sides, never constants + tied to one scene: the object's pose and size, which arm or both, the target surface + height, speeds and forces with their tested ranges; +- the state it needs at the start (posture, grippers, what is held, what must be visible) + and the state it leaves at the end (for example "arms at `ready`, nothing held" or + "box held between both grippers at carry height, torso `ready`"): the end state of one + primitive is the start state the next one checks; +- its return value `{ok, measured, why}`, with what the next step needs in `measured` + (the object pose it found, the grip force, the height reached); +- on failure: stop in a safe state, say which precondition or check failed, and leave + enough in `measured` for a caller to retry or recover. + +**Keep the code composable**: + +- one function per primitive, `def primitive(ctx, ..., log=print) -> dict`, taking `ctx` + and its inputs, with no globals, no hidden state and no dependence on the current + working directory; perception helpers take a frame and return data without moving the + robot; motion helpers do one thing; +- `code/run.py:main(ctx, **params)` only chains the skill's own primitives; anything a + different task could use lives in its own module or its own skill; +- reuse instead of copying: import another library skill's functions and declare it in + the frontmatter (`uses: [localize-box, torso-lift]`; the merge checks those skills + exist): + + ```python + import importlib.util + from pathlib import Path + SKILLS = Path(__file__).resolve().parents[2] # skill-library/skills/ + + def load(slug, module="run"): + path = SKILLS / slug / "code" / f"{module}.py" + spec = importlib.util.spec_from_file_location(f"{slug.replace('-', '_')}_{module}", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + localize = load("localize-box", "perception") + ``` + +- changing a primitive others use: keep its signature and contract, or add a new function + and leave the old one working; bump `version` and say in its changelog what changed. + Check `uses:` in `INDEX.md` / other skills before changing behaviour. + +**Prefer the robot's own tools inside primitives** (whole-body IK, Cartesian moves, the +planning tools) over hand-written solvers: they are measured and they improve without the +skill changing. + +**Model the invariant motion, take the scene as input.** A library skill is reused in +other layouts, environments and tasks, so it stores the part that stays the same and +perceives the rest: + +- the motion is written in the object's or target's frame (standoffs, approach + directions, grasp offsets, lift heights, contact strategy), never in one run's + base-frame coordinates; +- its inputs are a scene description (object pose, size and kind, support height, + obstacles) produced by a perception function it ships with and that callers may + replace, so a new environment plugs in its own perception and keeps the motion; +- object descriptions and per-environment settings are parameters with tested ranges, + listed in `## Code`; +- `## When to use` and the evidence say which variations were tested (positions, + orientations, sizes, distances, distractors, lighting), so a later session knows how + far the invariants have been shown to hold. + +**Leave room for the agent's perception.** A library skill is used in scenes its author +never saw, so it must not be a blind script: + +- each primitive re-observes what it acts on, and returns the `frame_id`s it used with + its result, so the agent running it can look; +- mark the **perception checkpoints** in `## Checks`: where the agent should look before + continuing, at which frame, and what it must see (for example "both fingertips below + the box's top edge, box centred between them"), written as the question to hand to a + perception subagent; +- keep geometry in code (depth, pixel to position, forward kinematics) and leave + semantically rich perception (what the objects are, which is the target, whether a + grasp holds, why it failed) to perception subagents at those checkpoints rather than + brittle hand-written rules; +- document every checkpoint in a `### Perception checkpoints` table under `## Checks` + (the merge requires the heading; write "None" if the skill truly has none): step, + subagent model (a fast model such as `haiku` for structured perception, which we + recommend; `sonnet` / `opus` for open-ended scene understanding or diagnosis), frames, + the exact question, expected answer, pass criterion, action on fail. The code returns the same brief in its result, as + autonomous-control describes: + + ```python + "checkpoint": { + "subagent": "haiku", # fast model for structured checks; sonnet / opus for diagnosis + "frames": ["runtime/frames//head_camera.jpg"], + "question": "Are both fingertips below the box's top edge, one at each end face?", + "answer": "yes | no, plus the pixel of each fingertip", + "pass_if": "yes for both fingertips", + "on_fail": "back off 3 cm outward, re-localize the end faces, retry once; then stop", + } + ``` + +- inputs that come from perception (object pose, size, the surface to place on) are + parameters the agent can supply from its own verified observation, with the skill's own + localization as the default; +- when a check is ambiguous the skill stops safely and returns the frames and `why` + rather than guessing; +- `run.py` may chain the primitives for the case its evidence covers, but its `## Code` + section says which checkpoints that chain skips and under which conditions that was + verified. + +When you build a task from library primitives, contribute the composition as its own +skill (`uses:` the primitives) with its own evidence, and contribute any primitive you had +to write or fix on the way. + +## 4. The format (checked by the merge) + +``` +skill-library/ + INDEX.md one row per skill + skills// + SKILL.md frontmatter + the seven sections + code/run.py the entry: main(ctx, ...) -> {ok, measured, why} + code/*.py helpers it imports (relative to code/) + evidence/runs.jsonl one JSON object per run of the code + evidence/images/*.jpg visual references (≤ 400 kB each, e.g. 640 px JPEG) +``` + +`INDEX.md` row: `| [](skills//SKILL.md) | draft | what it does | when to use |`. + +`SKILL.md`: + +```markdown +--- +name: # equals the folder name +description: +status: draft # draft | verified | deprecated +robot: {{ robot.name }} +entry: code/run.py +version: 1 # bump when behaviour changes +uses: [localize-box] # optional: library skills this one imports +--- + +# + +## When to use +Observable conditions: the object (kind, size range, weight if known), where it is +(floor, table, height and distance ranges), the scene (clutter, lighting), the robot's +start posture. Also when NOT to use it. + +## Preconditions +What the code checks before moving, and how (tools, thresholds). The robot posture it +starts from; gripper state; what must be visible. + +## Procedure +The steps in order, each with its tool calls and the reason for its parameters. + +## Code +Entry and how to call it; every parameter with its tested range and default; what it +returns in `measured`; where it logs. + +## Checks +The completion check of each step (observable: image, depth, measured opening, wrist +force, joint state) and the final success check, with thresholds. + +### Perception checkpoints +| Step | Subagent model | Frames | Question | Expected answer | Pass if | On fail | +|---|---|---|---|---|---|---| +| grasp | haiku | head_camera after the squeeze | Is the box between both fingertips, below its top edge? | yes / no + fingertip pixels | yes | open, back off 3 cm, re-localize, retry once | + +## Failure modes +Each failure seen: how it shows, how the code detects it, what it does (stop safely, +retry, report), and what the operator or a later session should do. + +## Evidence +Table of runs (date, session, outcome, unattended, conditions) summarizing +`evidence/runs.jsonl`, and the visual references: `![start](evidence/images/<file>.jpg)` +of the start state and the success state. +``` + +The code (`main(ctx, **params)`): + +- Re-localizes everything it acts on from fresh observations; no positions remembered + from one scene unless they are relative to something it observes. +- Checks its preconditions first and stops with `ok: False` and a clear `why` when one + fails; checks each step's completion before the next; ends in a safe state (holding, + arms in) on failure. +- Uses the robot only through `ctx` (the session's tools); named constants with their + tested ranges at the top; no paths outside the workspace; only the agent environment's + packages. +- Returns `{"ok": bool, "measured": {...}, "why": str}`, with the measurements the + checks used. + +Each line of `evidence/runs.jsonl` (append; never rewrite others' lines): + +```json +{"session": "<session name>", "date": "<YYYY-MM-DD>", "commit": "<git commit of the code that ran>", + "outcome": "success", "unattended": true, + "conditions": "cardboard box 0.30 x 0.20 x 0.15 m on the floor 0.9 m ahead, robot at ready", + "checks": {"box_lifted_m": 0.12, "opening_m": 0.21, "wrist_force_n": [12, 11]}, + "images": ["evidence/images/2026-10-08-start.jpg", "evidence/images/2026-10-08-end.jpg"], + "notes": "optional"} +``` + +- `unattended: true` only when the code ran from start to end with no help from you or + the operator (a scene reset before the run is fine). +- `images`: at least the start and end frame of that run, copied from `runtime/frames/` + and downscaled. Record failures too; they define the skill's limits. + +**Status** follows the evidence: + +| Status | Needs | +|---|---| +| `draft` | the seven sections, a compiling entry with `main(ctx, ...)`, at least one image | +| `verified` | additionally at least 2 unattended successful runs with images in `runs.jsonl`, ideally on different layouts or sessions | +| `deprecated` | why, and what replaces it | + +When you change a verified skill's behaviour, bump `version`; it stays verified only if +new unattended runs of the new code meet the bar, otherwise set it back to `draft`. + +## 5. Commit, sync and merge, every session + +```bash +cd skill-library +git add -A && git commit -m "<slug>: what changed" +git fetch origin && git merge origin/main # take in other sessions' merges; resolve conflicts +``` + +Then call `skill_library_merge` with a one-line `message`. It replies: + +- `merged: true`: done; later sessions see it. +- `problems`: the format or evidence rules above that a changed skill breaks; fix, commit, + call again. +- `conflicts`: `git fetch origin && git merge origin/main`, resolve (keep both sessions' + `runs.jsonl` lines and reconcile the text), commit, call again. + +Merge at least when a skill is first automated (as `draft`), when it becomes `verified` +or changes, and always before you end the session or write your final report, so nothing +learned is lost. Only committed changes merge. A merge may change only `INDEX.md` and +files under `skills/`. diff --git a/hermit/agent/evolver/methods/rax/upstream/skill_library.py b/hermit/agent/evolver/methods/rax/upstream/skill_library.py new file mode 100644 index 00000000..bf6c9869 --- /dev/null +++ b/hermit/agent/evolver/methods/rax/upstream/skill_library.py @@ -0,0 +1,354 @@ +"""The agent's persistent skill library: task skills learned across sessions, one git repository per robot. + +Separate from the harness's read-only skills (`agent_skills/`, rendered into `.agents/skills/`): +those are written by people; this library is written by agents, one session at a time. + + <artifact root>/skill-library/<robot>/ the library (git, branch main); only the harness writes it + <session>/agent-workspace/skill-library/ the session's clone, on branch session/<session name> + +The agent reads the library, runs its skills, and commits new or improved skills on its +session branch. `merge()` (the harness tool `skill_library_merge`) validates the branch and +merges it into main. The harness never runs git inside the agent's clone (its config and +hooks are the agent's): it copies the clone's object store to a scratch directory with a +fresh config and no hooks, fetches the branch from there into the library, validates the +files of that commit as data (code is only compiled, never run), and merges. + +Format (enforced by `validate_tree`, documented in the library README and the agent's +`continual-learning` skill): + + INDEX.md one table row per skill: slug link, status, what, when + skills/<slug>/SKILL.md frontmatter + the required sections below + skills/<slug>/code/*.py the executable procedure; the entry defines main(ctx, ...) + skills/<slug>/evidence/runs.jsonl one JSON object per run of the code + skills/<slug>/evidence/images/ visual references (jpg / png) the runs and SKILL.md cite +""" +from __future__ import annotations + +import fcntl +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile + +LIBRARY_DIR = 'skill-library' +ENVIRONMENT = 'RAX_SKILL_LIBRARY' +STATUSES = ('draft', 'verified', 'deprecated') +SECTIONS = ('When to use', 'Preconditions', 'Procedure', 'Code', 'Checks', 'Failure modes', 'Evidence') +RUN_KEYS = ('session', 'date', 'commit', 'outcome', 'unattended', 'conditions', 'checks', 'images') +VERIFIED_MIN_RUNS = 2 # unattended successful runs of the committed code +MAX_IMAGE_BYTES = 400_000 +MAX_FILE_BYTES = 2_000_000 +MAX_SKILL_BYTES = 25_000_000 # saved frames (RGB + depth + meta) let later sessions replay perception offline +SLUG = re.compile(r'^[a-z0-9][a-z0-9-]{1,60}$') +GIT_ENV = {'GIT_CONFIG_NOSYSTEM': '1', 'GIT_TERMINAL_PROMPT': '0', 'HOME': '/nonexistent'} + +README = """# {robot} skill library + +Skills agents learned on this robot, kept across sessions. Agents read and use them, and +add or improve them on their session branch; the harness tool `skill_library_merge` +checks the format and evidence and merges into `main`. The protocol is the agent skill +`continual-learning`; the rules the merge enforces: + +- `INDEX.md`: one row per skill, `| [slug](skills/slug/SKILL.md) | status | what it does | when to use |`. +- `skills/<slug>/SKILL.md` begins with frontmatter (`name` = the folder name, `description`, + `status`: draft | verified | deprecated, `robot`, `entry`: the code file, e.g. + `code/run.py`) and has the sections {sections}. +- The entry is Python defining `main(ctx, ...)` (ctx: `api.runtime.Context`) that returns + `{{"ok": bool, "measured": {{...}}, "why": str}}`. +- `evidence/runs.jsonl`: one JSON object per run of the code with {run_keys}; `images` are + paths under `evidence/images/` (jpg / png, at most {image_kb} kB each). +- `## Checks` holds a `### Perception checkpoints` table: for each checkpoint the step, the + perception subagent, frames, question, expected answer, pass criterion and action on + fail (or "None"). +- At least one image per skill. `verified` needs at least {verified} unattended successful + runs. A branch may only change `INDEX.md` and files under `skills/`. +- Never delete another session's skill: set its status to `deprecated` and say why. +""" +INDEX = """# Skill index + +| Skill | Status | What it does | When to use | +|---|---|---|---| +""" + + +class LibraryError(RuntimeError): + pass + + +def _git(*args, cwd=None, check=True): + result = subprocess.run(['git', *args], cwd=cwd, capture_output=True, text=True, timeout=60, + env={**os.environ, **GIT_ENV}) + if check and result.returncode: + raise LibraryError(f"git {' '.join(args)}: {(result.stderr or result.stdout).strip()[:500]}") + return result + + +def library_path(config): + """The robot's library: RAX_SKILL_LIBRARY, else <artifact root>/skill-library/<robot> next to sessions/.""" + configured = os.environ.get(ENVIRONMENT) + if configured: + return Path(configured)/config.robot + sessions = Path(config.root).resolve().parent + base = sessions.parent if sessions.name == 'sessions' else sessions + return base/LIBRARY_DIR/config.robot + + +def ensure_library(path, robot): + """Create the library repository (README, INDEX, skills/) on first use.""" + path = Path(path) + if (path/'.git').is_dir(): + return path + path.mkdir(parents=True, exist_ok=True) + _git('init', '-q', '-b', 'main', cwd=path) + _git('config', 'user.name', 'rax harness', cwd=path) + _git('config', 'user.email', 'harness@rax.local', cwd=path) + (path/'README.md').write_text(README.format(robot=robot, sections=', '.join(f'`## {s}`' for s in SECTIONS), + run_keys=', '.join(f'`{k}`' for k in RUN_KEYS), + image_kb=MAX_IMAGE_BYTES // 1000, verified=VERIFIED_MIN_RUNS)) + (path/'INDEX.md').write_text(INDEX) + (path/'skills').mkdir(exist_ok=True) + (path/'skills'/'.gitkeep').write_text('') + _git('add', '-A', cwd=path) + _git('commit', '-q', '-m', f'Initialize the {robot} skill library', cwd=path) + return path + + +def branch_name(config): + return f'session/{Path(config.root).name}' + + +def checkout(config, workspace): + """Clone the library into the new workspace on the session's branch; returns its summary.""" + library = ensure_library(library_path(config), config.robot) + clone = Path(workspace)/LIBRARY_DIR + _git('clone', '-q', '--no-hardlinks', str(library), str(clone)) + _git('checkout', '-q', '-b', branch_name(config), cwd=clone) + _git('config', 'user.name', f'agent {Path(config.root).name}', cwd=clone) + _git('config', 'user.email', 'agent@rax.local', cwd=clone) + return {'library': str(library), 'clone': str(clone), 'branch': branch_name(config), + 'skills': len(list((clone/'skills').glob('*/SKILL.md')))} + + +# ----- validation (files of a commit, read as data) -------------------------------------------- +def _frontmatter(text): + match = re.match(r'^---\n(.*?)\n---\n', text, re.S) + if not match: + return None + fields = {} + for line in match.group(1).splitlines(): + if ':' in line: + key, value = line.split(':', 1) + value = re.sub(r'\s+#.*$', '', value) # a trailing YAML comment + fields[key.strip()] = value.strip().strip('"\'') + return fields + + +def _list_field(value): + """A frontmatter list written inline: `[a, b]` or `a, b`.""" + return [item.strip().strip('"\'') for item in value.strip().strip('[]').split(',') if item.strip()] + + +def validate_skill(folder): + """Problems of one skill folder (a list of strings; empty when it follows the format).""" + folder = Path(folder) + slug = folder.name + problems = [] + + def bad(message): + problems.append(f'skills/{slug}: {message}') + links = [p for p in [folder, *folder.rglob('*')] if p.is_symlink()] + if links: # refuse before reading anything through a link + bad(f'symlinks are not allowed: {[str(p.relative_to(folder.parent)) for p in links][:5]}') + return problems + if not SLUG.match(slug): + bad('folder name must be lower-case letters, digits and hyphens') + total = sum(p.stat().st_size for p in folder.rglob('*') if p.is_file()) + if total > MAX_SKILL_BYTES: + bad(f'{total / 1e6:.1f} MB is over the {MAX_SKILL_BYTES / 1e6:g} MB per skill') + for p in folder.rglob('*'): + if p.is_file() and p.stat().st_size > MAX_FILE_BYTES: + bad(f'{p.relative_to(folder)} is over {MAX_FILE_BYTES / 1e6:g} MB') + skill = folder/'SKILL.md' + if not skill.is_file(): + bad('SKILL.md missing') + return problems + text = skill.read_text(errors='replace') + meta = _frontmatter(text) + if meta is None: + bad('SKILL.md must begin with --- frontmatter ---') + return problems + for key in ('name', 'description', 'status', 'robot', 'entry'): + if not meta.get(key): + bad(f'frontmatter needs {key}') + if meta.get('name') and meta['name'] != slug: + bad(f"frontmatter name {meta['name']!r} must equal the folder name") + status = meta.get('status') + if status and status not in STATUSES: + bad(f'status must be one of {", ".join(STATUSES)}') + headings = set(re.findall(r'^##\s+(.+?)\s*$', text, re.M)) + for section in SECTIONS: + if section not in headings: + bad(f'SKILL.md needs a "## {section}" section') + if not re.search(r'^###\s+Perception checkpoints\s*$', text, re.M): + bad('SKILL.md needs a "### Perception checkpoints" table under "## Checks" (what each perception ' + 'subagent checks: step, subagent, frames, question, expected answer, pass criterion, on fail; ' + 'or "None")') + entry = meta.get('entry') + if entry: + code = (folder/entry).resolve() + if not code.is_relative_to(folder.resolve()) or not code.is_file() or code.suffix != '.py': + bad(f'entry {entry} must be a .py file inside the skill folder') + else: + try: + compile(code.read_text(errors='replace'), entry, 'exec') # syntax only: nothing runs + except (SyntaxError, ValueError) as exc: + bad(f'entry {entry} does not compile: {str(exc)[:200]}') + if not re.search(r'^def main\(\s*ctx\b', code.read_text(errors='replace'), re.M): + bad(f'entry {entry} must define main(ctx, ...)') + images = folder/'evidence'/'images' + image_files = [p for p in images.glob('*') if p.suffix.lower() in ('.jpg', '.jpeg', '.png')] if images.is_dir() else [] + if not image_files: + bad('evidence/images/ needs at least one image (a visual reference of the start state or result)') + for p in image_files: + if p.stat().st_size > MAX_IMAGE_BYTES: + bad(f'{p.relative_to(folder)} is {p.stat().st_size // 1000} kB (at most {MAX_IMAGE_BYTES // 1000} kB)') + runs_file = folder/'evidence'/'runs.jsonl' + runs = [] + if runs_file.is_file(): + for n, line in enumerate(runs_file.read_text(errors='replace').splitlines(), start=1): + if not line.strip(): + continue + try: + run = json.loads(line) + except json.JSONDecodeError: + bad(f'evidence/runs.jsonl line {n} is not JSON') + continue + missing = [k for k in RUN_KEYS if k not in run] + if missing: + bad(f'evidence/runs.jsonl line {n} lacks {missing}') + continue + if run['outcome'] not in ('success', 'failure'): + bad(f'evidence/runs.jsonl line {n}: outcome must be success or failure') + for image in run['images'] if isinstance(run['images'], list) else []: + path = (folder/image).resolve() + if not path.is_relative_to(images.resolve()) or not path.is_file(): + bad(f'evidence/runs.jsonl line {n}: image {image} is not a file under evidence/images/') + runs.append(run) + elif status == 'verified': + bad('verified needs evidence/runs.jsonl') + if status == 'verified': + good = [r for r in runs if r.get('outcome') == 'success' and r.get('unattended') is True and r.get('images')] + if len(good) < VERIFIED_MIN_RUNS: + bad(f'verified needs at least {VERIFIED_MIN_RUNS} unattended successful runs with images in ' + f'evidence/runs.jsonl (has {len(good)}); keep it draft until then') + return problems + + +def validate_tree(tree, changed): + """Problems of a library tree, for the files a branch changed.""" + tree = Path(tree) + problems = [] + outside = [p for p in changed if not (p == 'INDEX.md' or p.startswith('skills/'))] + if outside: + problems.append(f'a session branch may only change INDEX.md and skills/; it changed {sorted(outside)[:10]}') + slugs = sorted({p.split('/')[1] for p in changed if p.startswith('skills/') and p.count('/') >= 2}) + index_path = tree/'INDEX.md' + if index_path.is_symlink(): + return problems + ['INDEX.md must be a file, not a symlink'], [] + index = index_path.read_text(errors='replace') if index_path.is_file() else '' + for slug in slugs: + folder = tree/'skills'/slug + if not folder.is_dir(): + problems.append(f'skills/{slug} was deleted; set its status to deprecated instead') + continue + problems += validate_skill(folder) + if f'(skills/{slug}/SKILL.md)' not in index: + problems.append(f'INDEX.md needs a row linking skills/{slug}/SKILL.md') + meta = _frontmatter((folder/'SKILL.md').read_text(errors='replace')) if (folder/'SKILL.md').is_file() else None + for used in _list_field((meta or {}).get('uses', '')): + if not (tree/'skills'/used/'SKILL.md').is_file(): + problems.append(f'skills/{slug}: uses {used!r}, which is not a skill in the library') + return problems, slugs + + +# ----- merge (the harness tool) --------------------------------------------------------------- +def _copy_objects(source, target): + """Copy a git object store without symlinks and without alternates (no reads outside the clone).""" + source = Path(source) + for directory, names, files in os.walk(source, followlinks=False): + here = Path(directory) + out = Path(target)/here.relative_to(source) + out.mkdir(parents=True, exist_ok=True) + names[:] = [n for n in names if not (here/n).is_symlink()] + for name in files: + path = here/name + if path.is_symlink() or (here.name == 'info' and name in ('alternates', 'http-alternates')): + continue + shutil.copyfile(path, out/name) + + + +def merge(config, workspace, message): + """Validate the session branch of the workspace's clone and merge it into the library's main.""" + library = ensure_library(library_path(config), config.robot) + clone = Path(workspace)/LIBRARY_DIR + branch = branch_name(config) + if not (clone/'.git').is_dir(): + raise LibraryError('the workspace has no skill-library clone') + lock = open(library/'.git'/'rax-merge.lock', 'w') + fcntl.flock(lock, fcntl.LOCK_EX) + scratch = Path(tempfile.mkdtemp(prefix='skill-merge-')) + try: + # The agent's objects only: no config, hooks or info from its .git. + objects = scratch/'agent.git' + objects.mkdir() + _copy_objects(clone/'.git'/'objects', objects/'objects') + refs = clone/'.git'/'refs'/'heads'/Path(branch) + packed = clone/'.git'/'packed-refs' + head = refs.read_text().strip() if refs.is_file() else None + if head is None and packed.is_file(): + for line in packed.read_text().splitlines(): + if line.endswith(f' refs/heads/{branch}'): + head = line.split()[0] + if not head or not re.fullmatch(r'[0-9a-f]{40}', head): + raise LibraryError(f'no commit on {branch}: commit your skill first (git add, git commit)') + (objects/'refs'/'heads').mkdir(parents=True) + (objects/'HEAD').write_text('ref: refs/heads/main\n') + (objects/'config').write_text('[core]\n\trepositoryformatversion = 0\n\tbare = true\n') + _git('fetch', '-q', '--no-tags', str(objects), head, cwd=library) + base = _git('merge-base', 'main', head, cwd=library).stdout.strip() + changed = [p for p in _git('diff', '--name-only', base, head, cwd=library).stdout.splitlines() if p] + if not changed: + return {'merged': False, 'reason': 'no committed changes on the session branch since its base', + 'branch': branch, 'head': head} + tree = scratch/'tree' + tree.mkdir() + archive = subprocess.run(['git', 'archive', '--format=tar', head], cwd=library, capture_output=True, + timeout=60, env={**os.environ, **GIT_ENV}) + if archive.returncode: + raise LibraryError('git archive failed: ' + archive.stderr.decode(errors='replace')[:300]) + subprocess.run(['tar', '-x', '-C', str(tree)], input=archive.stdout, check=True, timeout=60) + problems, slugs = validate_tree(tree, changed) + if problems: + return {'merged': False, 'branch': branch, 'head': head, 'problems': problems, + 'do': 'fix these in skill-library/, commit, and call skill_library_merge again'} + before = _git('rev-parse', 'main', cwd=library).stdout.strip() + result = _git('merge', '--no-ff', '-m', f'Merge {branch}: {message.strip()[:200]}', head, cwd=library, + check=False) + if result.returncode: + conflicts = _git('diff', '--name-only', '--diff-filter=U', cwd=library, check=False).stdout.split() + _git('merge', '--abort', cwd=library, check=False) + return {'merged': False, 'branch': branch, 'head': head, 'conflicts': conflicts, + 'do': 'in skill-library/: git fetch origin && git merge origin/main, resolve the conflicts ' + '(keep both sessions\' evidence), commit, and call skill_library_merge again'} + after = _git('rev-parse', 'main', cwd=library).stdout.strip() + return {'merged': True, 'branch': branch, 'head': head, 'library_main': after, 'previous_main': before, + 'skills': slugs, 'changed_files': len(changed), + 'next': 'git fetch origin in skill-library/ to see the merged main'} + finally: + shutil.rmtree(scratch, ignore_errors=True) + fcntl.flock(lock, fcntl.LOCK_UN) + lock.close() diff --git a/tests/README.md b/tests/README.md index 4f45e3ba..d18e37f6 100644 --- a/tests/README.md +++ b/tests/README.md @@ -10,7 +10,7 @@ python -m pytest --integration ... # also the tests that run an agent CLI insta | Group | What it covers | |---|---| | `core/` | the framework: the Trainer, templates and `check_spec`, deployment and host exporters, the agent layers (Base Agents, CLI agents, model bindings), the sandbox and isolation, the generic AgentEvolvers | -| `methods/<name>/` | one method: its Evolver, its template and its examples (`ace`, `ahe`, `aspire`, `continual_harness`, `evosafe`, `harness2`, `meta_harness_adapter`, `mwm`, `opro`, `optimizers` for GEPA and SkillOpt, `reharness`, `rrsi_adapter`, `she`) | +| `methods/<name>/` | one method: its Evolver, its template and its examples (`ace`, `ahe`, `aspire`, `continual_harness`, `evosafe`, `harness2`, `meta_harness_adapter`, `mwm`, `opro`, `optimizers` for GEPA and SkillOpt, `rax`, `reharness`, `rrsi_adapter`, `she`) | `--changed` reads `selection.py`: `core/` runs for every change but documentation (its tests also read every method's template, manifest and packaging); a method's own files (its Evolver, its template, its examples, its tests) diff --git a/tests/core/test_selection.py b/tests/core/test_selection.py index c48640c1..3d88618f 100644 --- a/tests/core/test_selection.py +++ b/tests/core/test_selection.py @@ -62,8 +62,8 @@ def test_a_benchmarks_shared_files_run_the_methods_with_an_example_there(): "rrsi_adapter", "core"} assert groups_for("examples/servelearnbench/utils/x.py") == {"mwm", "core"} # an engine several benchmarks run on: the methods with an example under any of them - assert groups_for("examples/cap_harness/utils/agent/sim.py") == {"aspire", "core"} - assert groups_for("examples/libero/utils/agent/task.py") == {"aspire", "core"} + assert groups_for("examples/cap_harness/utils/agent/sim.py") == {"aspire", "rax", "core"} + assert groups_for("examples/libero/utils/agent/task.py") == {"aspire", "rax", "core"} assert groups_for("examples/robosuite/aspire/run.yaml") == {"aspire", "core"} groups, why = select(["hermit/cli.py", "examples/officeqa/rrsi_adapter/README.md", "docs/index.md"]) assert groups == {"core", "rrsi_adapter"} and why == {"core": "hermit/cli.py", diff --git a/tests/methods/rax/test_rax.py b/tests/methods/rax/test_rax.py new file mode 100644 index 00000000..59e63447 --- /dev/null +++ b/tests/methods/rax/test_rax.py @@ -0,0 +1,1099 @@ +"""RAX: the rax template (RAX's skill library and its check), RAX's library code on both sides of a step (library.py: +the session's repository, its export, the Evolver's take-in), the merge tool a session is given (library_server.py), +RAX's relaunch policy as a Stop hook (stop_hook.py), RAX's session as task functions (actor.py) run by the +framework's Claude Code agent, the Evolver and its merge program (evolver.py, merge.py), and the LIBERO example: its +rows and splits, its host service, its judge and its configs. + +Stand-ins: a scripted `claude` on PATH that acts as the agent (it commits a skill in its clone and calls +skill_library_merge through the server the session's MCP configuration names), a RAX checkout of the files the task +functions read (its START_PROMPT.md, verbatim), the example's service with RAX's parts replaced (no operator script, +no workspace maker, no frontend, no simulator), a robot socket that answers `status`. No model, no network, no GPU.""" +import base64 +import dataclasses +import hashlib +from http.server import ThreadingHTTPServer +import importlib.util +import io +import json +import os +from pathlib import Path +import py_compile +import shutil +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import threading +from types import ModuleType, SimpleNamespace + +import pytest + +from hermit.agent.evolver.methods.rax import actor as A +from hermit.agent.evolver.methods.rax import library as L +from hermit.agent.evolver.methods.rax import library_server as S +from hermit.agent.evolver.methods.rax import merge as M +from hermit.agent.evolver.methods.rax import stop_hook as H +from hermit.agent.evolver.methods.rax.upstream import skill_library as rax +from hermit.isolate import _safe +from hermit.spec import check_spec + +ROOT = Path(__file__).resolve().parents[3] +TEMPLATE = ROOT / "hermit" / "adapter" / "templates" / "rax" +METHOD = ROOT / "hermit" / "agent" / "evolver" / "methods" / "rax" +EXAMPLE = ROOT / "examples" / "libero" / "rax" +# RAX's auto_research_agent/START_PROMPT.md at libero-pro/native 1767412, and the prompt its launcher gives in code mode +START_PROMPT = ("Read AGENTS.md, then MCP_SESSION.md and TASK.md, and call `status`. Follow the AGENTS.md\n" + "workflow{% if agent_formal %}: solve the task by hand, automate it, and practise with your\n" + "controller in every episode; when no episode remains, follow `status.next_step` and end\n" + "your turn{% endif %}.\n") +CODE_MODE = "Read AGENTS.md, then MCP_SESSION.md and TASK.md, and call `status`. Follow the AGENTS.md\nworkflow." +PNG = b"\x89PNG\r\n\x1a\n" + bytes(64) # an image as RAX's check reads one: its suffix and its size +TASK = "train-libero_spatial_0" + + +@pytest.fixture +def tmp_path(): + """A directory outside /tmp: the template check runs under bubblewrap with an empty tmpfs at /tmp, and a Unix + socket's path must be short.""" + base = Path.home() / ".cache" / "hermit-tests" + base.mkdir(parents=True, exist_ok=True) + path = Path(tempfile.mkdtemp(dir=base, prefix="rax-")).resolve() + yield path + if not os.environ.get("KEEP_TEST_DIRS"): + shutil.rmtree(path, ignore_errors=True) + + +def _load(name: str, path: Path): + spec_ = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(module) + return module + + +def seed(tmp: Path, name: str = "adapter") -> Path: + adapter = tmp / name + shutil.copytree(TEMPLATE, adapter, ignore=shutil.ignore_patterns("__pycache__")) + return adapter + + +def spec(path) -> dict: + r = check_spec(Path(path), TEMPLATE, deploy=False) + return {"passed": r.passed, "issues": [{"path": i.path, "problem": i.problem} for i in r.issues]} + + +def skill_files(slug: str, *, status: str = "draft", runs: int = 0, drop: str | None = None) -> dict[str, bytes]: + """A skill in RAX's format (services/skill_library.py validate_skill), relative to the library: its SKILL.md + (without the section `drop`), entry, image and runs.""" + sections = [s for s in rax.SECTIONS if s != drop] + body = "\n\n".join(f"## {s}\n\n" + ("### Perception checkpoints\n\nNone" if s == "Checks" else f"{s} of {slug}.") + for s in sections) + text = (f"---\nname: {slug}\ndescription: Picks up a bowl by its rim.\nstatus: {status}\nrobot: {L.ROBOT}\n" + f"entry: code/run.py\n---\n\n# {slug}\n\n{body}\n") + run = {"session": "s1", "date": "2026-11-28", "commit": "0" * 40, "outcome": "success", "unattended": True, + "conditions": "official layout", "checks": [], "images": ["evidence/images/start.png"]} + return {f"skills/{slug}/SKILL.md": text.encode(), + f"skills/{slug}/code/run.py": b"def main(ctx, bowl='akita black bowl'):\n" + b" return {'ok': True, 'measured': {}, 'why': ''}\n", + f"skills/{slug}/evidence/images/start.png": PNG, + f"skills/{slug}/evidence/runs.jsonl": "".join(json.dumps(run) + "\n" for _ in range(runs)).encode()} + + +def add_skill(tree: Path, slug: str, *, index: bool = True, **kw) -> None: + for name, data in skill_files(slug, **kw).items(): + (tree / name).parent.mkdir(parents=True, exist_ok=True) + (tree / name).write_bytes(data) + if index: + with open(tree / "INDEX.md", "a") as f: + f.write(f"| [{slug}](skills/{slug}/SKILL.md) | {kw.get('status', 'draft')} | Picks up a bowl. | " + f"A bowl on the table. |\n") + + +def commit(clone: Path, message: str) -> None: + L.git("add", "-A", cwd=clone) + L.git("commit", "-q", "-m", message, cwd=clone) + + +def session(tmp: Path, adapter: Path, name: str, *, run: str = "run") -> tuple[Path, Path, str]: + """A session's library as `prepare` makes it: (its repository, its workspace with the clone, the base commit).""" + repository = tmp / run / "rax" / "library" / L.ROBOT + base = L.build(adapter, repository) + work = tmp / run / "work" + work.mkdir(parents=True) + L.checkout(repository, name, work) + return repository, work, base + + +# ---------- the vendored code and the template ---------- + +def test_the_vendored_files_are_raxs_own_at_the_pinned_commits(): + """RAX's library module and its continual-learning skill are RAX's (real/rainbow 36c926c) byte for byte, with + RAX's license and notice; the method page and the launcher name the commits.""" + vendored = {"skill_library.py": "4a91f721cdcc32e1a0b1631733b3e0606d1d0e72796d5eb80da2a80f29ec7475", + "continual-learning.SKILL.md": "86151e017553648912b806ad95be62cf1a58532a7160a025f4b94ced3dc0588d"} + for name, digest in vendored.items(): + assert hashlib.sha256((METHOD / "upstream" / name).read_bytes()).hexdigest() == digest, name + assert "Apache License" in (METHOD / "upstream" / "LICENSE").read_text() + assert "RAX contributors" in (METHOD / "upstream" / "NOTICE").read_text() + page = (ROOT / "docs" / "methods" / "rax.md").read_text() + assert "36c926c" in page and "1767412" in page and "evolver.yaml" in page + assert "PINNED=1767412c5300b9358059ae6a39740c3c28d2b8b9" in (EXAMPLE / "launch.sh").read_text() + + +def test_the_template_root_passes_its_own_check_and_is_raxs_empty_library(tmp_path): + """The template is the library RAX's ensure_library starts a robot with: the library's first commit holds RAX's + files for this robot byte for byte (README.md, INDEX.md and an empty skills/.gitkeep, which `build` adds: a + package keeps no dotfile, so the template has no skills/).""" + assert check_spec(TEMPLATE, TEMPLATE).passed + assert (TEMPLATE / "README.md").read_text() == L.readme() + assert not (TEMPLATE / "skills").exists() + ours = tmp_path / "ours" / L.ROBOT + L.build(TEMPLATE, ours) + theirs = rax.ensure_library(tmp_path / "theirs" / L.ROBOT, L.ROBOT) + assert L.git("ls-tree", "-r", "main", cwd=ours) == L.git("ls-tree", "-r", "main", cwd=theirs) + + +def test_the_check_runs_raxs_checks_on_every_skill_and_refuses_links(tmp_path): + """A valid skill passes; a verified skill short of its runs, a skill without its index row and a link are + refused, each naming the path the Trainer repairs.""" + adapter = seed(tmp_path) + add_skill(adapter, "grasp-bowl") + add_skill(adapter, "place-plate", status="verified", runs=2) + assert spec(adapter) == {"passed": True, "issues": []} + add_skill(adapter, "open-drawer", status="verified", runs=1) + add_skill(adapter, "close-drawer", index=False) + issues = spec(adapter)["issues"] + assert any(i["path"] == "skills/open-drawer" and "verified needs at least 2" in i["problem"] for i in issues) + assert any(i["path"] == "INDEX.md" and "skills/close-drawer/SKILL.md" in i["problem"] for i in issues) + shutil.rmtree(adapter / "skills" / "open-drawer") + shutil.rmtree(adapter / "skills" / "close-drawer") + (adapter / "skills" / "grasp-bowl" / "code" / "alias.py").symlink_to("run.py") + assert not spec(adapter)["passed"] + with pytest.raises(rax.LibraryError, match="links are not allowed"): + L.library_files(adapter) + + +# ---------- the library on both sides of a step ---------- + +def test_a_library_built_from_the_same_files_is_the_same_commit(tmp_path): + """Every session and the Evolver that start from one adapter start from one commit (RAX's merge base): a fixed + identity and date, every file 100644 whatever its mode in the adapter.""" + adapter = seed(tmp_path) + add_skill(adapter, "grasp-bowl") + (adapter / "skills" / "grasp-bowl" / "code" / "run.py").chmod(0o755) + first = L.build(adapter, tmp_path / "a" / L.ROBOT) + assert L.build(adapter, tmp_path / "b" / L.ROBOT) == first + tree = L.git("ls-tree", "-r", "main", cwd=tmp_path / "a" / L.ROBOT).splitlines() + assert tree and all(line.startswith("100644 ") for line in tree) + assert {line.split("\t")[1] for line in tree} == {*L.library_files(adapter), L.KEEP} + (adapter / L.KEEP).write_text("") # an adapter a step wrote back holds main's .gitkeep + assert L.build(adapter, tmp_path / "k" / L.ROBOT) == first + with open(adapter / "INDEX.md", "a") as f: + f.write("\n") + assert L.build(adapter, tmp_path / "c" / L.ROBOT) != first + with pytest.raises(rax.LibraryError, match="made fresh"): + L.build(adapter, tmp_path / "a" / L.ROBOT) + with pytest.raises(ValueError, match="named after its robot"): + L.checkout(tmp_path / "x" / "other", "s", tmp_path) + + +def test_a_sessions_merges_reach_the_next_adapter_through_its_bundle_and_raxs_merge(tmp_path): + """The session merges into its own repository with RAX's merge; `export` bundles its main past the base; the + Evolver's repository of the same adapter has the same base, takes the bundle in with RAX's merge, and writes the + merged tree back as the adapter, which passes the template's check.""" + adapter = seed(tmp_path) + name = "train-libero_spatial_0-1a2b3c4d" + repository, work, base = session(tmp_path, adapter, name) + clone = work / rax.LIBRARY_DIR + assert L.git("rev-parse", "--abbrev-ref", "HEAD", cwd=clone).strip() == f"session/{name}" + add_skill(clone, "grasp-bowl") + commit(clone, "grasp-bowl, draft") + reply = L.merge(repository, name, work, "grasp-bowl: draft") + assert reply["merged"] and reply["skills"] == ["grasp-bowl"] and reply["previous_main"] == base + log = tmp_path / "log" + record = L.export(repository, base, log) + assert record == {"base": base, "head": reply["library_main"], "bundle": L.BUNDLE} + evolver = tmp_path / "evolver" / L.ROBOT + assert L.build(adapter, evolver) == base + taken = L.take_in(evolver, log / L.BUNDLE, record, name, "the merges of task t's session") + assert taken["merged"] and taken["skills"] == ["grasp-bowl"] + assert "skills/grasp-bowl/SKILL.md" in L.write_tree(evolver, adapter) + assert (adapter / "skills" / "grasp-bowl" / "evidence" / "images" / "start.png").read_bytes() == PNG + assert "(skills/grasp-bowl/SKILL.md)" in (adapter / "INDEX.md").read_text() + assert (adapter / "README.md").read_text() == L.readme() + assert spec(adapter)["passed"] + forged = {**record, "head": "f" * 40} # a record that does not name the bundle's main + again = tmp_path / "again" / L.ROBOT + assert L.build(seed(tmp_path, "original"), again) == base + assert "not the recorded" in L.take_in(again, log / L.BUNDLE, forged, name, "m")["reason"] + + +def test_the_export_says_when_nothing_was_merged_and_refuses_a_main_off_the_base(tmp_path): + """Nothing merged: no bundle. A main that does not descend from the session's base, or no main at all, is an + error the Evolver reads, not a bundle.""" + adapter = seed(tmp_path) + repository, _, base = session(tmp_path, adapter, "s1") + assert L.export(repository, base, tmp_path / "log") == {"base": base, "head": base, "bundle": None} + other = L.build(adapter, tmp_path / "other" / L.ROBOT) + (repository / "README.md").write_text("another library\n") + L.git("add", "-A", cwd=repository) + L.git("commit", "-q", "--amend", "-m", "rewritten", cwd=repository) # main is no longer past the base + record = L.export(repository, base, tmp_path / "log2") + assert record["bundle"] is None and "does not descend" in record["error"] and other == base + shutil.rmtree(repository / ".git" / "refs" / "heads") + (repository / ".git" / "refs" / "heads").mkdir() + (repository / ".git" / "packed-refs").unlink(missing_ok=True) + assert "no main branch" in L.export(repository, base, tmp_path / "log3")["error"] + + +def test_raxs_merge_answers_a_broken_skill_and_a_change_outside_the_library_with_its_problems(tmp_path): + """RAX's merge refuses what its format forbids and says what to do; nothing reaches main.""" + adapter = seed(tmp_path) + repository, work, base = session(tmp_path, adapter, "s1") + clone = work / rax.LIBRARY_DIR + add_skill(clone, "grasp-bowl", drop="Procedure") + (clone / "README.md").write_text("mine\n") + commit(clone, "broken") + reply = L.merge(repository, "s1", work, "broken") + assert reply["merged"] is False and "skill_library_merge again" in reply["do"] + assert any('needs a "## Procedure" section' in p for p in reply["problems"]) + assert any("may only change INDEX.md and skills/" in p for p in reply["problems"]) + assert L.git("rev-parse", "main", cwd=repository).strip() == base + + +# ---------- the session's merge tool ---------- + +def _session_record(work: Path, record: dict) -> None: + (work.parent / "rax").mkdir(parents=True, exist_ok=True) + (work.parent / "rax" / "session.json").write_text(json.dumps(record)) + + +def test_the_merge_tool_is_raxs_skill_library_merge(tmp_path): + """The tool's name, schema and one-line refusal are RAX's frontend's; its call is RAX's merge into the session's + repository; an error is the agent's to read (isError), as RAX's frontend returns one.""" + adapter = seed(tmp_path) + name = "train-libero_spatial_0-1a2b3c4d" + repository, work, base = session(tmp_path, adapter, name) + _session_record(work, {"name": name, "repository": str(repository), "base": base}) + rpc = lambda method, params=None, ident=1: S.handle(work, {"jsonrpc": "2.0", "id": ident, "method": method, + **({"params": params} if params is not None else {})}) + assert rpc("initialize", {})["result"]["protocolVersion"] == "2025-06-18" + assert rpc("notifications/initialized") is None + tool = rpc("tools/list")["result"]["tools"][0] + assert tool["name"] == "skill_library_merge" and tool["inputSchema"]["required"] == ["message"] + assert tool["inputSchema"]["properties"]["message"]["maxLength"] == 500 + assert tool["inputSchema"]["additionalProperties"] is False + for arguments in ({}, {"message": " "}, {"message": "x", "force": True}): + result = rpc("tools/call", {"name": "skill_library_merge", "arguments": arguments})["result"] + assert result["isError"] and json.loads(result["content"][0]["text"])["error"]["message"] == \ + "skill_library_merge takes message (one line)" + add_skill(work / rax.LIBRARY_DIR, "grasp-bowl") + commit(work / rax.LIBRARY_DIR, "grasp-bowl") + result = rpc("tools/call", {"name": "skill_library_merge", "arguments": {"message": "grasp-bowl: draft"}})["result"] + value = json.loads(result["content"][0]["text"]) + assert "isError" not in result and value["merged"] and value["skills"] == ["grasp-bowl"] + assert L.git("rev-parse", "main", cwd=repository).strip() == value["library_main"] + assert rpc("tools/call", {"name": "libero_step", "arguments": {}})["error"]["code"] == -32000 + assert rpc("resources/list")["error"]["code"] == -32000 + _session_record(work, {"name": name}) # a session without the adapter has no library + result = rpc("tools/call", {"name": "skill_library_merge", "arguments": {"message": "m"}})["result"] + assert result["isError"] and "no skill library" in result["content"][0]["text"] + + +def test_the_merge_tool_serves_on_stdio_as_the_sessions_mcp_configuration_starts_it(tmp_path): + """The server entry `prepare` writes (the framework's Python, the module, the workspace, PYTHONPATH of this + package) starts and answers line by line, a parse error included.""" + work = tmp_path / "run" / "work" + work.mkdir(parents=True) + _session_record(work, {"name": "s1"}) + entry = A.servers(tmp_path / "rax", work, True)[A.LIBRARY_SERVER] + lines = [{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}, + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}] + stdin = "".join(json.dumps(x) + "\n" for x in lines) + "not json\n" + done = subprocess.run([entry["command"], *entry["args"]], input=stdin, capture_output=True, text=True, timeout=60, + cwd=tmp_path, env={"PATH": os.environ["PATH"], **entry["env"]}) + replies = [json.loads(line) for line in done.stdout.splitlines()] + assert done.returncode == 0, done.stderr + assert [r.get("id") for r in replies] == [1, 2, None] and replies[2]["error"]["code"] == -32700 + assert replies[1]["result"]["tools"][0]["name"] == "skill_library_merge" + + +# ---------- the Stop hook ---------- + +class Robot: + """The session's robot socket as RAX's frontend serves `status` on it (newline-delimited JSON-RPC).""" + + def __init__(self, path: Path, status: dict): + self.status, self.path = status, path + self.server = socket.socket(socket.AF_UNIX) + self.server.bind(str(path)) + self.server.listen() + threading.Thread(target=self._serve, daemon=True).start() + + def _serve(self): + while True: + try: + conn, _ = self.server.accept() + except OSError: + return + with conn, conn.makefile("r") as reader, conn.makefile("w") as writer: + for line in reader: + request = json.loads(line) + result = ({"content": [{"type": "text", "text": json.dumps(self.status)}]} + if request["method"] == "tools/call" else {"protocolVersion": "2025-06-18"}) + writer.write(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}) + "\n") + writer.flush() + + def close(self): + self.server.close() + + +def test_the_stop_hook_continues_an_open_exploration_at_most_three_times(tmp_path): + """While RAX's status names no next step, the turn's end is blocked with RAX's continue prompt, at most three + times (RAX's MAX_RELAUNCHES); once exploration is closed, or with no robot to ask, the turn ends.""" + work = tmp_path / "run" / "work" + work.mkdir(parents=True) + (tmp_path / "run" / "rax").mkdir() + path = tmp_path / "r.sock" + robot = Robot(path, {"exploration_remaining": 4}) + + def hook(): + done = subprocess.run([sys.executable, "-I", str(METHOD / "stop_hook.py")], input='{"hook_event_name":"Stop"}', + capture_output=True, text=True, cwd=work, timeout=60, + env={**os.environ, "RAX_MCP_SOCKET": str(path)}) + assert done.returncode == 0, done.stderr + return json.loads(done.stdout) if done.stdout.strip() else None + + try: + for n in (1, 2, 3): + assert hook() == {"decision": "block", "reason": H.CONTINUE_PROMPT} + assert (tmp_path / "run" / "rax" / "relaunches").read_text().strip() == str(n) + assert hook() is None + (tmp_path / "run" / "rax" / "relaunches").write_text("0\n") + robot.status = {"next_step": "Exploration is closed: end your turn."} + assert hook() is None + finally: + robot.close() + path.unlink() + assert hook() is None # no robot: the turn ends + assert "Your previous turn ended while exploration is still open" in H.CONTINUE_PROMPT + + +# ---------- the session's task functions ---------- + +def test_the_prompt_is_raxs_start_prompt_in_code_mode(tmp_path, rax_root): + """Agent formal off: its block is left out, as RAX's renderer drops a false block; any other template construct is + refused rather than passed on.""" + assert A.prompt({"id": TASK}, {"rax_root": str(rax_root)}) == CODE_MODE + path = tmp_path / "START_PROMPT.md" + path.write_text(START_PROMPT + "Your task is {{ task }}.\n") + with pytest.raises(ValueError, match="does not render"): + A.start_prompt(path) + with pytest.raises(ValueError, match="rax_root"): + A.rax_root({}) + + +def _tar(files: dict[str, bytes], *, link: str | None = None, mode: int = 0o644) -> str: + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:") as archive: + for name, data in files.items(): + info = tarfile.TarInfo(name) + info.size, info.mode = len(data), (0o755 if name.endswith(".sh") else mode) + archive.addfile(info, io.BytesIO(data)) + if link: + info = tarfile.TarInfo(link) + info.type, info.linkname = tarfile.SYMTYPE, "/etc/passwd" + archive.addfile(info) + return base64.b64encode(buffer.getvalue()).decode() + + +def test_the_subagent_tools_are_denied_only_when_the_sessions_cap_is_zero(tmp_path): + """RAX's agent_command: a cap of 0 (one environment, no subagents) removes Agent and Task; two environments keep + them (one subagent each). The rest of RAX's deny list holds either way.""" + two, none = A.permissions(tmp_path, 2)["deny"], A.permissions(tmp_path, 0)["deny"] + assert "Agent" not in two and {"Agent", "Task"} <= set(none) and set(two) < set(none) + assert {"WebFetch", "WebSearch", f"Edit(/{tmp_path}/.mcp.json)", f"Edit(/{tmp_path}/.claude)"} <= set(two) + + +def test_raxs_workspace_is_written_inside_the_workspace_only(tmp_path): + """Regular files and directories inside the workspace, modes kept; RAX's AGENTS.md before one the deployment + wrote; a link or a path out of the workspace is refused.""" + work = tmp_path / "work" + work.mkdir() + (work / "AGENTS.md").write_text("the deployment's\n") + names = A._extract(_tar({"AGENTS.md": b"RAX's\n", "bin/run.sh": b"#!/bin/sh\n", "TASK.md": b"t"}), work) + assert sorted(names) == ["AGENTS.md", "TASK.md", "bin/run.sh"] + assert (work / "AGENTS.md").read_text() == "RAX's\n\nthe deployment's\n" + assert os.stat(work / "bin" / "run.sh").st_mode & stat.S_IXUSR and not os.stat(work / "TASK.md").st_mode & 0o111 + with pytest.raises(ValueError, match="not a file or directory inside"): + A._extract(_tar({"../escape.md": b"x"}), work) + with pytest.raises(ValueError, match="not a file or directory inside"): + A._extract(_tar({}, link="passwd"), work) + assert not (tmp_path / "escape.md").exists() and not (work / "passwd").exists() + + +@pytest.fixture +def rax_root(tmp_path): + """The files of RAX's checkout the task functions read: its start prompt, its bridge, its agent Python.""" + root = tmp_path / "rax" + (root / "auto_research_agent").mkdir(parents=True) + (root / "auto_research_agent" / "START_PROMPT.md").write_text(START_PROMPT) + (root / "harness").mkdir() + (root / "harness" / "mcp_bridge.py").write_text("# RAX's bridge to the robot socket (not run here)\n") + (root / "runtime" / "envs" / "host" / "bin").mkdir(parents=True) + (root / "runtime" / "envs" / "host" / "bin" / "python").symlink_to(sys.executable) + return root + + +@pytest.fixture +def socket_dir(tmp_path, monkeypatch): + """The session's socket directory, here instead of the task sandbox's own /tmp.""" + path = tmp_path / "sandbox-tmp" / "rax" + monkeypatch.setattr(A, "SOCKET_DIR", path) + monkeypatch.setattr(A, "SOCKET", path / "robot.sock") + return path + + +class Frontend: + """RAX's frontend as the service holds one: it writes the session's state when it starts, and is stopped once.""" + + def __init__(self, root: Path, state: dict): + (root / "state.json").write_text(json.dumps(state)) + self.stops = 0 + + def stop(self): + self.stops += 1 + + +@pytest.fixture +def service(tmp_path, rax_root, monkeypatch): + """The example's host service over HTTP with RAX's parts replaced: the operator script, the workspace maker (a + workspace of RAX's files: AGENTS.md, MCP_SESSION.md, TASK.md, the rendered START_PROMPT.md, a skill) and the + frontend (the session's state as it ends: two episodes, one rehearsal, a submitted bundle, $1.50 of Gemini).""" + S_ = _load("rax_service", EXAMPLE / "service.py") + monkeypatch.setattr(sys, "path", [*sys.path]) # the service puts RAX's checkout first + contract = ModuleType("services.mcp_contract") + contract.Contract = SimpleNamespace(from_config=lambda config: SimpleNamespace(subagent_cap=0)) + monkeypatch.setitem(sys.modules, "services", ModuleType("services")) + monkeypatch.setitem(sys.modules, "services.mcp_contract", contract) + for name in ("NO_PROXY", "no_proxy"): + monkeypatch.setenv(name, "127.0.0.1,localhost") + args = SimpleNamespace(rax_root=rax_root, workspaces=[tmp_path / "logs"], state=tmp_path / "state", + socket_links=tmp_path / "s", sim_gpu="0", key_file=None, agent_effort="xhigh", + exploration_envs=2, subagents=0, formal_workers=4, frontend_timeout=5.0, nonce="n") + args.state.mkdir() + rows = {row["id"]: row for group in _load("rax_rows", EXAMPLE / "rows.py").rows().values() for row in group} + svc = S_.Service(args, rows) + svc.made, svc.frontends_started, svc.configured = [], [], [] + svc.state = {"exploration_started": 2, "results": [{"mode": "rehearsal"}, {"mode": "interactive"}], + "submission": {"bundle": "bundle-1", "sha256": "ab"}, "gemini_spend": {"reported": 1_500_000_000}} + + def configure(row): + svc.configured.append(row["id"]) + return tmp_path / "operator-input.json" + + def workspace(_): + root = rax_root / "runtime" / "auto-research" / f"session-{len(svc.made)}" + root.mkdir(parents=True) + (root / "configuration.json").write_text(json.dumps({"exploration_seeds": list(range(100, 120))})) + svc.made.append(root) + files = {"AGENTS.md": b"# RAX's AGENTS.md\n", "MCP_SESSION.md": b"the tools\n", "TASK.md": b"# Task\n", + "START_PROMPT.md": (CODE_MODE + "\n").encode(), ".agents/skills/robot-tools/SKILL.md": b"tools\n"} + return SimpleNamespace(root=root, training=SimpleNamespace(cpus=2)), _tar(files) + + def start(config, workspace_, mine): + frontend = Frontend(config.root, svc.state) + frontend.pid, frontend.workspace, frontend.mine = None, workspace_, mine + svc.frontends_started.append(frontend) + return frontend + + svc._configure, svc._workspace, svc._start_frontend = configure, workspace, start + server = ThreadingHTTPServer(("127.0.0.1", 0), S_.handler(svc)) + threading.Thread(target=server.serve_forever, daemon=True).start() + svc.url = f"http://127.0.0.1:{server.server_address[1]}" + svc.module = S_ + monkeypatch.setenv("RAX_SERVICE_URL", svc.url) + yield svc + server.shutdown() + server.server_close() + svc.stop() + svc.held.close() + + +# The agent: it reads what the session was given, commits a skill in its clone and merges it with skill_library_merge +# through the server its MCP configuration names, as Claude Code starts it, writes its notes and code, and ends. +FAKE_CLAUDE = f'''#!{sys.executable} +import base64, json, os, subprocess, sys +from pathlib import Path +here = Path(__file__).resolve().parent +args = sys.argv[1:] +prompt = sys.stdin.read() +saw = {{"args": args, "prompt": prompt, "claude_md": Path("CLAUDE.md").read_text(), + "settings": json.loads(Path(".claude/settings.json").read_text()), + "skills_link": os.readlink(".claude/skills"), "skills": sorted(p.name for p in Path(".agents/skills").iterdir()), + "run_tree": os.readlink("runtime/autonomous_controller"), + "socket_dir": os.readlink(os.path.dirname( + json.loads(Path(".claude/settings.json").read_text())["env"]["RAX_MCP_SOCKET"]))}} +servers = json.loads(Path(args[args.index("--mcp-config") + 1]).read_text())["mcpServers"] +saw["servers"] = servers +if "skill_library" in servers: + for name, data in json.loads((here / "skill.json").read_text()).items(): + target = Path("skill-library") / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(base64.b64decode(data)) + with open("skill-library/INDEX.md", "a") as f: + f.write("| [grasp-bowl](skills/grasp-bowl/SKILL.md) | draft | Picks up a bowl. | A bowl. |\\n") + subprocess.run(["git", "add", "-A"], cwd="skill-library", check=True) + subprocess.run(["git", "commit", "-q", "-m", "grasp-bowl"], cwd="skill-library", check=True) + server = servers["skill_library"] + calls = [{{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {{}}}}, + {{"jsonrpc": "2.0", "id": 2, "method": "tools/call", + "params": {{"name": "skill_library_merge", "arguments": {{"message": "grasp-bowl: draft"}}}}}}] + done = subprocess.run([server["command"], *server["args"]], capture_output=True, text=True, + input="".join(json.dumps(c) + "\\n" for c in calls), env={{**os.environ, **server["env"]}}) + saw["merge"] = [json.loads(line) for line in done.stdout.splitlines()] + saw["merge_stderr"] = done.stderr[-2000:] +Path("memory").mkdir(exist_ok=True) +Path("memory/PROGRESS.md").write_text("Explored two layouts; submitted.\\n") +Path("code/grasp").mkdir(parents=True, exist_ok=True) +Path("code/grasp/controller.py").write_text("def main(ctx):\\n return None\\n") +os.symlink("/etc/passwd", "memory/elsewhere") +Path("../saw.json").write_text(json.dumps(saw)) +print(json.dumps({{"type": "system", "session_id": "s1"}})) +print(json.dumps({{"type": "result", "result": "Submitted bundle-1.", "num_turns": 3, "total_cost_usd": 0.5, + "usage": {{"input_tokens": 10, "output_tokens": 5, "cache_read_input_tokens": 0}}}})) +''' + + +@pytest.fixture +def claude(tmp_path, monkeypatch): + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + exe = bin_dir / "claude" + exe.write_text(FAKE_CLAUDE) + exe.chmod(0o755) + (bin_dir / "skill.json").write_text(json.dumps({k: base64.b64encode(v).decode() + for k, v in skill_files("grasp-bowl").items()})) + monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ['PATH']}") + return exe + + +def _params(tmp_path, rax_root, rollout: str) -> dict: + """The CLI agent's params as run.yaml gives them, the rollout's workspaces where the framework makes them + (<agent.params.logs>/<role>/<task id>-<hex>/workspaces).""" + actor = "hermit.agent.evolver.methods.rax.actor" + return {"backend": "claude", "web_search": False, "model": "claude-opus-5-5", "rax_root": str(rax_root), + "workspaces": str(tmp_path / "logs" / "acting" / rollout / "workspaces"), + "args": ["--mcp-config", A.CLAUDE_MCP, "--strict-mcp-config"], + **{name: f"{actor}:{name}" for name in ("prompt", "prepare", "answer", "collect")}} + + +def _row(task_id: str) -> dict: + rows = _load("rax_rows", EXAMPLE / "rows.py").rows() + return next(r for group in rows.values() for r in group if r["id"] == task_id) + + +def test_a_rax_session_runs_on_the_frameworks_claude_code_agent_and_its_merges_reach_the_adapter( + tmp_path, rax_root, socket_dir, service, claude, monkeypatch): + """One step, end to end: the framework's Claude Code agent deploys the library, RAX's task functions register the + session at the service and write RAX's workspace and Claude Code's wiring, the agent merges a skill with + skill_library_merge, `collect` ends the session and keeps its merges, notes and code; the rax Evolver takes the + merges into the next adapter with RAX's merge, and the judge scores RAX's formal batch of the ledger's session.""" + from hermit.agent.evolver import loader + from hermit.agent.evolver.base import Access, StepContext, Workspace + from hermit.task import load_pipeline + + adapter = seed(tmp_path) + run = load_pipeline("hermit.agent.acting.workspace:run", EXAMPLE, _params(tmp_path, rax_root, f"{TASK}-0123abcd")) + out = run(_row(TASK), adapter) + work = Path(out.extra["workspace"]) + saw = json.loads((work.parent / "saw.json").read_text()) + + # the session as RAX's Claude Code launcher starts it, with the library + assert saw["prompt"] == CODE_MODE and out.output == {"answer": "Submitted bundle-1.", "fail_reason": ""} + assert saw["args"][saw["args"].index("--mcp-config") + 1] == A.CLAUDE_MCP + assert "WebSearch" in saw["args"][saw["args"].index("--disallowedTools") + 1] + assert saw["claude_md"].startswith("@AGENTS.md\n") and "# The skill library" in saw["claude_md"] + assert (work / "AGENTS.md").read_text() == "# RAX's AGENTS.md\n" + assert saw["skills_link"] == "../.agents/skills" and saw["skills"] == ["continual-learning", "robot-tools"] + assert "LIBERO Franka Panda" in (work / ".agents" / "skills" / "continual-learning" / "SKILL.md").read_text() + env = saw["settings"]["env"] + assert env["RAX_MCP_SOCKET"] == str(socket_dir / "robot.sock") and env["OMP_NUM_THREADS"] == "2" + assert env["PATH"].split(":")[0] == str(A.agent_python(rax_root).parent) and env["PYTHONPATH"] == str(work) + deny = saw["settings"]["permissions"]["deny"] # RAX's: its tools, no subagent at a cap of 0, its settings + assert deny[:4] == ["WebFetch", "WebSearch", "Agent", "Task"] and "--strict-mcp-config" in saw["args"] + assert f"Edit(/{work}/.claude/**)" in deny and f"Edit(/{work}/{A.CLAUDE_MCP})" in deny + hook = saw["settings"]["hooks"]["Stop"][-1]["hooks"][0] + assert hook["command"].endswith("stop_hook.py") and " -I " in hook["command"] + bridge = saw["servers"][A.MCP_SERVER] + assert bridge["command"] == str(A.agent_python(rax_root)) + assert bridge["args"] == ["-I", str(rax_root / "harness" / "mcp_bridge.py"), str(socket_dir / "robot.sock")] + assert sorted(saw["servers"]) == [A.MCP_SERVER, A.LIBRARY_SERVER], saw.get("merge_stderr") + merged = json.loads(saw["merge"][1]["result"]["content"][0]["text"]) + assert merged["merged"] and merged["skills"] == ["grasp-bowl"], saw["merge"] + assert saw["run_tree"] == str(work.parent / "rax" / "published") # links out of the workspace, removed after + assert saw["socket_dir"] == str(work.parent / "rax" / "sock") == os.readlink(socket_dir) + assert not (work / "runtime" / "autonomous_controller").is_symlink() # links out: removed after the run + + # collect: the service's facts, the library's merges and the notes in the log + facts = out.extra["task"] + assert {k: facts[k] for k in ("workspace", "session", "submitted_bundle", "rehearsals", "exploration_used", + "exploration_budget", "gemini_usd")} == { + "workspace": str(work), "session": "session-0", "submitted_bundle": "bundle-1", "rehearsals": 1, + "exploration_used": 2, "exploration_budget": 20, "gemini_usd": 1.5} + assert facts["library"]["bundle"] == L.BUNDLE and facts["library"]["head"] == merged["library_main"] + assert facts["notes"] == {"files": 2, "bytes": facts["notes"]["bytes"]} + assert (out.log / "session" / "memory" / "PROGRESS.md").is_file() + assert not (out.log / "session" / "memory" / "elsewhere").exists() + assert json.loads((out.log / L.RECORD).read_text())["name"] == work.parent.name + assert service.configured == [TASK] and service.frontends_started[0].stops == 1 + ledger = json.loads((tmp_path / "state" / "ledger.json").read_text()) + assert ledger[str(work)]["finished"] and ledger[str(work)]["rollout"] == str(tmp_path / "logs" / "acting" / + f"{TASK}-0123abcd") + + # the Evolver: the step's learning material as the Trainer writes it, the merge program run by the Evolver + material = tmp_path / "material" + step = material / "step_0001" + (step / "tasks").mkdir(parents=True) + shutil.copytree(out.log, step / "trajectories" / _safe(TASK), symlinks=True) + (step / "tasks" / f"{_safe(TASK)}.json").write_text(json.dumps({"id": TASK, + "trajectory": f"trajectories/{_safe(TASK)}"})) + (step / "summary.json").write_text(json.dumps({"tasks": [TASK]})) + (material / "current").symlink_to("step_0001") + nxt = seed(tmp_path, "next") + places = {k: tmp_path / "ws" / k for k in ("task_info", "history", "state", "scratch", "output")} + for place in places.values(): + place.mkdir(parents=True) + evolver, params = loader.instantiate(loader.find("rax"), {"env": {"PYTHONPATH": str(ROOT)}}) + ctx = StepContext(workspace=Workspace(adapter=nxt, learning_material=material, **places), access=Access(), + tools={}, params=params) + result = evolver.step(ctx) + assert result.status == "done" and "took in 1 of 1" in result.summary, result + assert result.extra["sessions"][0]["merged"] and result.extra["sessions"][0]["skills"] == ["grasp-bowl"] + assert (nxt / "skills" / "grasp-bowl" / "SKILL.md").read_bytes() == skill_files("grasp-bowl")[ + "skills/grasp-bowl/SKILL.md"] + assert spec(nxt)["passed"] + + # the judge: RAX's formal batch of the session the ledger names for the run's workspace + J = _load("rax_judge", EXAMPLE / "judge.py") + monkeypatch.setenv("RAX_STATE", str(tmp_path / "state")) + played = [] + monkeypatch.setattr(J, "_formal", lambda root: played.append(root) or {"status": "completed", "success_count": 40, + "episode_count": 43}) + scored = J.score(_row(TASK), out) + assert scored["score"] == pytest.approx(40 / 43) + assert scored["feedback"] == "40/43 on official LIBERO init states 0-42" + assert played == [str(service.made[0])] and scored["gemini_usd"] == 1.5 + + +def test_a_session_without_the_adapter_is_raxs_as_published(tmp_path, rax_root, socket_dir, service, claude): + """`--adapter none`: no library, no clone, no continual-learning skill, no merge tool; the robot's server alone.""" + from hermit.task import load_pipeline + + run = load_pipeline("hermit.agent.acting.workspace:run", EXAMPLE, _params(tmp_path, rax_root, f"{TASK}-4567cdef")) + out = run(_row(TASK), None) + work = Path(out.extra["workspace"]) + saw = json.loads((work.parent / "saw.json").read_text()) + assert sorted(saw["servers"]) == [A.MCP_SERVER] and saw["skills"] == ["robot-tools"] + assert saw["claude_md"] == "@AGENTS.md\n" and not (work / rax.LIBRARY_DIR).exists() + assert "library" not in out.extra["task"] and out.extra["task"]["submitted_bundle"] == "bundle-1" + assert not (out.log / L.RECORD).exists() + + +def test_prepare_refuses_another_agent_a_foreign_socket_directory_and_ends_a_session_it_cannot_wire( + tmp_path, rax_root, socket_dir, service): + """Claude Code only. A /tmp/rax that is not a link of this sandbox is never removed: the call is refused before it + registers. A session registered and then not wired (RAX's workspace renders another prompt) is ended at once.""" + rollout = tmp_path / "logs" / "acting" / f"{TASK}-89abcdef" / "workspaces" / f"{TASK}-01234567" + work = rollout / "work" + work.mkdir(parents=True) + params = {"backend": "claude", "rax_root": str(rax_root)} + with pytest.raises(ValueError, match="Claude Code"): + A.prepare({"id": TASK}, work, {**params, "backend": "codex"}) + socket_dir.mkdir(parents=True) + (socket_dir / "keep").write_text("someone's") + with pytest.raises(RuntimeError, match="not this session's link"): + A.prepare({"id": TASK}, work, params) + assert (socket_dir / "keep").read_text() == "someone's" and service.configured == [] + shutil.rmtree(socket_dir) + (rax_root / "auto_research_agent" / "START_PROMPT.md").write_text("Another prompt.\n") + with pytest.raises(RuntimeError, match="re-pin RAX"): + A.prepare({"id": TASK}, work, params) + ledger = json.loads((tmp_path / "state" / "ledger.json").read_text()) + assert ledger[str(work.resolve())]["finished"] and service.frontends_started[0].stops == 1 + + +def test_collect_keeps_the_session_when_the_service_cannot_end_it(tmp_path, monkeypatch): + """The service gone: the facts say so, and the library's merges and the notes are still kept.""" + adapter = seed(tmp_path) + repository, work, base = session(tmp_path, adapter, "s1") + _session_record(work, {"name": "s1", "repository": str(repository), "base": base}) + (work / "memory").mkdir() + (work / "memory" / "PROGRESS.md").write_text("notes\n") + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] # a port nothing listens on + monkeypatch.setenv("RAX_SERVICE_URL", f"http://127.0.0.1:{port}") + for name in ("NO_PROXY", "no_proxy"): + monkeypatch.setenv(name, "127.0.0.1,localhost") + log = tmp_path / "log" + log.mkdir() + facts = A.collect({"id": TASK}, work, log, {}) + assert "finish_error" in facts and facts["session"] is None and facts["notes"]["files"] == 1 + assert facts["library"] == {"base": base, "head": base, "bundle": None, "error": None} + + +# ---------- the Evolver ---------- + +def test_the_evolver_takes_in_the_steps_sessions_in_order_and_says_why_it_left_one_out(tmp_path, monkeypatch): + """Two sessions of one step from the same library: the first is merged, the second's index row conflicts with it + (RAX's merge aborts and names INDEX.md); a session that started from another library, one that merged nothing and + one without the library are left out, each with its reason; the adapter is the merged main.""" + adapter = seed(tmp_path) + material = tmp_path / "material" + step = material / "step_0003" + (step / "tasks").mkdir(parents=True) + ids = ["train-libero_spatial_0", "train-libero_spatial_1", "train-libero_spatial_2", "train-libero_spatial_3", + "train-libero_spatial_4"] + + def logged(task_id: str, record: dict | None, bundle: Path | None = None) -> None: + log = step / "trajectories" / _safe(task_id) + log.mkdir(parents=True) + if record is not None: + (log / L.RECORD).write_text(json.dumps(record)) + if bundle is not None: + shutil.copyfile(bundle, log / L.BUNDLE) + trajectory = f"trajectories/{_safe(task_id)}" + (step / "tasks" / f"{_safe(task_id)}.json").write_text(json.dumps({"id": task_id, "trajectory": trajectory})) + + for n, slug in ((0, "grasp-bowl"), (1, "place-plate")): + repository, work, base = session(tmp_path, adapter, f"s{n}", run=f"run{n}") + add_skill(work / rax.LIBRARY_DIR, slug) + commit(work / rax.LIBRARY_DIR, slug) + assert L.merge(repository, f"s{n}", work, slug)["merged"] + record = {**L.export(repository, base, tmp_path / f"out{n}"), "name": f"s{n}"} + logged(ids[n], record, tmp_path / f"out{n}" / L.BUNDLE) + logged(ids[2], {"base": "e" * 40, "head": "f" * 40, "bundle": L.BUNDLE, "name": "s2"}) + logged(ids[3], {"base": base, "head": base, "bundle": None, "name": "s3"}) + logged(ids[4], None) + (step / "summary.json").write_text(json.dumps({"tasks": ids})) + (material / "current").symlink_to("step_0003") + places = {k: tmp_path / "ws" / k for k in ("scratch", "output")} + context = tmp_path / "context.json" + context.write_text(json.dumps({"workspace": {"adapter": str(adapter), "learning_material": str(material), + **{k: str(v) for k, v in places.items()}}})) + monkeypatch.setenv("HA_CONTEXT", str(context)) + assert M.main() == 0 + result = json.loads((places["output"] / "step_result.json").read_text()) + sessions = result["extra"]["sessions"] + assert [s["task"] for s in sessions] == ids and result["status"] == "done" + assert sessions[0]["merged"] and sessions[0]["skills"] == ["grasp-bowl"] + assert sessions[1]["merged"] is False and sessions[1]["conflicts"] == ["INDEX.md"] + assert "started from library" in sessions[2]["reason"] and "merged nothing" in sessions[3]["reason"] + assert "no library record" in sessions[4]["reason"] + assert result["summary"] == "took in 1 of 5 sessions' merges: grasp-bowl" + assert (adapter / "skills" / "grasp-bowl").is_dir() and not (adapter / "skills" / "place-plate").exists() + assert spec(adapter)["passed"] + assert M.main() == 0 # a step run again rebuilds its library: the same result + assert json.loads((places["output"] / "step_result.json").read_text())["summary"].startswith("no change") + + +def test_the_evolver_reads_no_log_outside_the_step(tmp_path, monkeypatch): + """A record whose trajectory leaves the step, or has none, is not read.""" + step = tmp_path / "current" + (step / "tasks").mkdir(parents=True) + (tmp_path / "outside").mkdir() + assert M.take_in(step, tmp_path / "r", "b", "t", {"trajectory": "../outside"})["reason"] == "no log of the run" + assert M.take_in(step, tmp_path / "r", "b", "t", {"trajectory": None})["reason"] == "no log of the run" + (step / "summary.json").write_text("not json") + (step / "tasks" / "x.json").write_text(json.dumps({"id": "x"})) + assert [t for t, _ in M.tasks(step)] == ["x"] + + +# ---------- the LIBERO example ---------- + +def test_the_splits_explore_disjoint_layouts_and_score_on_states_no_session_plays(): + """Train, validation and test explore disjoint fresh layouts of collection 0; train and validation are scored on + disjoint official init states; test on LIBERO-Pro's swap states (another collection); every formal collection + differs from the exploration's, as RAX requires of a held-out formal layout.""" + R = _load("rax_rows", EXAMPLE / "rows.py") + rows = R.rows() + assert len(R.TASKS) == 40 and len(set(R.TASKS)) == 40 + layouts = {} + for split, group in rows.items(): + assert [r["id"] for r in group] == ([f"{split}-{t}" for t in R.TASKS] if not split.startswith("smoke") + else [f"{split}-libero_spatial_0"]) + assert {r["exploration_collection"] for r in group} == {0} + assert all(r["formal_collection"] != r["exploration_collection"] for r in group) + row = group[0] + layouts[split] = set(range(row["exploration_start"], row["exploration_start"] + row["episodes"])) + assert all(r["episodes"] == (2 if split.startswith("smoke") else 20) for r in group) + explored = ("train", "val", "test", "smoke", "smoke_test") + assert set(rows) == {*explored, "official"} + for a in explored: + for b in explored: + assert a == b or not layouts[a] & layouts[b], (a, b) + assert layouts["official"] == layouts["test"] # RAX's own layouts, for its own protocol + states = {s: (g[0]["formal_collection"], set(range(g[0]["formal_first"], g[0]["formal_first"] + + g[0]["formal_episodes"]))) for s, g in rows.items()} + assert states["train"] == (1, set(range(0, 43))) and states["val"] == (1, set(range(43, 50))) + assert states["test"] == (2, set(range(50))) and states["official"] == (1, set(range(50))) + assert "swap" in rows["test"][0]["score_label"] and "43-49" in rows["val"][0]["score_label"] + + +def test_the_rows_are_written_as_task_directories_and_read_back_whole(tmp_path, monkeypatch): + """rows.py writes Harbor-format task directories with no network and no agent clock of their own, and the + configs' view gives each back as its row.""" + from hermit.task.directory import tasks_of + R = _load("rax_rows", EXAMPLE / "rows.py") + monkeypatch.setattr(sys, "argv", ["rows.py", "--out", str(tmp_path)]) + monkeypatch.setattr(sys, "path", [*sys.path]) + R.main() + assert sorted(p.name for p in (tmp_path / "splits").iterdir()) == [ + "official.txt", "smoke.txt", "smoke_test.txt", "test.txt", "train.txt", "val.txt"] + tasks = tasks_of(tmp_path / "tasks", view=R.task_row) + assert len(tasks) == 4 * 40 + 2 + row = tasks["val-libero_10_9"].public + assert row == {"id": "val-libero_10_9", **{k: v for k, v in _row("val-libero_10_9").items() if k != "id"}} + assert tasks["val-libero_10_9"].private["needs"]["network"] == {"agent": "no-network", "verifier": "no-network"} + assert tasks["val-libero_10_9"].private["needs"]["agent_timeout_sec"] is None + instruction = (tmp_path / "tasks" / "test-libero_goal_3" / "instruction.md").read_text() + assert "layouts 0-19" in instruction and "LIBERO-Pro swap" in instruction + + +def _registration(tmp_path, rollout: str, inner: str, *, made: bool = True) -> Path: + """A rollout's workspace where the framework makes it, with the run directory `prepare` makes beside it.""" + work = tmp_path / "logs" / "acting" / rollout / "workspaces" / inner / "work" + work.mkdir(parents=True, exist_ok=True) + for part in ("published/runs", "published/episode_reviews", "sock") if made else (): + (work.parent / "rax" / part).mkdir(parents=True, exist_ok=True) + return work + + +def test_the_service_registers_only_a_rollouts_own_workspace_and_one_session_a_rollout(tmp_path, service): + """The workspace must be the one the framework makes for a rollout of that task, with no link on its path and the + run directory `prepare` makes; a rollout has one session; a registration again (the framework's retry of a session + the model never served) starts afresh only while its session has spent nothing.""" + service.state = {} # a session that has spent nothing yet + work = _registration(tmp_path, f"{TASK}-0a0a0a0a", f"{TASK}-1b1b1b1b") + first = service.register({"workspace": str(work), "task": TASK}) + assert first["ok"] and (first["session"], first["cpus"], first["subagents"]) == ("session-0", 2, 0) + again = service.register({"workspace": str(work), "task": TASK}) + assert again["session"] == "session-1" and service.frontends_started[0].stops == 1 + entry = json.loads((tmp_path / "state" / "ledger.json").read_text())[str(work)] + assert entry["superseded"] == [str(service.made[0])] and entry["session"] == "session-1" + (service.made[1] / "state.json").write_text(json.dumps({"exploration_started": 1})) + with pytest.raises(ValueError, match="never started again"): + service.register({"workspace": str(work), "task": TASK}) + (service.made[1] / "state.json").write_text("{}") + (service.made[1] / "exploration").mkdir() + (service.made[1] / "exploration" / "state.json").write_text(json.dumps({"episodes": {"0": {}}})) + with pytest.raises(ValueError, match="never started again"): # an episode charged in the parallel pool + service.register({"workspace": str(work), "task": TASK}) + sibling = _registration(tmp_path, f"{TASK}-0a0a0a0a", f"{TASK}-2c2c2c2c") + with pytest.raises(ValueError, match="has a RAX session already"): + service.register({"workspace": str(sibling), "task": TASK}) + with pytest.raises(ValueError, match="is not the workspace of a rollout"): + service.register({"workspace": str(work), "task": "train-libero_spatial_1"}) + with pytest.raises(ValueError, match="no task"): + service.register({"workspace": str(work), "task": "train-nothing"}) + shallow = tmp_path / "logs" / "acting" / f"{TASK}-3d3d3d3d" / "work" + shallow.mkdir(parents=True) + with pytest.raises(ValueError, match="is not the workspace of a rollout"): + service.register({"workspace": str(shallow), "task": TASK}) + real = _registration(tmp_path, f"{TASK}-4e4e4e4e", f"{TASK}-5f5f5f5f") + (tmp_path / "logs" / "acting" / f"{TASK}-6a6a6a6a").symlink_to(real.parents[2], target_is_directory=True) + linked = tmp_path / "logs" / "acting" / f"{TASK}-6a6a6a6a" / "workspaces" / f"{TASK}-5f5f5f5f" / "work" + with pytest.raises(ValueError, match="no link on its path"): + service.register({"workspace": str(linked), "task": TASK}) + bare = _registration(tmp_path, f"{TASK}-7b7b7b7b", f"{TASK}-8c8c8c8c", made=False) + with pytest.raises(ValueError, match="must be a directory the task's prepare made"): + service.register({"workspace": str(bare), "task": TASK}) + assert service.finish({"workspace": str(tmp_path / "nowhere")}) == {"ok": False, "error": + "no session registered for this workspace"} + service.made[1].joinpath("state.json").write_text(json.dumps({"gemini_spend": {"reported": 2_000_000}, + "submission": {"bundle": "b2", "sha256": "c"}})) + facts = service.finish({"workspace": str(work)}) + assert facts["ok"] and facts["submitted_bundle"] == "b2" and facts["gemini_usd"] == 0.002 + assert service.frontends_started[1].stops == 1 + service.finish({"workspace": str(work)}) # ended once: its frontend is not stopped again + assert service.frontends_started[1].stops == 1 + + +def test_a_service_started_again_ends_what_the_last_one_left_open_and_two_never_share_a_state(tmp_path, service): + """The ledger's unfinished sessions of a service that was killed: a frontend still running (its command line names + the session's configuration) is stopped, a process that is not one is left alone, and each is ended with its facts; + a finished one is not touched. A second service on the same state directory is refused.""" + root = tmp_path / "left" + root.mkdir() + (root / "configuration.json").write_text(json.dumps({"exploration_seeds": [1, 2]})) + (root / "state.json").write_text(json.dumps({"exploration_started": 1, "submission": {"bundle": "b9"}})) + sleep = [sys.executable, "-c", "import time; time.sleep(120)"] + left = subprocess.Popen([*sleep, "services.controller.frontend", "--config", str(root / "configuration.json")]) + other = subprocess.Popen([*sleep, "--config", str(root / "configuration.json")]) + try: + ledger = {"/w/left": {"task": TASK, "root": str(root), "session": "left", "finished": None, + "frontend_pid": left.pid}, + "/w/other": {"task": TASK, "root": str(root), "session": "other", "finished": None, + "frontend_pid": other.pid}, + "/w/done": {"task": TASK, "root": str(root), "session": "done", "finished": 5.0, + "frontend_pid": other.pid}} + state = tmp_path / "state2" + state.mkdir() + (state / "ledger.json").write_text(json.dumps(ledger)) + args = SimpleNamespace(**{**vars(service.args), "state": state}) + again = service.module.Service(args, service.rows) + assert left.wait(30) == -15 and other.poll() is None + data = json.loads((state / "ledger.json").read_text()) + assert data["/w/left"]["abandoned"] and data["/w/left"]["finished"] + assert (data["/w/left"]["submitted_bundle"], data["/w/left"]["exploration_budget"]) == ("b9", 2) + assert data["/w/other"]["abandoned"] and data["/w/done"] == ledger["/w/done"] + with pytest.raises(RuntimeError, match="another RAX service uses"): + service.module.Service(args, service.rows) + again.held.close() + finally: + left.kill() + other.kill() + left.wait() + other.wait() + + +def test_the_services_routes_refuse_with_their_reason_and_its_health_names_its_launch(service): + """A refusal is a reply (ok false, the error), not the service's end; /health carries the launch's nonce.""" + import urllib.request + request = urllib.request.Request(service.url + "/register", data=json.dumps({"task": "x"}).encode(), + method="POST", headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=30) as response: + reply = json.loads(response.read()) + assert reply == {"ok": False, "error": "ValueError: no task 'x' in this service's tasks"} + with urllib.request.urlopen(service.url + "/health", timeout=30) as response: + assert json.loads(response.read()) == {"ok": True, "nonce": "n"} + + + +def test_a_session_has_spent_something_once_any_of_raxs_records_says_so(tmp_path): + """An episode started, one charged in the parallel pool, a bundle, a result or a submission: no second session.""" + S_ = _load("rax_service", EXAMPLE / "service.py") + root = tmp_path / "session" + (root / "exploration").mkdir(parents=True) + assert S_.spent(root) is False and S_.spent(tmp_path / "nowhere") is False + (root / "state.json").write_text(json.dumps({"exploration_started": 0, "bundles": {}, "results": []})) + assert S_.spent(root) is False + for state in ({"exploration_started": 1}, {"bundles": {"b": {}}}, {"results": [{}]}, {"submission": {"b": 1}}): + (root / "state.json").write_text(json.dumps(state)) + assert S_.spent(root) is True, state + (root / "state.json").write_text("{}") + (root / "exploration" / "state.json").write_text(json.dumps({"episodes": {"0": {"layout": 100}}})) + assert S_.spent(root) is True + assert S_.gemini_usd({"gemini_spend": {"reported": 1_234_567_891}}) == 1.234568 and S_.gemini_usd({}) == 0.0 + + +def test_the_judge_scores_raxs_formal_batch_and_nothing_without_the_ledgers_session_or_a_bundle(tmp_path, + monkeypatch): + """The score is the formal batch's successes over the row's formal episodes (a single-episode outcome as RAX gives + one); a workspace the ledger does not name for this task, or a session with no bundle, scores 0; a session + `collect` did not end is ended first.""" + J = _load("rax_judge", EXAMPLE / "judge.py") + state = tmp_path / "state" + state.mkdir() + monkeypatch.setenv("RAX_STATE", str(state)) + row = _row("test-libero_goal_3") + output = lambda workspace: SimpleNamespace(extra={"task": {"workspace": workspace}}) + assert J.score(row, output("/w")) == {"score": 0.0, "episodes": 50, "feedback": + "0/50 on LIBERO-Pro swap init states 0-49: no RAX session of this task for " + "the run"} + root = tmp_path / "session" + root.mkdir() + (root / "state.json").write_text(json.dumps({"gemini_spend": {"reported": 250_000_000}})) + ledger = {"/w": {"task": row["id"], "root": str(root), "finished": 1.0, "submitted_bundle": "b"}, + "/v": {"task": "val-libero_goal_3", "root": str(root), "finished": 1.0, "submitted_bundle": "b"}, + "/n": {"task": row["id"], "root": str(root), "finished": 1.0, "submitted_bundle": None}, + "/u": {"task": row["id"], "root": str(root), "finished": None}} + (state / "ledger.json").write_text(json.dumps(ledger)) + monkeypatch.setattr(J, "_formal", lambda root_: {"status": "interrupted", "success_count": 12}) + scored = J.score(row, output("/w")) + assert scored["score"] == 12 / 50 and scored["gemini_usd"] == 0.25 + assert scored["feedback"] == "12/50 on LIBERO-Pro swap init states 0-49; the batch is interrupted" + assert J.score(row, output("/v"))["score"] == 0.0 # another task's session + assert "submitted no bundle" in J.score(row, output("/n"))["feedback"] + ended = [] + + def finish(workspace): + ended.append(workspace) + ledger["/u"].update(finished=2.0, submitted_bundle=None) + (state / "ledger.json").write_text(json.dumps(ledger)) + monkeypatch.setattr(J, "_finish", finish) + assert "submitted no bundle" in J.score(row, output("/u"))["feedback"] and ended == ["/u"] + monkeypatch.setattr(J, "_formal", lambda root_: {"status": "completed", "task_complete": True}) + assert J.score({**row, "formal_episodes": 1}, output("/w"))["score"] == 1.0 + + +def test_the_judge_runs_the_formal_batch_on_raxs_python_without_raxs_session_variables(tmp_path, rax_root, + monkeypatch): + """formal.py on RAX's host Python from RAX's checkout (PYTHONPATH the checkout), as RAX's launcher starts its + services: no RAX_* variable passes; the key file is passed when there is one; the batch's last line is read.""" + J = _load("rax_judge", EXAMPLE / "judge.py") + python = rax_root / "runtime" / "envs" / "host" / "bin" / "python" + python.unlink() + python.write_text('#!/bin/sh\nprintf \'{"status": "completed", "args": "%s", "rax": "%s", "path": "%s", ' + '"cwd": "%s"}\\n\' "$*" "$(env | grep -c \'^RAX_\')" "$PYTHONPATH" "$(pwd)"\n') + python.chmod(0o755) + monkeypatch.setenv("RAX_ROOT", str(rax_root)) + monkeypatch.setenv("RAX_KEY_FILE", str(tmp_path / "key")) + monkeypatch.setenv("RAX_STATE", str(tmp_path)) + outcome = J._formal(str(tmp_path / "session")) + assert outcome["args"] == f"{EXAMPLE / 'formal.py'} --root {tmp_path / 'session'} --key-file {tmp_path / 'key'}" + assert outcome["rax"] == "0" and outcome["path"] == str(rax_root) and outcome["cwd"] == str(rax_root) + py_compile.compile(str(EXAMPLE / "formal.py"), cfile=str(tmp_path / "formal.pyc"), doraise=True) + + +def test_the_configs_run_raxs_session_on_claude_code_in_the_task_sandbox_with_their_splits(tmp_path, rax_root, + monkeypatch): + """Every config: RAX's task functions on the Claude Code agent, one session at a time, RAX's session variables, + no web tools, the task sandbox required and shown only RAX's agent Python, bridge and start prompt, the judge on + the host, the rax template and Evolver; training on the train split, and each evaluation on its own split.""" + from hermit.agent.acting import workspace as cli + from hermit.config import Config + monkeypatch.setenv("RAX_ROOT", str(rax_root)) + monkeypatch.setenv("RAX_SERVICE_URL", "http://127.0.0.1:8130") + configs = {p.name: Config.load(p, []) for p in sorted(EXAMPLE.glob("*.yaml"))} + assert sorted(configs) == ["eval_official.yaml", "eval_val.yaml", "run.yaml", "smoke.yaml"] + splits = {"run.yaml": ("train", "test"), "eval_val.yaml": ("train", "val"), + "eval_official.yaml": ("train", "official"), "smoke.yaml": ("smoke", "smoke_test")} + run_env = configs["run.yaml"].data["agent"]["params"]["env"] + assert run_env["MCP_TOOL_TIMEOUT"] == "1728300000" and run_env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] == "250000" + for name, config in configs.items(): + d = config.data + data, agent = d["data"], d["agent"] + params = agent["params"] + assert config.path(data["tasks"]) == (EXAMPLE / "tasks").resolve() and data["view"] == "rows.py:task_row" + assert (Path(data["train"]).stem, Path(data["test"]).stem) == splits[name], name + assert data.get("val") is None and data["step_size"] == 1 and data["shuffle"] is False + assert agent["name"] == "claude-code" and agent["concurrency"] == 1 and params["login"] == "claude" + for fn in ("prompt", "prepare", "answer", "collect"): + assert cli._task_function(params[fn], config.base) is getattr(A, fn), (name, fn) + assert params["web_search"] is False and params["args"] == ["--mcp-config", A.CLAUDE_MCP, "--strict-mcp-config"] + assert params["env"] == run_env and params["rax_root"] == "$RAX_ROOT", name + assert d["environment"]["read"] == ["$RAX_ROOT/runtime/envs/host", "$RAX_ROOT/harness/mcp_bridge.py", + "$RAX_ROOT/auto_research_agent/START_PROMPT.md"], name + assert d["environment"]["env"] == ["RAX_SERVICE_URL"] + assert d["sandbox"]["enabled"] is True and d["sandbox"]["enforce"] == "required" + assert config.path(d["judge"]["path"]) == (EXAMPLE / "judge.py").resolve() and d["judge"]["mode"] == "host" + assert d["template"] == "rax" and d["evolver"]["name"] == "rax" + run_params = configs["run.yaml"].data["agent"]["params"] + assert (run_params["model"], run_params["effort"], run_params["timeout_s"]) == ("claude-opus-5-5", "xhigh", 172800) + assert configs["run.yaml"].data["trainer"]["save_freq"]["steps"] == 10 + from hermit.agent.evolver import loader + found = loader.find("rax") + assert found.needs == [] and found.class_path == "evolver.py:RaxEvolver" + + +def test_the_launcher_serves_the_rollouts_it_runs_and_keeps_the_runs_out_of_raxs_checkout(): + """The service serves the workspaces hermit makes (agent.params.logs), the task functions get RAX's checkout + expanded, and the launcher parses.""" + text = (EXAMPLE / "launch.sh").read_text() + assert '--workspaces "$OUT/actor-logs"' in text and '"agent.params.logs=$OUT/actor-logs"' in text + assert '"agent.params.rax_root=$RAX_ROOT"' in text and "lies inside RAX_ROOT" in text + assert subprocess.run(["bash", "-n", str(EXAMPLE / "launch.sh")]).returncode == 0 diff --git a/tests/selection.py b/tests/selection.py index 37f93bde..75224a71 100644 --- a/tests/selection.py +++ b/tests/selection.py @@ -48,6 +48,8 @@ def fnmatch(path: str, pattern: str) -> bool: "examples/*/reharness/*"], "rrsi_adapter": ["hermit/agent/evolver/methods/rrsi_adapter/*", "hermit/adapter/templates/rrsi_adapter/*", "examples/*/rrsi_adapter/*"], + "rax": ["hermit/agent/evolver/methods/rax/*", "hermit/adapter/templates/rax/*", "examples/*/rax/*", + "docs/methods/rax.md"], # its fidelity table names the vendored files the tests pin } # group -> the other groups whose tests read its files (tests/core/test_selection.py finds a method's tests naming # another group's directory) From d8ff7feb12f792b29089297514eb52b878173140 Mon Sep 17 00:00:00 2001 From: iamziyuzhao <iamziyuzhao@gmail.com> Date: Sun, 29 Nov 2026 00:43:10 -0500 Subject: [PATCH 2/7] RAX: a lease ends a session whose worker is gone; a bwrap with --size; CPU rendering; tests through the Trainer - A session `prepare` registered and no `collect` ended (the CLI failed before its session, the call was stopped) kept RAX's frontend and simulators until the launch ended. `prepare` now takes a lease (POST /lease), a connection the worker holds; when it closes before /finish, the service ends the session as abandoned. - RAX's bundle sandbox passes bwrap --size, which RHEL 9's bubblewrap 0.6.3 does not take: every rehearsal and formal episode failed at its start (found by the smoke). launch.sh refuses such a bwrap; RAX_BWRAP names a newer one for RAX's processes only (the service and the judge's formal batch find it first on PATH). - RAX_RENDER=cpu: on a host whose GPUs run other processes' CUDA, NVIDIA's EGL broke under the simulators (the smoke's start_episode failed in LIBERO's depth check). The launcher gives RAX's simulators a Python (LIBERO_PRO_PYTHON, which RAX reads) that renders with Mesa's llvmpipe; egl_device.py finds Mesa's software device. - Tests through the Trainer in real bubblewrap: the training session in the task sandbox, its merge taken in by the merge program in the evolver sandbox, the evaluation of the final library; a CLI that fails before its session; the launcher's bwrap check and CPU rendering; the EGL helper on the host's Mesa. An unused import removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/methods/rax.md | 12 +- examples/libero/rax/README.md | 18 ++ examples/libero/rax/egl_device.py | 23 ++ examples/libero/rax/judge.py | 5 +- examples/libero/rax/launch.sh | 49 ++++- examples/libero/rax/service.py | 37 ++++ hermit/agent/evolver/methods/rax/actor.py | 60 ++++- tests/methods/rax/test_rax.py | 256 +++++++++++++++++++++- 8 files changed, 436 insertions(+), 24 deletions(-) create mode 100644 examples/libero/rax/egl_device.py diff --git a/docs/methods/rax.md b/docs/methods/rax.md index 9b1ca46f..0d4fbb33 100644 --- a/docs/methods/rax.md +++ b/docs/methods/rax.md @@ -144,6 +144,7 @@ URL, default `RAX_SERVICE_URL`) and `bin` (the CLI). The session's settings are | Library | one repository per robot on the host; a session merges into it directly | each session merges into its own repository; the Evolver merges the sessions' merges with the same code | the session runs in the task sandbox; the learner's update is the Evolver's | | Library on LIBERO | the paper's LIBERO results use no library (independent sessions); the library is shown on the real RB-Y1 | the library across LIBERO's forty tasks | the reproduction's question; `--adapter none` is the paper's setting | | Session clock | none | Hermit's cap, 48 h (`claude.timeout_s`) | a run must end | +| Rendering | NVIDIA's EGL on the simulators' GPU | the same; with `RAX_RENDER=cpu`, Mesa's llvmpipe through RAX's own `LIBERO_PRO_PYTHON` (physics unchanged, images differ by renderer noise) | a host whose GPUs run other processes' CUDA, which can break NVIDIA's EGL; a run with it says so | ## Boundaries @@ -157,10 +158,13 @@ the checks hold its format, not that the runs happened. The service trusts a session only with its workspace and task: it registers the one workspace the framework makes for a rollout, once (again only for a retry of a session that spent nothing), so a session cannot start a second session or a fresh budget. A session `prepare` registered but could not set up is ended at once; one whose `collect` cannot reach the -service is ended by the judge. Gemini's calls (RAX's frontend on the host, OpenRouter) are outside Hermit's model layer -and its usage accounting; their cost is in each session's facts and score (`gemini_usd`). The session's Claude Code -calls go through Hermit's Claude Code agent (Model: the Claude login's model; Base Agent: Claude Code; Acting Agent: the -CLI agent with RAX's task functions), with its login plan, timeout and usage. The Evolver calls no model. +service is ended by the judge; and one whose worker ends without `collect` (the CLI failed before its session, the call +was stopped) is ended by the service when the worker's lease closes: a connection `prepare` opens and the worker holds, +which goes with everything in the task sandbox. Gemini's calls (RAX's frontend on the host, OpenRouter) are outside +Hermit's model layer and its usage accounting; their cost is in each session's facts and score (`gemini_usd`). The +session's Claude Code calls go through Hermit's Claude Code agent (Model: the Claude login's model; Base Agent: Claude +Code; Acting Agent: the CLI agent with RAX's task functions), with its login plan, timeout and usage. The Evolver calls +no model. ## Example diff --git a/examples/libero/rax/README.md b/examples/libero/rax/README.md index 05852662..6f499290 100644 --- a/examples/libero/rax/README.md +++ b/examples/libero/rax/README.md @@ -60,6 +60,22 @@ done; done runtime/envs/host/bin/python scripts/libero_pro_doctor.py --gpu 0 --task libero_spatial_0 ``` +RAX runs each rehearsal and formal episode in a fresh bubblewrap sandbox whose `/tmp` it caps with `bwrap --size`. +RHEL 9's bubblewrap (0.6.3) takes no `--size`, and every episode would fail at its start: `launch.sh` refuses such a +bwrap. `RAX_BWRAP` names a newer one for RAX's processes only (the service, its frontends, the judge's formal +batches); hermit's own sandboxes keep the one on `PATH`: + +```bash +conda create -y -p ~/bwrap-env -c conda-forge bubblewrap=0.9.0 # then: export RAX_BWRAP=~/bwrap-env/bin/bwrap +``` + +On a host whose GPUs also run other processes' CUDA work, NVIDIA's EGL can break under the simulators: `start_episode` +then fails in LIBERO's depth check (`get_real_depth_map`'s range assertion) or hangs. `RAX_RENDER=cpu` renders with +Mesa's llvmpipe instead (Mesa's EGL must be installed): `launch.sh` gives RAX a simulator Python (`LIBERO_PRO_PYTHON`, +which RAX's `services/libero_pro/process.py` reads) that selects Mesa's software EGL device (`egl_device.py` finds it) +and no CUDA device, at `nice 10` with two llvmpipe threads. Physics is unchanged; the images differ from NVIDIA's by +renderer noise, so a run with it says so beside its results. + The sessions run on the machine's Claude login ([Claude subscription](../../../docs/guides/claude-subscription.md): `claude setup-token`, then `CLAUDE_CODE_OAUTH_TOKEN`). RAX's Gemini perception tool (`gemini_generate`, which the paper's sessions had) needs an OpenRouter key file (`RAX_KEY_FILE`); without one the sessions run without it. @@ -70,6 +86,8 @@ From this folder: ```bash export RAX_ROOT=/path/to/rax RAX_SIM_GPU=0 RAX_KEY_FILE=~/.codex/secrets/openrouter_api_key +export RAX_BWRAP=~/bwrap-env/bin/bwrap # where the system's bwrap takes no --size (above) +export RAX_RENDER=cpu # where other processes' CUDA shares the GPUs (above) RAX_CONFIG=smoke.yaml ./launch.sh # the smoke ./launch.sh # train: forty sessions, one per step RAX_CONFIG=eval_val.yaml ./launch.sh eval --adapter rax-libero/ckpt-step-20 # validation, per checkpoint diff --git a/examples/libero/rax/egl_device.py b/examples/libero/rax/egl_device.py new file mode 100644 index 00000000..c3691f02 --- /dev/null +++ b/examples/libero/rax/egl_device.py @@ -0,0 +1,23 @@ +"""Prints the index of Mesa's software (llvmpipe) EGL device, for RAX_RENDER=cpu (launch.sh): run on RAX's simulator +Python with Mesa as the only EGL vendor (__EGL_VENDOR_LIBRARY_FILENAMES), MUJOCO_EGL_DEVICE_ID then selects it.""" +import ctypes + +EGL_EXTENSIONS = 0x3055 + +egl = ctypes.CDLL("libEGL.so.1") +egl.eglGetProcAddress.argtypes = [ctypes.c_char_p] +egl.eglGetProcAddress.restype = ctypes.c_void_p +query_devices = ctypes.CFUNCTYPE(ctypes.c_uint, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p), + ctypes.POINTER(ctypes.c_int))(egl.eglGetProcAddress(b"eglQueryDevicesEXT")) +query_string = ctypes.CFUNCTYPE(ctypes.c_char_p, ctypes.c_void_p, ctypes.c_int)( + egl.eglGetProcAddress(b"eglQueryDeviceStringEXT")) +count = ctypes.c_int() +query_devices(0, None, ctypes.byref(count)) +devices = (ctypes.c_void_p * count.value)() +query_devices(count.value, devices, ctypes.byref(count)) +for index in range(count.value): + if b"EGL_MESA_device_software" in (query_string(devices[index], EGL_EXTENSIONS) or b""): + print(index) + break +else: + raise SystemExit("no Mesa software EGL device") diff --git a/examples/libero/rax/judge.py b/examples/libero/rax/judge.py index 82a1d21c..75165631 100644 --- a/examples/libero/rax/judge.py +++ b/examples/libero/rax/judge.py @@ -7,7 +7,8 @@ The session is the one the RAX service's ledger names for the run's workspace (the facts `collect` returned name the workspace; the ledger, outside every sandbox, names the session). Variables (launch.sh exports them): RAX_ROOT (the checkout), RAX_STATE (the service's directory: ledger.json), RAX_SERVICE_URL (to end a session `collect` did not end), -RAX_KEY_FILE (the Gemini router's key, optional), RAX_FORMAL_TIMEOUT_S (default 86400).""" +RAX_KEY_FILE (the Gemini router's key, optional), RAX_BIN (the directory of the bwrap RAX's bundle sandbox runs, +first on the batch's PATH), RAX_FORMAL_TIMEOUT_S (default 86400).""" from __future__ import annotations import json @@ -41,6 +42,8 @@ def _formal(root: str) -> dict: command += ["--key-file", os.environ["RAX_KEY_FILE"]] env = {k: v for k, v in os.environ.items() if not k.startswith("RAX_")} # as RAX's launcher starts its services env["PYTHONPATH"] = str(rax) + if os.environ.get("RAX_BIN"): # the bwrap RAX's bundle sandbox runs (launch.sh: RAX_BWRAP) + env["PATH"] = os.environ["RAX_BIN"] + os.pathsep + env.get("PATH", "") done = subprocess.run(command, cwd=rax, env=env, capture_output=True, text=True, timeout=float(os.environ.get("RAX_FORMAL_TIMEOUT_S", 86400))) if done.returncode: diff --git a/examples/libero/rax/launch.sh b/examples/libero/rax/launch.sh index fb55a259..1f21c383 100755 --- a/examples/libero/rax/launch.sh +++ b/examples/libero/rax/launch.sh @@ -13,8 +13,11 @@ # GPU, an ordinal or UUID: RAX's --sim-gpu), RAX_KEY_FILE (an OpenRouter key file for RAX's Gemini perception tool; # without it the sessions have none), RAX_OUT (the runs, default runs/ beside this folder), RAX_PORT (the service, # default 8130), RAX_CONFIG (default run.yaml), RAX_TREE (the adapter tree under $RAX_OUT/trees: the config's name; -# run for eval_*.yaml), HERMIT_PYTHON (default python). The Claude Code sessions run on the -# machine's Claude login (CLAUDE_CODE_OAUTH_TOKEN, docs/guides/claude-subscription.md). +# run for eval_*.yaml), RAX_BWRAP (the bwrap RAX's processes run bundles in, default the one on PATH: it must take +# --size, which RHEL 9's bubblewrap 0.6.3 does not; README.md), RAX_RENDER (gpu, the default: NVIDIA's EGL on +# RAX_SIM_GPU, as RAX renders; cpu: Mesa's llvmpipe, for a host whose GPUs run other processes' CUDA; README.md), +# HERMIT_PYTHON (default python). The Claude Code sessions run on the machine's Claude login +# (CLAUDE_CODE_OAUTH_TOKEN, docs/guides/claude-subscription.md). # # The launcher writes the task rows and splits (rows.py: tasks/, splits/), starts RAX's host service on RAX's host # Python (service.py: the sessions' frontends, simulators and formal batches; stopped when the run ends) and runs @@ -26,6 +29,13 @@ HERE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" RAX_ROOT="$(cd "$RAX_ROOT" && pwd)" RAX_PYTHON="$RAX_ROOT/runtime/envs/host/bin/python" [[ -x "$RAX_PYTHON" ]] || { echo "$RAX_PYTHON: set RAX up first (README.md: setup_host_env.sh, ...)" >&2; exit 1; } +# RAX's bundle sandbox (services/controller/sandbox.py) caps its /tmp with bwrap's --size: without it every rehearsal +# and formal episode fails at its start, and every session scores 0 +BWRAP="${RAX_BWRAP:-$(command -v bwrap || true)}" +[[ -n "$BWRAP" && -x "$BWRAP" ]] || { echo "no bwrap: RAX runs its bundles in bubblewrap (README.md)" >&2; exit 1; } +"$BWRAP" --ro-bind / / --size 1048576 --tmpfs /tmp true 2>/dev/null || { + echo "$BWRAP ($("$BWRAP" --version 2>&1 | tail -n 1)) takes no --size, which RAX's bundle sandbox passes: set" \ + "RAX_BWRAP to a newer bubblewrap's bwrap (README.md)" >&2; exit 1; } # The RAX commit this example was written against; another one is run, but named. PINNED=1767412c5300b9358059ae6a39740c3c28d2b8b9 ACTUAL="$(git -C "$RAX_ROOT" rev-parse HEAD 2>/dev/null || echo unknown)" @@ -40,7 +50,6 @@ CONFIG="${RAX_CONFIG:-run.yaml}" HERMIT="${HERMIT_PYTHON:-python}" [[ "$HERMIT" != */* || "$HERMIT" == /* ]] || HERMIT="$PWD/$HERMIT" # a relative path: from here, as given cd "$HERE" -"$HERMIT" rows.py --out . # tasks/ and splits/: the rows every config reads OUT="${RAX_OUT:-$HERE/../runs/rax}" mkdir -p "$OUT" @@ -49,10 +58,39 @@ case "$(cd "$OUT" && pwd -P)/" in # RAX's checkout is shown to t "$(cd "$RAX_ROOT" && pwd -P)"/*) echo "RAX_OUT ($OUT) lies inside RAX_ROOT: keep the runs elsewhere" >&2; exit 2 ;; esac +# RAX's processes (the service, its frontends, the judge's formal batches) find that bwrap first; hermit's own +# sandboxes keep the one on PATH +RAX_BIN="$OUT/rax-service/bin" +mkdir -p "$RAX_BIN" +ln -sfn "$(cd "$(dirname "$BWRAP")" && pwd)/$(basename "$BWRAP")" "$RAX_BIN/bwrap" + +# RAX_RENDER=cpu: other processes' CUDA work on a GPU can break NVIDIA's EGL under the simulators there (start_episode +# fails in LIBERO's depth check, or hangs). RAX takes its simulators' Python from LIBERO_PRO_PYTHON +# (services/libero_pro/process.py): this one renders with Mesa's llvmpipe and sees no CUDA device, physics unchanged. +case "${RAX_RENDER:-gpu}" in + gpu) ;; + cpu) + SIM_PYTHON="${LIBERO_PRO_PYTHON:-$RAX_ROOT/runtime/envs/libero_pro/bin/python}" + MESA=/usr/share/glvnd/egl_vendor.d/50_mesa.json + DEVICE="$(__EGL_VENDOR_LIBRARY_FILENAMES="$MESA" "$SIM_PYTHON" -I "$HERE/egl_device.py")" || { + echo "RAX_RENDER=cpu: no Mesa software EGL device for $SIM_PYTHON (Mesa's EGL: $MESA)" >&2; exit 1; } + { echo '#!/bin/bash' + echo "# RAX's simulators on the CPU (launch.sh, RAX_RENDER=cpu): Mesa's software EGL device, no CUDA device" + printf 'export __EGL_VENDOR_LIBRARY_FILENAMES=%q MUJOCO_EGL_DEVICE_ID=%q\n' "$MESA" "$DEVICE" + echo 'export CUDA_VISIBLE_DEVICES=' + echo 'export LP_NUM_THREADS="${LP_NUM_THREADS:-2}"' + printf 'exec nice -n 10 %q "$@"\n' "$SIM_PYTHON"; } > "$RAX_BIN/libero-pro-python" + chmod +x "$RAX_BIN/libero-pro-python" + export LIBERO_PRO_PYTHON="$RAX_BIN/libero-pro-python" ;; + *) echo "RAX_RENDER is gpu or cpu, not ${RAX_RENDER}" >&2; exit 2 ;; +esac + +"$HERMIT" rows.py --out . # tasks/ and splits/: the rows every config reads + # RAX's host service: the sessions' frontends and simulators, on the host, on RAX's host Python PORT="${RAX_PORT:-8130}" NONCE="$$-$RANDOM-$(date +%s%N)" # this launch's service answers /health with it, another run's not -"$RAX_PYTHON" "$HERE/service.py" --port "$PORT" --rax-root "$RAX_ROOT" --tasks "$HERE/tasks" \ +PATH="$RAX_BIN:$PATH" "$RAX_PYTHON" "$HERE/service.py" --port "$PORT" --rax-root "$RAX_ROOT" --tasks "$HERE/tasks" \ --workspaces "$OUT/actor-logs" --state "$OUT/rax-service" --sim-gpu "$RAX_SIM_GPU" --nonce "$NONCE" \ ${RAX_KEY_FILE:+--key-file "$RAX_KEY_FILE"} > "$OUT/rax-service.log" 2>&1 & SERVICE=$! @@ -65,7 +103,8 @@ for _ in $(seq 1 30); do done ours || { echo "the RAX service did not come up on port $PORT: $OUT/rax-service.log" >&2; exit 1; } # The sessions reach the service (environment.env); the judge reads the ledger and runs RAX's formal batches -export RAX_ROOT RAX_SERVICE_URL="http://127.0.0.1:$PORT" RAX_STATE="$OUT/rax-service" RAX_KEY_FILE="${RAX_KEY_FILE:-}" +export RAX_ROOT RAX_SERVICE_URL="http://127.0.0.1:$PORT" RAX_STATE="$OUT/rax-service" RAX_KEY_FILE="${RAX_KEY_FILE:-}" \ + RAX_BIN MODE=train if [[ "${1:-}" == train || "${1:-}" == eval ]]; then MODE="$1"; shift; fi diff --git a/examples/libero/rax/service.py b/examples/libero/rax/service.py index c2417c8e..4a3bd3f0 100644 --- a/examples/libero/rax/service.py +++ b/examples/libero/rax/service.py @@ -19,6 +19,10 @@ mount namespace (bubblewrap): the agent sees that tree and nothing else of the session's directory. A rollout has one session: a workspace registers again (the framework's retry of a session the model never served) only while its session has spent nothing, and then starts afresh. + POST /lease {workspace, session} by the task's `prepare`, once the session is wired: the connection stays + open while the process that runs the session lives (the task sandbox's worker). When it closes + before /finish ended the session (the CLI failed before its session, the call was stopped, and + `collect` never ran), the session is ended (`abandoned` in the ledger). POST /finish {workspace} by the task's `collect` (and the judge): RAX's frontend stopped, as RAX's launcher stops it when the agent ends; the session's state read from its directory. GET /health @@ -345,6 +349,28 @@ def finish(self, body: dict) -> dict: return {"ok": False, "error": "no session registered for this workspace"} return {"ok": True, **self._end(entry, frontend)} + def lease(self, body: dict) -> tuple[str, str]: + """A session's lease (the task's `prepare`, once the session is wired): its key and its session, or a + refusal. The handler holds the connection until it closes (`lease_ended`).""" + key = str(Path(str(body.get("workspace", ""))).resolve()) + session = str(body.get("session") or "") + with self.ledger.lock: + entry = self.ledger.data.get(key) + if entry is None or entry.get("finished") or entry.get("session") != session: + raise ValueError("no open session of this workspace by that name") + return key, session + + def lease_ended(self, key: str, session: str) -> None: + """A lease's connection closed: the process that ran the session is gone. The session, if `collect` did not + end it and the workspace did not register again since, is ended now (`abandoned`).""" + with self.registering: # never while the workspace registers again + with self.ledger.lock: + entry = self.ledger.data.get(key) + if entry is None or entry.get("finished") or entry.get("session") != session: + return + frontend = self.frontends.pop(key, None) + self._end(entry, frontend, abandoned=True) + def stop(self) -> None: """The service's end (launch.sh's trap): every session still open is ended.""" with self.ledger.lock: @@ -373,6 +399,17 @@ def do_GET(self): # the nonce: launch.sh knows def do_POST(self): try: body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + if self.path == "/lease": + held = service.lease(body) + self._reply({"ok": True}) + self.wfile.flush() + try: + while self.rfile.read(1): # nothing comes: it ends with its process + pass + except OSError: + pass + service.lease_ended(*held) + return route = {"/register": service.register, "/finish": service.finish}.get(self.path) self._reply(route(body) if route else {"ok": False, "error": f"no route {self.path}"}) except Exception as exc: # a bad request is the session's error, not the service's end diff --git a/hermit/agent/evolver/methods/rax/actor.py b/hermit/agent/evolver/methods/rax/actor.py index 5e0a4df7..c499ca4a 100644 --- a/hermit/agent/evolver/methods/rax/actor.py +++ b/hermit/agent/evolver/methods/rax/actor.py @@ -16,12 +16,16 @@ (stop_hook.py). With an adapter (the `rax` template), it makes the session's library repository of the adapter's files and RAX's clone of it, skill-library/, adds RAX's continual-learning skill (library.py) and serves RAX's skill_library_merge tool (library_server.py), as RAX's harness does for a workspace with a - library. Without one (`--adapter none`) the session is RAX's on LIBERO as published. + library. Without one (`--adapter none`) the session is RAX's on LIBERO as published. Last, it takes the + session's lease (`_lease`): a connection to the service this process holds while the session runs, so + that a session whose worker ends without `collect` (the CLI failed before its session, the call was + stopped: everything in the task sandbox goes with its worker) is ended by the service. prompt RAX's START_PROMPT.md as its launcher gives it in code mode (`startup_prompt`) answer the agent's last message - collect ends the session at the service (RAX's frontend stopped, as RAX stops it when the agent ends), and - returns the session's facts (the judge scores its submitted bundle with RAX's formal batch); writes what - the session merged into its library (library.export) and the session's notes and code into the log + collect ends the session at the service (RAX's frontend stopped, as RAX stops it when the agent ends) and lets + its lease go, and returns the session's facts (the judge scores its submitted bundle with RAX's formal + batch); writes what the session merged into its library (library.export) and the session's notes and + code into the log RAX's own checkout comes from agent.params.rax_root (its START_PROMPT.md, bridge and agent environment must be declared readable: environment.read). The config gives the Claude Code session RAX's frontend server on the command line @@ -37,8 +41,10 @@ import re import shlex import shutil +import socket import sys import tarfile +import urllib.parse import urllib.request from hermit.agent.evolver.methods.rax import library @@ -56,6 +62,7 @@ PROTECTED = (".claude", ".mcp.json", CLAUDE_MCP) # RAX's protected(): the workspace's files that configure Claude Code NOTE_FILE_BYTES = 1_000_000 NOTE_BYTES = 20_000_000 +LEASES: dict[str, socket.socket] = {} # workspace -> the lease this process holds of its session (`_lease`) def _service(params: dict) -> str: @@ -76,6 +83,43 @@ def _post(url: str, body: dict, timeout: float = 1800.0) -> dict: return reply +def _lease(url: str, workspace: str, session: str, timeout: float = 600.0) -> socket.socket: + """The session's lease: a connection to the service (POST /lease), held open by this process while the session + runs. The service ends the session when the connection closes before /finish did: when this process is gone + (the CLI failed before its session, the call was stopped: everything in the task sandbox goes with its worker). + A Python socket is not inherited by the processes this one starts (the CLI).""" + where = urllib.parse.urlsplit(url) + body = json.dumps({"workspace": workspace, "session": session}).encode() + lease = socket.create_connection((where.hostname or "127.0.0.1", where.port or 80), timeout=timeout) + try: + lease.sendall(b"POST /lease HTTP/1.0\r\nHost: %b\r\nContent-Type: application/json\r\n" + b"Content-Length: %d\r\n\r\n%b" % (where.netloc.encode(), len(body), body)) + received = b"" + while b"\r\n\r\n" not in received and len(received) < 65536: + chunk = lease.recv(4096) + if not chunk: + break + received += chunk + head, _, data = received.partition(b"\r\n\r\n") + length = re.search(rb"(?im)^content-length:\s*(\d+)\s*$", head) + while length and len(data) < int(length.group(1)): + chunk = lease.recv(4096) + if not chunk: + break + data += chunk + try: + reply = json.loads(data[:int(length.group(1))]) if length else {} + except ValueError: + reply = {} + if not reply.get("ok"): + raise RuntimeError(f"RAX service lease: {reply.get('error') or 'no reply'}") + lease.settimeout(None) + return lease + except BaseException: + lease.close() + raise + + def rax_root(params: dict) -> Path: value = params.get("rax_root") if not value: @@ -233,6 +277,7 @@ def prepare(task: dict, work: Path, params: dict) -> list: reply = _post(url + "/register", {"workspace": str(work), "task": task["id"]}) try: _wire(task, work, params, rax, mine, reply) + lease = _lease(url, str(work), str(reply.get("session") or "")) except BaseException: # No session follows (the call fails, and `collect` is not run): RAX's frontend is stopped now try: @@ -240,6 +285,10 @@ def prepare(task: dict, work: Path, params: dict) -> list: except Exception: # noqa: BLE001 - the failure that brought us here wins pass raise + earlier = LEASES.pop(str(work), None) # a retry of the call: its first session's (ended there) + LEASES[str(work)] = lease + if earlier is not None: + earlier.close() return [] @@ -311,6 +360,9 @@ def collect(task: dict, work: Path, log: Path, params: dict) -> dict: reply = _post(_service(params) + "/finish", {"workspace": str(work)}) except Exception as exc: # noqa: BLE001 - the judge ends it from the ledger reply = {"finish_error": f"{type(exc).__name__}: {exc}"[:500]} + lease = LEASES.pop(str(work), None) # after /finish: the session is ended, its lease with it + if lease is not None: + lease.close() facts = {"workspace": str(work), **{k: reply.get(k) for k in ("session", "submitted_bundle", "rehearsals", "exploration_used", "exploration_budget", "gemini_usd")}, diff --git a/tests/methods/rax/test_rax.py b/tests/methods/rax/test_rax.py index 59e63447..487b77e0 100644 --- a/tests/methods/rax/test_rax.py +++ b/tests/methods/rax/test_rax.py @@ -7,9 +7,10 @@ Stand-ins: a scripted `claude` on PATH that acts as the agent (it commits a skill in its clone and calls skill_library_merge through the server the session's MCP configuration names), a RAX checkout of the files the task functions read (its START_PROMPT.md, verbatim), the example's service with RAX's parts replaced (no operator script, -no workspace maker, no frontend, no simulator), a robot socket that answers `status`. No model, no network, no GPU.""" +no workspace maker, no frontend, no simulator), a robot socket that answers `status`, and for the run through the +Trainer RAX's modules formal.py imports (a supervisor whose batch succeeds on one episode). No model, no network, no +GPU. The run through the Trainer uses bubblewrap and skips without it.""" import base64 -import dataclasses import hashlib from http.server import ThreadingHTTPServer import importlib.util @@ -26,10 +27,12 @@ import tarfile import tempfile import threading +import time from types import ModuleType, SimpleNamespace import pytest +from claude_stand import bwrap_works from hermit.agent.evolver.methods.rax import actor as A from hermit.agent.evolver.methods.rax import library as L from hermit.agent.evolver.methods.rax import library_server as S @@ -65,6 +68,22 @@ def tmp_path(): shutil.rmtree(path, ignore_errors=True) +@pytest.fixture(autouse=True) +def _no_lease_left(): + """A lease a test's `prepare` took and no `collect` let go is closed after it, never left to the next test.""" + yield + while A.LEASES: + A.LEASES.popitem()[1].close() + + +def _until(done, seconds: float = 20.0) -> None: + """Poll `done` until it holds, against a deadline.""" + deadline = time.monotonic() + seconds + while not done(): + assert time.monotonic() < deadline, "the condition did not hold in time" + time.sleep(0.02) + + def _load(name: str, path: Path): spec_ = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec_) @@ -523,12 +542,17 @@ def start(config, workspace_, mine): # The agent: it reads what the session was given, commits a skill in its clone and merges it with skill_library_merge -# through the server its MCP configuration names, as Claude Code starts it, writes its notes and code, and ends. +# through the server its MCP configuration names, as Claude Code starts it, writes its notes and code, and ends. The +# skill's files are in the script itself: a task sandbox shows the CLI, not the files beside it. +SKILL_JSON = json.dumps({k: base64.b64encode(v).decode() for k, v in skill_files("grasp-bowl").items()}) FAKE_CLAUDE = f'''#!{sys.executable} import base64, json, os, subprocess, sys from pathlib import Path -here = Path(__file__).resolve().parent +SKILL = {SKILL_JSON!r} args = sys.argv[1:] +if args[:1] == ["--version"]: + print("2.1.332 (Claude Code)") + raise SystemExit(0) prompt = sys.stdin.read() saw = {{"args": args, "prompt": prompt, "claude_md": Path("CLAUDE.md").read_text(), "settings": json.loads(Path(".claude/settings.json").read_text()), @@ -538,8 +562,10 @@ def start(config, workspace_, mine): json.loads(Path(".claude/settings.json").read_text())["env"]["RAX_MCP_SOCKET"]))}} servers = json.loads(Path(args[args.index("--mcp-config") + 1]).read_text())["mcpServers"] saw["servers"] = servers -if "skill_library" in servers: - for name, data in json.loads((here / "skill.json").read_text()).items(): +library = Path("skill-library/skills") +saw["library"] = sorted(p.parent.name for p in library.glob("*/SKILL.md")) if library.is_dir() else None +if "skill_library" in servers and "grasp-bowl" not in saw["library"]: + for name, data in json.loads(SKILL).items(): target = Path("skill-library") / name target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(base64.b64decode(data)) @@ -574,8 +600,6 @@ def claude(tmp_path, monkeypatch): exe = bin_dir / "claude" exe.write_text(FAKE_CLAUDE) exe.chmod(0o755) - (bin_dir / "skill.json").write_text(json.dumps({k: base64.b64encode(v).decode() - for k, v in skill_files("grasp-bowl").items()})) monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ['PATH']}") return exe @@ -960,6 +984,39 @@ def test_a_service_started_again_ends_what_the_last_one_left_open_and_two_never_ other.wait() +def test_a_session_whose_process_ends_without_collect_is_ended_when_its_lease_closes(tmp_path, service): + """The lease `prepare` takes: refused for a name that is not the open session's; a connection that closes while + its session is open (the worker gone, `collect` never run) ends the session as abandoned; one that closes after + its workspace registered again (the call's retry) or after /finish ends nothing.""" + service.state = {} # nothing spent: the call's retry may register again + + def entry(work): + return json.loads((tmp_path / "state" / "ledger.json").read_text())[str(work.resolve())] + work = _registration(tmp_path, f"{TASK}-0a1b2c3d", f"{TASK}-4e5f6a7b") + first = A._post(service.url + "/register", {"workspace": str(work), "task": TASK}) + with pytest.raises(RuntimeError, match="no open session"): + A._lease(service.url, str(work), "another") + lease = A._lease(service.url, str(work), first["session"]) + again = A._post(service.url + "/register", {"workspace": str(work), "task": TASK}) + held = A._lease(service.url, str(work), again["session"]) + lease.close() # the first session's: it ended when the call ran again + time.sleep(0.5) # what must not happen: the wait is what this holds + assert not entry(work)["finished"] and entry(work)["session"] == again["session"] + held.close() # the worker gone: its session ends + _until(lambda: entry(work)["finished"]) + assert entry(work)["abandoned"] and [f.stops for f in service.frontends_started] == [1, 1] + other = _registration(tmp_path, f"{TASK}-1a2b3c4d", f"{TASK}-5e6f7a8b") + reply = A._post(service.url + "/register", {"workspace": str(other), "task": TASK}) + lease = A._lease(service.url, str(other), reply["session"]) + A._post(service.url + "/finish", {"workspace": str(other)}) + lease.close() + time.sleep(0.5) + assert entry(other)["finished"] and "abandoned" not in entry(other) + assert service.frontends_started[2].stops == 1 + with pytest.raises(RuntimeError, match="no open session"): + A._lease(service.url, str(other), reply["session"]) # a finished session takes none + + def test_the_services_routes_refuse_with_their_reason_and_its_health_names_its_launch(service): """A refusal is a reply (ok false, the error), not the service's end; /health carries the launch's nonce.""" import urllib.request @@ -1038,14 +1095,17 @@ def test_the_judge_runs_the_formal_batch_on_raxs_python_without_raxs_session_var python = rax_root / "runtime" / "envs" / "host" / "bin" / "python" python.unlink() python.write_text('#!/bin/sh\nprintf \'{"status": "completed", "args": "%s", "rax": "%s", "path": "%s", ' - '"cwd": "%s"}\\n\' "$*" "$(env | grep -c \'^RAX_\')" "$PYTHONPATH" "$(pwd)"\n') + '"cwd": "%s", "bin": "%s"}\\n\' "$*" "$(env | grep -c \'^RAX_\')" "$PYTHONPATH" "$(pwd)" ' + '"${PATH%%:*}"\n') python.chmod(0o755) monkeypatch.setenv("RAX_ROOT", str(rax_root)) monkeypatch.setenv("RAX_KEY_FILE", str(tmp_path / "key")) monkeypatch.setenv("RAX_STATE", str(tmp_path)) + monkeypatch.setenv("RAX_BIN", str(tmp_path / "bin")) # the launcher's bwrap for RAX's bundle sandbox outcome = J._formal(str(tmp_path / "session")) assert outcome["args"] == f"{EXAMPLE / 'formal.py'} --root {tmp_path / 'session'} --key-file {tmp_path / 'key'}" assert outcome["rax"] == "0" and outcome["path"] == str(rax_root) and outcome["cwd"] == str(rax_root) + assert outcome["bin"] == str(tmp_path / "bin") py_compile.compile(str(EXAMPLE / "formal.py"), cfile=str(tmp_path / "formal.pyc"), doraise=True) @@ -1092,8 +1152,184 @@ def test_the_configs_run_raxs_session_on_claude_code_in_the_task_sandbox_with_th def test_the_launcher_serves_the_rollouts_it_runs_and_keeps_the_runs_out_of_raxs_checkout(): """The service serves the workspaces hermit makes (agent.params.logs), the task functions get RAX's checkout - expanded, and the launcher parses.""" + expanded, RAX's processes get the launcher's bwrap first, and the launcher parses.""" text = (EXAMPLE / "launch.sh").read_text() assert '--workspaces "$OUT/actor-logs"' in text and '"agent.params.logs=$OUT/actor-logs"' in text assert '"agent.params.rax_root=$RAX_ROOT"' in text and "lies inside RAX_ROOT" in text + assert 'PATH="$RAX_BIN:$PATH" "$RAX_PYTHON" "$HERE/service.py"' in text assert subprocess.run(["bash", "-n", str(EXAMPLE / "launch.sh")]).returncode == 0 + + +def test_the_launcher_refuses_a_bwrap_that_cannot_run_raxs_bundle_sandbox(tmp_path, rax_root): + """RAX's bundle sandbox passes bwrap --size (RHEL 9's bubblewrap 0.6.3 has none): such a bwrap is refused before + anything starts, since every rehearsal and formal episode would fail and every session score 0.""" + old = tmp_path / "old-bwrap" + old.write_text('#!/bin/sh\n[ "$1" = --version ] && { echo "bubblewrap 0.6.3"; exit 0; }\n' + 'echo "bwrap: Unknown option --size" >&2\nexit 1\n') + old.chmod(0o755) + env = {**os.environ, "RAX_ROOT": str(rax_root), "RAX_SIM_GPU": "0", "RAX_BWRAP": str(old), + "RAX_OUT": str(tmp_path / "out"), "HERMIT_PYTHON": "false"} + done = subprocess.run(["bash", str(EXAMPLE / "launch.sh")], env=env, capture_output=True, text=True, timeout=60) + assert done.returncode == 1 and "bubblewrap 0.6.3" in done.stderr and "takes no --size" in done.stderr + assert not (tmp_path / "out").exists() + + +def test_the_launcher_gives_raxs_simulators_a_cpu_renderer_when_asked(tmp_path, rax_root): + """RAX_RENDER=cpu: RAX's simulators get a Python (LIBERO_PRO_PYTHON, which RAX reads) that selects Mesa's software + EGL device, which egl_device.py finds, and no CUDA device; a host without one, or another value, is refused.""" + bwrap = tmp_path / "bwrap" + bwrap.write_text("#!/bin/sh\nexit 0\n") + simulator = tmp_path / "simulator python" # a path with a space, as a checkout may have + simulator.write_text('#!/bin/sh\ncase "$2" in *egl_device.py) [ -n "$NO_DEVICE" ] && exit 1; ' + '[ "$__EGL_VENDOR_LIBRARY_FILENAMES" = /usr/share/glvnd/egl_vendor.d/50_mesa.json ] && ' + 'echo 8; exit 0;; esac\n' + 'printf "%s|%s|%s|%s|%s\\n" "$__EGL_VENDOR_LIBRARY_FILENAMES" "${CUDA_VISIBLE_DEVICES-unset}" ' + '"$MUJOCO_EGL_DEVICE_ID" "$LP_NUM_THREADS" "$*"\n') + for tool in (bwrap, simulator): + tool.chmod(0o755) + env = {**os.environ, "RAX_ROOT": str(rax_root), "RAX_SIM_GPU": "0", "RAX_BWRAP": str(bwrap), + "RAX_OUT": str(tmp_path / "out"), "HERMIT_PYTHON": "false", "LIBERO_PRO_PYTHON": str(simulator), + "RAX_RENDER": "cpu"} + done = subprocess.run(["bash", str(EXAMPLE / "launch.sh")], env=env, capture_output=True, text=True, timeout=60) + assert done.returncode == 1, done.stderr # it stops at rows.py: HERMIT_PYTHON is `false` + wrapper = tmp_path / "out" / "rax-service" / "bin" / "libero-pro-python" + ran = subprocess.run([str(wrapper), "-m", "services.libero_pro.server"], capture_output=True, text=True, + env={"PATH": os.environ["PATH"], "MUJOCO_EGL_DEVICE_ID": "3", "CUDA_VISIBLE_DEVICES": "", + "__EGL_VENDOR_LIBRARY_FILENAMES": "/usr/share/glvnd/egl_vendor.d/10_nvidia.json"}) + assert ran.stdout == "/usr/share/glvnd/egl_vendor.d/50_mesa.json||8|2|-m services.libero_pro.server\n", ran + + refused = subprocess.run(["bash", str(EXAMPLE / "launch.sh")], env={**env, "NO_DEVICE": "1"}, + capture_output=True, text=True, timeout=60) + assert refused.returncode == 1 and "no Mesa software EGL device" in refused.stderr + other = subprocess.run(["bash", str(EXAMPLE / "launch.sh")], env={**env, "RAX_RENDER": "osmesa"}, + capture_output=True, text=True, timeout=60) + assert other.returncode == 2 and "RAX_RENDER is gpu or cpu" in other.stderr + + +MESA = Path("/usr/share/glvnd/egl_vendor.d/50_mesa.json") + + +@pytest.mark.skipif(not MESA.is_file(), reason="needs Mesa's EGL") +def test_the_egl_device_helper_finds_mesas_software_device(): + """egl_device.py (RAX_RENDER=cpu) on this host's Mesa: the index of its software (llvmpipe) EGL device.""" + done = subprocess.run([sys.executable, "-I", str(EXAMPLE / "egl_device.py")], capture_output=True, text=True, + env={**os.environ, "__EGL_VENDOR_LIBRARY_FILENAMES": str(MESA)}, timeout=60) + assert done.returncode == 0 and done.stdout.strip().isdigit(), (done.stdout, done.stderr) + + +# ---------- through the Trainer, in the sandboxes ---------- + +def _formal_stand_in(root: Path) -> None: + """The RAX modules formal.py imports, in the stand-in checkout: a supervisor whose formal batch succeeds on one of + the row's two episodes, so formal.py's own code runs (its imports, its outcome, its record, its last line).""" + files = { + "services/__init__.py": "", + "services/agent_formal/__init__.py": "", + "services/agent_formal/checkpoint.py": ( + "def _outcome(batch, state, bundle):\n" + " return {'status': 'completed', 'success_count': batch['successes'],\n" + " 'episode_count': batch['episodes'], 'bundle': bundle}\n"), + "services/controller/__init__.py": "", + "services/controller/backend.py": "def make_backend(config):\n return None\n", + "services/controller/frontend.py": ( + "from pathlib import Path\nfrom types import SimpleNamespace\n\n\n" + "def load_configuration(path):\n" + " return SimpleNamespace(root=Path(path).parent, external_perception=False, formal_collection=1,\n" + " formal_seed=0, formal_episodes=2)\n"), + "services/controller/gemini.py": "class GeminiRouter:\n pass\n\n\ndef load_key(path):\n return None\n", + "services/controller/storage.py": ( + "import json\nfrom pathlib import Path\n\n\n" + "def persist(path, value):\n Path(path).write_text(json.dumps(value))\n"), + "services/controller/supervisor.py": ( + "import json\n\n\nclass Supervisor:\n" + " def __init__(self, config, backend, router):\n" + " self.state = json.loads((config.root / 'state.json').read_text())\n\n" + " def submission_done(self):\n return False\n\n" + " def run_submission(self):\n self.state['formal_batch'] = {'successes': 1, 'episodes': 2}\n\n" + " def close(self):\n pass\n"), + } + for name, text in files.items(): + (root / name).parent.mkdir(parents=True, exist_ok=True) + (root / name).write_text(text) + + +def _smoke_config(tmp_path, rax_root, monkeypatch): + """smoke.yaml as launch.sh runs it, on the stand-ins: its rows written, RAX's checkout and the service's state + named, the runs, trees, workspaces and plan in the test's directory, a token that is no login's.""" + from hermit.config import Config + _formal_stand_in(rax_root) + rows = tmp_path / "rows" + R = _load("rax_rows", EXAMPLE / "rows.py") + monkeypatch.setattr(sys, "argv", ["rows.py", "--out", str(rows)]) + R.main() + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("RAX_ROOT", str(rax_root)) + monkeypatch.setenv("RAX_STATE", str(tmp_path / "state")) + monkeypatch.setenv("CLAUDE_CODE_OAUTH_TOKEN", "fake-setup-token-never-real") + return Config.load(EXAMPLE / "smoke.yaml", [ + f"data.tasks={rows / 'tasks'}", f"data.train={rows / 'splits' / 'smoke.txt'}", + f"data.test={rows / 'splits' / 'smoke_test.txt'}", f"trainer.output_dir={tmp_path / 'runs'}", + f"trainer.tree_dir={tmp_path / 'trees'}", f"agent.params.rax_root={rax_root}", + f"agent.params.logs={tmp_path / 'logs'}", f"agent.claude.plan_dir={tmp_path / 'plan'}"]) + + +@pytest.mark.skipif(not bwrap_works(), reason="needs bubblewrap with unprivileged user namespaces (CONTRIBUTING.md)") +def test_a_run_trains_through_the_trainer_in_the_sandboxes_and_evaluates_its_final_library( + tmp_path, rax_root, service, claude, monkeypatch): + """The smoke config as launch.sh runs it, on the stand-ins: the training session in the task sandbox (its /tmp/rax + link in the sandbox's own /tmp, the service's port forwarded, RAX's checkout shown in part), its merge taken into + the adapter by the merge program in the evolver sandbox, the judge's formal batch on the host; then the evaluation + session on the final library, whose clone holds the skill.""" + from hermit.evaluate import evaluate + from hermit.trainer.trainer import Trainer + config = _smoke_config(tmp_path, rax_root, monkeypatch) + Trainer(config, log=lambda *_: None).train() + run = tmp_path / "runs" / "rax-libero-smoke" + [step] = [json.loads(line) for line in (run / "steps.jsonl").read_text().splitlines()] + assert step["status"] == "done" and "took in 1 of 1" in step["evolver"]["summary"], step + final = run / "checkout" + assert (final / "skills" / "grasp-bowl" / "SKILL.md").read_bytes() == skill_files("grasp-bowl")[ + "skills/grasp-bowl/SKILL.md"] + assert "(skills/grasp-bowl/SKILL.md)" in (final / "INDEX.md").read_text() and spec(final)["passed"] + records = {p.name: json.loads(p.read_text()) for p in (run / "sandbox").glob("*.json")} + assert any(name.startswith("rollout-") for name in records), sorted(records) + for name, record in records.items(): + assert record["enforced"] and record["probe"]["passed"], (name, record) + [trained] = (tmp_path / "logs").glob("*/smoke-libero_spatial_0-*/workspaces/*/saw.json") + saw = json.loads(trained.read_text()) + assert saw["library"] == [] and saw["socket_dir"] == str(trained.parent / "rax" / "sock") + merged = json.loads(saw["merge"][1]["result"]["content"][0]["text"]) + assert merged["merged"] and merged["skills"] == ["grasp-bowl"], saw.get("merge_stderr") + + result = evaluate(config, "final", log=lambda *_: None) + assert result["mean_score"] == 0.5, result + [evaluated] = (tmp_path / "logs").glob("*/smoke_test-libero_spatial_0-*/workspaces/*/saw.json") + saw = json.loads(evaluated.read_text()) + assert saw["library"] == ["grasp-bowl"] and "merge" not in saw # the final library, read, not merged again + ledger = json.loads((tmp_path / "state" / "ledger.json").read_text()) + assert sorted(e["task"] for e in ledger.values()) == ["smoke-libero_spatial_0", "smoke_test-libero_spatial_0"] + assert all(e["finished"] for e in ledger.values()) + assert json.loads((service.made[1] / "hermit-formal.json").read_text())["success_count"] == 1 + + +@pytest.mark.skipif(not bwrap_works(), reason="needs bubblewrap with unprivileged user namespaces (CONTRIBUTING.md)") +def test_a_session_whose_cli_fails_before_it_starts_is_ended_when_its_worker_is_gone(tmp_path, rax_root, service, + claude, monkeypatch): + """The CLI exits before its session (no event): the call fails and `collect` never runs. The session `prepare` + registered is ended (`abandoned`) once the worker's sandbox is gone, by its lease, instead of keeping RAX's + frontend and simulators until the launch ends.""" + from hermit.trainer.trainer import Trainer + claude.write_text('#!/bin/sh\n[ "$1" = --version ] && { echo "2.1.332 (Claude Code)"; exit 0; }\n' + 'echo "the CLI broke" >&2\nexit 1\n') + config = _smoke_config(tmp_path, rax_root, monkeypatch) + Trainer(config, log=lambda *_: None).train() + [step] = [json.loads(line) for line in (tmp_path / "runs" / "rax-libero-smoke" / "steps.jsonl").read_text() + .splitlines()] + assert "none of the 1 sessions" in step["evolver"]["summary"], step + + def ledger(): + return json.loads((tmp_path / "state" / "ledger.json").read_text()) + assert ledger() + _until(lambda: all(e["finished"] for e in ledger().values())) + assert all(e.get("abandoned") for e in ledger().values()) + assert service.frontends_started and all(f.stops == 1 for f in service.frontends_started) From 4f3158fbf4f14fc30d0874d37dac6bfd0dd412d9 Mon Sep 17 00:00:00 2001 From: iamziyuzhao <iamziyuzhao@gmail.com> Date: Sun, 29 Nov 2026 02:23:08 -0500 Subject: [PATCH 3/7] RAX: the run tree read-only, the Stop hook on RAX's own rule, one attempt a call - The session's run tree (RAX's published/) is the service's now, <state>/run-trees/<random>: the frontend binds it onto the session's published/, and the task sandbox shows the trees read-only (environment.read) in a directory it cannot list, so a session reads its own frames and traces and writes none of them, as RAX's Claude Code sandbox allows. Beside the workspace, the agent could write it. The facts name it (run_tree). - The Stop hook asks the service whether exploration is closed (POST /explored: RAX's launcher's exploration_closed on the session's directory) instead of calling status on the frontend, which a long call can hold; no answer counts as open; at most three relaunches as before. - The configs run each call once (claude.retries: 1): Hermit's second attempt removes the session's workspace and log and calls prepare again, which the service refuses for a session that spent anything. prepare removes nothing an earlier attempt left before the service has accepted the call. The method page says what this loses: a session the provider stops serving is scored 0 (RAX relaunches it on the same conversation). - ADAPTER.md says a bundle sees none of the library (RAX's bundle sandbox on LIBERO; RAX's skill, written for its real robots, lets a controller import library skills). - The merge program runs on this hermit (PYTHONPATH); the library's files leave out Python's caches, as the deployment does; the README runs RAX's setup scripts in RAX's order; cpu_render.sh writes the CPU renderer for launch.sh and for RAX's setup scripts; launch.sh says hermit's overrides go before eval's --adapter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/methods/rax.md | 60 ++++--- examples/libero/rax/README.md | 28 ++- examples/libero/rax/cpu_render.sh | 25 +++ examples/libero/rax/eval_official.yaml | 5 +- examples/libero/rax/eval_val.yaml | 5 +- examples/libero/rax/launch.sh | 19 +- examples/libero/rax/run.yaml | 5 +- examples/libero/rax/service.py | 76 ++++++-- examples/libero/rax/smoke.yaml | 5 +- hermit/adapter/templates/rax/ADAPTER.md | 4 +- hermit/agent/evolver/methods/rax/actor.py | 48 +++-- hermit/agent/evolver/methods/rax/evolver.py | 5 +- hermit/agent/evolver/methods/rax/library.py | 9 +- hermit/agent/evolver/methods/rax/stop_hook.py | 64 +++---- tests/methods/rax/test_rax.py | 167 ++++++++++++------ 15 files changed, 351 insertions(+), 174 deletions(-) create mode 100755 examples/libero/rax/cpu_render.sh diff --git a/docs/methods/rax.md b/docs/methods/rax.md index 0d4fbb33..8b4ff114 100644 --- a/docs/methods/rax.md +++ b/docs/methods/rax.md @@ -57,9 +57,12 @@ What reaches the acting session: `ADAPTER.md` in its context, and through the RA `ADAPTER.md` holds RAX's two library paragraphs of `real/rainbow`'s `AGENTS.md` (the reading one with its lead-in shortened, "Teach later sessions" verbatim) between two of the port's: where the clone is, and where a LIBERO run's frames are (`runtime/autonomous_controller/runs/<run>/frames/`, where RAX's skill, written for its real robots, says -`runtime/frames/`). Without an adapter (`--adapter none`) the session has none of these: it is RAX's LIBERO session as -published. No existing template fits: none holds a repository of skills that sessions merge into through a checked -merge. +`runtime/frames/`) and that a bundle sees none of the library. RAX's skill lets a controller import library skills, as +on its real robots, whose controllers run in the agent's workspace; on LIBERO a rehearsal and the formal batch run the +bundle in RAX's bundle sandbox, which shows only the bundle's directory and `api/runtime.py`, so `ADAPTER.md` says to +copy into the bundle what it uses of a library skill. Without an adapter (`--adapter none`) the session has none of +these: it is RAX's LIBERO session as published. No existing template fits: none holds a repository of skills that +sessions merge into through a checked merge. ## The session @@ -68,21 +71,25 @@ Python): for each rollout, RAX's operator script makes the session's configurati (`scripts/configure_auto_research.py`), RAX's `prepare_workspace` makes its workspace (RAX's template, skills, `TASK.md`, the three demonstration images), and RAX's frontend serves its robot, episode, bundle and Gemini tools on a Unix socket. The frontend runs in a mount namespace of its own (bubblewrap) where the session's run tree is a -directory beside the rollout's workspace, so the session reads its frames and traces there -(`runtime/autonomous_controller`) and nothing else of RAX's session directory. +directory of the service's (`<state>/run-trees/<random>`, `RAX_STATE`), which the task sandbox shows read-only +(`environment.read`) and cannot list: the session reads its own frames and traces there +(`runtime/autonomous_controller`), writes none of them and sees nothing else of RAX's session directory, as RAX's +Claude Code sandbox lets its agent write only the workspace and the socket's directory. The session runs in the task sandbox (`hermit/agent/evolver/methods/rax/actor.py`): `prepare` registers with the service, writes RAX's workspace beside the deployment, and wires Claude Code as RAX's Claude Code launcher does: `CLAUDE.md` reads `AGENTS.md`, `.claude/skills` is `.agents/skills`, RAX's bridge (`harness/mcp_bridge.py`) to the socket as the MCP server `auto_research`, RAX's agent environment for its commands (RAX's Python first, the robot -socket, offline package tools, thread limits) and RAX's relaunch policy as a Stop hook. With an adapter it builds the -session's library repository from the adapter's files, clones it with RAX's `checkout`, and serves -`skill_library_merge` (`library_server.py`: RAX's name, description, schema and refusal, and RAX's `merge` against -that repository). The prompt is RAX's `START_PROMPT.md` in code mode. `collect` ends the session at the service and -writes what the session merged into its library (a git bundle of the repository's main past its first commit, made in -a fresh repository from copied objects) and the session's notes and code into the log. The judge, on the host, runs -RAX's formal batch of the submitted bundle (the supervisor's `run_submission`, `formal.py`) on the row's formal -layouts: the share of successful episodes, LIBERO's own binary check, errors counted as failures. +socket, offline package tools, thread limits) and RAX's relaunch policy as a Stop hook (`stop_hook.py`: whether +exploration is closed is RAX's launcher's own rule, `exploration_closed`, which the service applies to the session's +directory; a service that does not answer counts as open). With an adapter it builds the session's library repository +from the adapter's files, clones it with RAX's `checkout`, and serves `skill_library_merge` (`library_server.py`: RAX's +name, description, schema and refusal, and RAX's `merge` against that repository). The prompt is RAX's `START_PROMPT.md` +in code mode. `collect` ends the session at the service and writes what the session merged into its library (a git +bundle of the repository's main past its first commit, made in a fresh repository from copied objects) and the session's +notes and code into the log. The judge, on the host, runs RAX's formal batch of the submitted bundle (the supervisor's +`run_submission`, `formal.py`) on the row's formal layouts: the share of successful episodes, LIBERO's own binary check, +errors counted as failures. ## The step @@ -133,11 +140,11 @@ URL, default `RAX_SERVICE_URL`) and `bin` (the CLI). The session's settings are | Code | `libero-pro/native` 1767412 (LIBERO); the skill library of `real/rainbow` 36c926c | the same commits: RAX's operator script, workspace, frontend, supervisor, simulators, formal batch and skill library, unchanged | — | | Agent | Claude Code, Claude Opus 5.5 at xhigh, its own home, its servers alone (`--strict-mcp-config`); denied: the web tools, the subagent tools at a subagent cap of 0, edits of the workspace's `.claude/` and `.mcp.json`; its commands in Claude Code's own sandbox (writes in the workspace and the socket's directory) | the same model, effort, flags and deny rules (the project's `.claude/settings.json`, with `.rax-mcp.json` guarded too), on Hermit's Claude Code agent; its commands in the task sandbox (bubblewrap), so a command, unlike a file tool, can still write `.claude/`, and what it writes there runs in the same sandbox | the task sandbox is the boundary | | Prompt and workspace | `START_PROMPT.md`; `prepare_workspace` | the same, byte for byte; with an adapter, the library's clone, RAX's continual-learning skill and the two library paragraphs of `real/rainbow`'s `AGENTS.md` (`ADAPTER.md`) | the library is `real/rainbow`'s, which `libero-pro/native` lacks | -| Robot tools | RAX's frontend, through RAX's bridge on a socket | the same, on the host; the run tree beside the workspace, which the agent can write (RAX's frontend reads it without following links) | the task sandbox shows only declared paths | -| Relaunch | the launcher runs the CLI again (`--resume`) with `CONTINUE_PROMPT` while exploration is open, at most 3 times | a Stop hook continues the same CLI with the same prompt, without its clause about stopped background workers (here they run on) | Hermit runs one CLI per call | -| Error relaunch, adaptation stage | relaunch after a provider error; up to 5 adaptation episodes on swap layouts (collection 6) | not ported: Hermit retries only a session the model never served; no adaptation | scope | +| Robot tools | RAX's frontend, through RAX's bridge on a socket | the same, on the host; the run tree in the service's directory, shown read-only in the task sandbox (RAX's agent writes only its workspace and the socket's directory) | the task sandbox shows only declared paths | +| Relaunch | the launcher runs the CLI again (`--resume`) with `CONTINUE_PROMPT` while exploration is open, at most 3 times | a Stop hook continues the same CLI with the same prompt, without its clause about stopped background workers (here they run on); exploration closed by the launcher's own rule (`exploration_closed`), which the service applies | Hermit runs one CLI per call | +| Error relaunch, adaptation stage | relaunch after a provider error; up to 5 adaptation episodes on swap layouts (collection 6) | not ported: a session the provider stops serving ends there, scored 0 with its merges left out (Hermit judges no failed session, even one that submitted); Hermit's own second attempt is off (`claude.retries: 1`): it would remove the session's workspace and log and start the session again, which RAX never does; no adaptation | Hermit runs one CLI per call; scope | | Agent pause | the agent CLI and its processes are stopped (SIGSTOP) while a bundle is copied and rehearsed | not paused: the main turn waits on the call, but background commands and subagents run on; the bundle copied is the registered snapshot | the CLI's processes are in the task sandbox's process namespace, which the host's frontend cannot signal | -| Bundles | run at the agent's workspace path, in a fresh bubblewrap sandbox and simulator per episode | run at RAX's session workspace path (not the Hermit workspace's); the same sandbox | RAX's supervisor names that path | +| Bundles | run at the agent's workspace path, in a fresh bubblewrap sandbox and simulator per episode | run at RAX's session workspace path (not the Hermit workspace's); the same sandbox, which shows none of the skill library: `ADAPTER.md` says to copy into the bundle what it uses of a library skill | RAX's supervisor names that path; RAX's library comes from `real/rainbow`, whose controllers run in the agent's workspace | | Exploration | ≤ 20 episodes on fresh layouts (`env.seed(1000 + i)`), two environments, 600 s + 5 s per step | the same; each split's layouts its own (train 100-119, val 200-219, test 0-19) | disjoint splits | | Evaluation | each session's bundle on official init states 0-49 and on LIBERO-Pro's swap states 0-49 | one split per score: train on official 0-42, val on official 43-49, test on swap 0-49 (official 0-49 for the paper's table, `eval_official.yaml`) | held-out splits for a learned library | | Gemini | Gemini 3.8 Flash via OpenRouter, $10 per session | the same tool, on the host; no session cap (removed upstream before the pinned commit); each session's spend recorded (`gemini_usd`) | the pinned code | @@ -156,15 +163,16 @@ skill in it passed RAX's checks twice (in the session and in the Evolver). RAX's the checks hold its format, not that the runs happened. The service trusts a session only with its workspace and task: it registers the one workspace the framework makes for a -rollout, once (again only for a retry of a session that spent nothing), so a session cannot start a second session or a -fresh budget. A session `prepare` registered but could not set up is ended at once; one whose `collect` cannot reach the -service is ended by the judge; and one whose worker ends without `collect` (the CLI failed before its session, the call -was stopped) is ended by the service when the worker's lease closes: a connection `prepare` opens and the worker holds, -which goes with everything in the task sandbox. Gemini's calls (RAX's frontend on the host, OpenRouter) are outside -Hermit's model layer and its usage accounting; their cost is in each session's facts and score (`gemini_usd`). The -session's Claude Code calls go through Hermit's Claude Code agent (Model: the Claude login's model; Base Agent: Claude -Code; Acting Agent: the CLI agent with RAX's task functions), with its login plan, timeout and usage. The Evolver calls -no model. +rollout, once (again only for a call run again whose session spent nothing; the configs run each call once), so a +session cannot start a second session or a fresh budget. The sessions' run trees are the service's: the task sandbox +shows them read-only and cannot list them, so a session reads its own and writes none. A session `prepare` registered +but could not set up is ended at once; one whose `collect` cannot reach the service is ended by the judge; and one whose +worker ends without `collect` (the CLI failed before its session, the call was stopped) is ended by the service when the +worker's lease closes: a connection `prepare` opens and the worker holds, which goes with everything in the task +sandbox. Gemini's calls (RAX's frontend on the host, OpenRouter) are outside Hermit's model layer and its usage +accounting; their cost is in each session's facts and score (`gemini_usd`). The session's Claude Code calls go through +Hermit's Claude Code agent (Model: the Claude login's model; Base Agent: Claude Code; Acting Agent: the CLI agent with +RAX's task functions), with its login plan, timeout and usage. The Evolver calls no model. ## Example diff --git a/examples/libero/rax/README.md b/examples/libero/rax/README.md index 6f499290..5f674daa 100644 --- a/examples/libero/rax/README.md +++ b/examples/libero/rax/README.md @@ -50,8 +50,8 @@ for the simulators, bubblewrap, git): ```bash git clone https://github.com/robot-agent-exploration/rax && cd rax git checkout 1767412c5300b9358059ae6a39740c3c28d2b8b9 # branch libero-pro/native -bash scripts/setup_host_env.sh # runtime/envs/host: the harness's and agent's Python bash scripts/bootstrap_sources.sh # LIBERO-PRO/ at its pinned commit +bash scripts/setup_host_env.sh # runtime/envs/host: the harness's and agent's Python bash scripts/setup_libero_pro_env.sh # runtime/envs/libero_pro: the simulator's runtime/envs/host/bin/python scripts/setup_libero_pro_data.py for suite in spatial object goal 10; do for i in $(seq 0 9); do # three demonstration images per task @@ -72,9 +72,16 @@ conda create -y -p ~/bwrap-env -c conda-forge bubblewrap=0.9.0 # then: export On a host whose GPUs also run other processes' CUDA work, NVIDIA's EGL can break under the simulators: `start_episode` then fails in LIBERO's depth check (`get_real_depth_map`'s range assertion) or hangs. `RAX_RENDER=cpu` renders with Mesa's llvmpipe instead (Mesa's EGL must be installed): `launch.sh` gives RAX a simulator Python (`LIBERO_PRO_PYTHON`, -which RAX's `services/libero_pro/process.py` reads) that selects Mesa's software EGL device (`egl_device.py` finds it) -and no CUDA device, at `nice 10` with two llvmpipe threads. Physics is unchanged; the images differ from NVIDIA's by -renderer noise, so a run with it says so beside its results. +which RAX's `services/libero_pro/process.py` reads) that `cpu_render.sh` writes. It selects Mesa's software EGL device +(`egl_device.py` finds it) and no CUDA device, at `nice 10` with two llvmpipe threads. Physics is unchanged; the +images differ from NVIDIA's by renderer noise (on `libero_spatial_0`'s layout 300, 1.3/255 per pixel on average, 0.6% +of the pixels by more than 20, at edges), so a run with it says so beside its results. RAX's setup scripts +render too (the demonstrations are replayed in the simulator): on such a host, run them with the same Python, + +```bash +cpu=/path/to/hermit/examples/libero/rax/cpu_render.sh # in RAX's checkout, before its setup scripts above +export LIBERO_PRO_PYTHON="$("$cpu" ~/rax-cpu "$PWD/runtime/envs/libero_pro/bin/python")" +``` The sessions run on the machine's Claude login ([Claude subscription](../../../docs/guides/claude-subscription.md): `claude setup-token`, then `CLAUDE_CODE_OAUTH_TOKEN`). RAX's Gemini perception tool (`gemini_generate`, which the @@ -96,13 +103,18 @@ RAX_CONFIG=eval_val.yaml ./launch.sh eval --adapter rax-libero/ckpt-step-20 # RAX_CONFIG=eval_official.yaml ./launch.sh eval --adapter none # the paper's protocol ``` +Further arguments go to hermit, its overrides (`key=value`) before `eval`'s `--adapter`, since hermit's parser takes +them in one run: `./launch.sh eval "agent.claude.plan_dir=$HOME/plan" --adapter final`. + `--adapter none` runs RAX's sessions as published (no library, no `skill_library_merge`); `--adapter root` gives every session the empty library, its clone and the merge tool. Runs go to `RAX_OUT` (default `../runs/rax`): the trainer's records, the sessions' logs (`actor-logs/`: the CLI's stream, the session's notes and code, its library -bundle), the service's ledger and log (`rax-service/`, `rax-service.log`). RAX's own session directories (its state, -bundles, run trees and formal reports) stay under `$RAX_ROOT/runtime/auto-research/`, named in the ledger. One launch -at a time on a `RAX_OUT`: its service holds a lock in `rax-service/`, and a service started after one that was killed -first ends the sessions that one left open. +bundle), the service's ledger and log (`rax-service/`, `rax-service.log`), and each session's run tree, its +exploration's frames and traces (`rax-service/run-trees/<random>`, `run_tree` in its facts: the task sandbox shows the +trees read-only and cannot list them). RAX's own session directories (its state, bundles and formal reports) stay +under `$RAX_ROOT/runtime/auto-research/`, named in the ledger. One launch at a time on a `RAX_OUT`: its service holds +a lock in `rax-service/`, and a service started after one that was killed first ends the sessions that one left +open. A session runs for hours (the paper reports a median of 0.7 to 1.8 hours of agent time per DexJoCo session, Table 17; LIBERO's sessions have two environments and up to 20 episodes), and each score is a formal batch of 43 (train), 7 diff --git a/examples/libero/rax/cpu_render.sh b/examples/libero/rax/cpu_render.sh new file mode 100755 index 00000000..52372158 --- /dev/null +++ b/examples/libero/rax/cpu_render.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# RAX's simulators on the CPU (RAX_RENDER=cpu in launch.sh; README.md): writes <dir>/libero-pro-python, a simulator +# Python for RAX's LIBERO_PRO_PYTHON (services/libero_pro/process.py reads it) that renders with Mesa's llvmpipe and +# sees no CUDA device, and prints its path. For a host whose GPUs run other processes' CUDA, which can break NVIDIA's +# EGL under the simulators; RAX's setup scripts (setup_libero_pro_demos.py, libero_pro_doctor.py) take it too. +# +# cpu_render.sh <dir> <RAX's simulator Python, e.g. $RAX_ROOT/runtime/envs/libero_pro/bin/python> +set -euo pipefail +(( $# == 2 )) || { echo "usage: cpu_render.sh <dir> <RAX's simulator Python>" >&2; exit 2; } +HERE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +DIR="$1" +SIM_PYTHON="$2" +MESA=/usr/share/glvnd/egl_vendor.d/50_mesa.json +DEVICE="$(__EGL_VENDOR_LIBRARY_FILENAMES="$MESA" "$SIM_PYTHON" -I "$HERE/egl_device.py")" || { + echo "no Mesa software EGL device for $SIM_PYTHON (Mesa's EGL: $MESA)" >&2; exit 1; } +mkdir -p "$DIR" +DIR="$(cd "$DIR" && pwd)" +{ echo '#!/bin/bash' + echo "# RAX's simulators on the CPU (cpu_render.sh): Mesa's software EGL device, no CUDA device" + printf 'export __EGL_VENDOR_LIBRARY_FILENAMES=%q MUJOCO_EGL_DEVICE_ID=%q\n' "$MESA" "$DEVICE" + echo 'export CUDA_VISIBLE_DEVICES=' + echo 'export LP_NUM_THREADS="${LP_NUM_THREADS:-2}"' + printf 'exec nice -n 10 %q "$@"\n' "$SIM_PYTHON"; } > "$DIR/libero-pro-python" +chmod +x "$DIR/libero-pro-python" +echo "$DIR/libero-pro-python" diff --git a/examples/libero/rax/eval_official.yaml b/examples/libero/rax/eval_official.yaml index c40a04d0..2f1eacf1 100644 --- a/examples/libero/rax/eval_official.yaml +++ b/examples/libero/rax/eval_official.yaml @@ -23,6 +23,8 @@ agent: claude: web_search: false # RAX's agent works offline (its DENIED_TOOLS: WebFetch, WebSearch) timeout_s: 172800 # Hermit's cap on a session (RAX sets none): 20 episodes and the work between + retries: 1 # no second attempt: it would remove the session's workspace and log, + # and RAX never starts a session again (docs/methods/rax.md) args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] # RAX's: only the session's servers (prepare writes them) env: # RAX's Claude Code session (harness/claude_cli/auto_research.py agent_environment) MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: (CALL_SECONDS + 300) ms @@ -32,11 +34,12 @@ agent: CLAUDE_CODE_AUTO_COMPACT_WINDOW: "250000" ENABLE_PROMPT_CACHING_1H: "1" CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: 1h -environment: # the task sandbox: RAX's agent Python, MCP bridge and start prompt, nothing else +environment: # the task sandbox: RAX's agent Python, MCP bridge, start prompt and run trees read: - $RAX_ROOT/runtime/envs/host - $RAX_ROOT/harness/mcp_bridge.py - $RAX_ROOT/auto_research_agent/START_PROMPT.md + - $RAX_STATE/run-trees # the sessions' run trees (the service's): read-only, never listed env: [RAX_SERVICE_URL] # the host's RAX service (launch.sh): its 127.0.0.1 port is forwarded judge: path: judge.py # on the host: RAX's formal batch of the submitted bundle on the row's layouts diff --git a/examples/libero/rax/eval_val.yaml b/examples/libero/rax/eval_val.yaml index ee79fb1a..dc30294f 100644 --- a/examples/libero/rax/eval_val.yaml +++ b/examples/libero/rax/eval_val.yaml @@ -24,6 +24,8 @@ agent: claude: web_search: false # RAX's agent works offline (its DENIED_TOOLS: WebFetch, WebSearch) timeout_s: 172800 # Hermit's cap on a session (RAX sets none): 20 episodes and the work between + retries: 1 # no second attempt: it would remove the session's workspace and log, + # and RAX never starts a session again (docs/methods/rax.md) args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] # RAX's: only the session's servers (prepare writes them) env: # RAX's Claude Code session (harness/claude_cli/auto_research.py agent_environment) MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: (CALL_SECONDS + 300) ms @@ -33,11 +35,12 @@ agent: CLAUDE_CODE_AUTO_COMPACT_WINDOW: "250000" ENABLE_PROMPT_CACHING_1H: "1" CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: 1h -environment: # the task sandbox: RAX's agent Python, MCP bridge and start prompt, nothing else +environment: # the task sandbox: RAX's agent Python, MCP bridge, start prompt and run trees read: - $RAX_ROOT/runtime/envs/host - $RAX_ROOT/harness/mcp_bridge.py - $RAX_ROOT/auto_research_agent/START_PROMPT.md + - $RAX_STATE/run-trees # the sessions' run trees (the service's): read-only, never listed env: [RAX_SERVICE_URL] # the host's RAX service (launch.sh): its 127.0.0.1 port is forwarded judge: path: judge.py # on the host: RAX's formal batch of the submitted bundle on the row's layouts diff --git a/examples/libero/rax/launch.sh b/examples/libero/rax/launch.sh index 1f21c383..6853e2f3 100755 --- a/examples/libero/rax/launch.sh +++ b/examples/libero/rax/launch.sh @@ -9,6 +9,9 @@ # RAX_CONFIG=eval_val.yaml ./launch.sh eval --adapter rax-libero/ckpt-step-20 # the validation split # RAX_CONFIG=eval_official.yaml ./launch.sh eval --adapter none # the paper's LIBERO protocol, RAX as published # +# Further arguments go to hermit, its overrides (key=value) before eval's --adapter: hermit's parser takes them in one +# run, e.g. ./launch.sh eval "agent.claude.plan_dir=$HOME/plan" --adapter final. +# # Variables: RAX_ROOT (RAX's checkout, libero-pro/native, set up as README.md says), RAX_SIM_GPU (the simulators' # GPU, an ordinal or UUID: RAX's --sim-gpu), RAX_KEY_FILE (an OpenRouter key file for RAX's Gemini perception tool; # without it the sessions have none), RAX_OUT (the runs, default runs/ beside this folder), RAX_PORT (the service, @@ -66,22 +69,14 @@ ln -sfn "$(cd "$(dirname "$BWRAP")" && pwd)/$(basename "$BWRAP")" "$RAX_BIN/bwra # RAX_RENDER=cpu: other processes' CUDA work on a GPU can break NVIDIA's EGL under the simulators there (start_episode # fails in LIBERO's depth check, or hangs). RAX takes its simulators' Python from LIBERO_PRO_PYTHON -# (services/libero_pro/process.py): this one renders with Mesa's llvmpipe and sees no CUDA device, physics unchanged. +# (services/libero_pro/process.py): cpu_render.sh's renders with Mesa's llvmpipe and no CUDA device, physics unchanged. case "${RAX_RENDER:-gpu}" in gpu) ;; cpu) SIM_PYTHON="${LIBERO_PRO_PYTHON:-$RAX_ROOT/runtime/envs/libero_pro/bin/python}" - MESA=/usr/share/glvnd/egl_vendor.d/50_mesa.json - DEVICE="$(__EGL_VENDOR_LIBRARY_FILENAMES="$MESA" "$SIM_PYTHON" -I "$HERE/egl_device.py")" || { - echo "RAX_RENDER=cpu: no Mesa software EGL device for $SIM_PYTHON (Mesa's EGL: $MESA)" >&2; exit 1; } - { echo '#!/bin/bash' - echo "# RAX's simulators on the CPU (launch.sh, RAX_RENDER=cpu): Mesa's software EGL device, no CUDA device" - printf 'export __EGL_VENDOR_LIBRARY_FILENAMES=%q MUJOCO_EGL_DEVICE_ID=%q\n' "$MESA" "$DEVICE" - echo 'export CUDA_VISIBLE_DEVICES=' - echo 'export LP_NUM_THREADS="${LP_NUM_THREADS:-2}"' - printf 'exec nice -n 10 %q "$@"\n' "$SIM_PYTHON"; } > "$RAX_BIN/libero-pro-python" - chmod +x "$RAX_BIN/libero-pro-python" - export LIBERO_PRO_PYTHON="$RAX_BIN/libero-pro-python" ;; + SIM_PYTHON="$("$HERE/cpu_render.sh" "$RAX_BIN" "$SIM_PYTHON")" || { + echo "RAX_RENDER=cpu: no CPU renderer (cpu_render.sh above)" >&2; exit 1; } + export LIBERO_PRO_PYTHON="$SIM_PYTHON" ;; *) echo "RAX_RENDER is gpu or cpu, not ${RAX_RENDER}" >&2; exit 2 ;; esac diff --git a/examples/libero/rax/run.yaml b/examples/libero/rax/run.yaml index b6352782..8f3543f7 100644 --- a/examples/libero/rax/run.yaml +++ b/examples/libero/rax/run.yaml @@ -33,6 +33,8 @@ agent: claude: web_search: false # RAX's agent works offline (its DENIED_TOOLS: WebFetch, WebSearch) timeout_s: 172800 # Hermit's cap on a session (RAX sets none): 20 episodes and the work between + retries: 1 # no second attempt: it would remove the session's workspace and log, + # and RAX never starts a session again (docs/methods/rax.md) args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] # RAX's: only the session's servers (prepare writes them) env: # RAX's Claude Code session (harness/claude_cli/auto_research.py agent_environment) MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: (CALL_SECONDS + 300) ms @@ -42,11 +44,12 @@ agent: CLAUDE_CODE_AUTO_COMPACT_WINDOW: "250000" ENABLE_PROMPT_CACHING_1H: "1" CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: 1h -environment: # the task sandbox: RAX's agent Python, MCP bridge and start prompt, nothing else +environment: # the task sandbox: RAX's agent Python, MCP bridge, start prompt and run trees read: - $RAX_ROOT/runtime/envs/host - $RAX_ROOT/harness/mcp_bridge.py - $RAX_ROOT/auto_research_agent/START_PROMPT.md + - $RAX_STATE/run-trees # the sessions' run trees (the service's): read-only, never listed env: [RAX_SERVICE_URL] # the host's RAX service (launch.sh): its 127.0.0.1 port is forwarded judge: path: judge.py # on the host: RAX's formal batch of the submitted bundle on the row's layouts diff --git a/examples/libero/rax/service.py b/examples/libero/rax/service.py index 4a3bd3f0..d8c92e72 100644 --- a/examples/libero/rax/service.py +++ b/examples/libero/rax/service.py @@ -14,15 +14,21 @@ layouts and episodes, and its formal layouts, which the judge plays after the session); RAX's prepare_workspace makes its directory and workspace under RAX's artifact root, outside every sandbox; the workspace comes back as a tar for `prepare` to write. RAX's frontend starts on a socket - in the run's own directory (<run>/rax/sock), with the session's run tree, which the frontend writes - and the agent reads, bound from <run>/rax/published onto <session>/published in the frontend's own - mount namespace (bubblewrap): the agent sees that tree and nothing else of the session's directory. - A rollout has one session: a workspace registers again (the framework's retry of a session the - model never served) only while its session has spent nothing, and then starts afresh. + in the run's own directory (<run>/rax/sock), with the session's run tree (which the frontend + writes and the agent reads) bound from <state>/run-trees/<random> onto <session>/published in the + frontend's own mount namespace (bubblewrap; the rest of its view is the host's). The trees are + outside every sandbox: the task sandbox shows <state>/run-trees read-only, a directory that can be + passed through but not listed, so a session reads its own tree (the reply names it) and writes + none, as RAX's agent reads and never writes its run tree. A rollout has one session: a workspace + registers again (a retry of the call) only while its session has spent nothing, and then starts + afresh. POST /lease {workspace, session} by the task's `prepare`, once the session is wired: the connection stays open while the process that runs the session lives (the task sandbox's worker). When it closes before /finish ended the session (the CLI failed before its session, the call was stopped, and `collect` never ran), the session is ended (`abandoned` in the ledger). + POST /explored {workspace, session} by the session's Stop hook: whether its exploration is closed, by RAX's + launcher's own rule on the session's directory (services/agent_formal/checkpoint.py + exploration_closed), never by asking the frontend, which a long call can keep busy. POST /finish {workspace} by the task's `collect` (and the judge): RAX's frontend stopped, as RAX's launcher stops it when the agent ends; the session's state read from its directory. GET /health @@ -48,6 +54,7 @@ from pathlib import Path import re import select +import shutil import signal import subprocess import sys @@ -61,6 +68,7 @@ STOP_SECONDS = 120 # RAX's SERVER_STOP_SECONDS SOCKET = "robot.sock" PUBLISHED_PARTS = ("runs", "episode_reviews") # RAX's PUBLISHED_PARTS +TREES = "run-trees" # <state>/run-trees/<random>: the sessions' run trees (environment.read in the configs) NANODOLLARS = 1_000_000_000 # RAX's billing unit (services/controller/billing.py) @@ -158,6 +166,11 @@ def __init__(self, args, rows: dict): self.registering = threading.Lock() # one registration at a time self.links = args.socket_links.resolve() self.links.mkdir(parents=True, exist_ok=True, mode=0o700) + # The sessions' run trees, outside every sandbox: the task sandbox shows this directory read-only, and without + # its read bit no session can list it, only pass through it to its own tree (`register`) + self.trees = (args.state / TREES).resolve() + self.trees.mkdir(exist_ok=True) + self.trees.chmod(0o300) sys.path.insert(0, str(self.rax)) self._reap() @@ -190,7 +203,7 @@ def _end(self, entry: dict, frontend: Frontend | None, **mark) -> dict: "rehearsals": sum(r.get("mode") == "rehearsal" for r in state.get("results", [])), "exploration_used": state.get("exploration_started", 0), "exploration_budget": len(configuration.get("exploration_seeds") or []), - "gemini_usd": gemini_usd(state)} + "gemini_usd": gemini_usd(state), "run_tree": entry.get("tree")} with self.ledger.lock: entry.update(finished=entry.get("finished") or time.time(), **facts, **mark) self.ledger.save() @@ -219,7 +232,7 @@ def _session_dirs(self, body: dict) -> tuple[Path, Path, Path, dict]: if workspace != given.absolute() or not workspace.is_dir(): raise ValueError(f"{given} is not a directory of its own (no link on its path)") mine = workspace.parent / "rax" - for part in ("", "published", *(f"published/{p}" for p in PUBLISHED_PARTS), "sock"): + for part in ("", "sock"): path = mine / part if path.is_symlink() or not path.is_dir(): raise ValueError(f"{path} must be a directory the task's prepare made") @@ -262,16 +275,27 @@ def _workspace(self, operator_input: Path): archive.add(path, arcname=relative, recursive=False) return config, base64.b64encode(buffer.getvalue()).decode() - def _start_frontend(self, config, workspace: Path, mine: Path) -> Frontend: + def _tree(self) -> Path: + """A session's run tree (RAX's published/: the parts its frontend writes), a fresh directory under the trees' + directory with a name no other session can learn: the task sandbox shows the trees read-only, and none can be + listed there.""" + tree = self.trees / uuid.uuid4().hex + tree.mkdir(mode=0o700) + for part in PUBLISHED_PARTS: + (tree / part).mkdir(mode=0o700) + return tree + + def _start_frontend(self, config, workspace: Path, mine: Path, tree: Path) -> Frontend: """RAX's start_frontend (harness/codex_cli/auto_research.py), in a mount namespace where the session's run tree - is the run's own published/, and with the socket in the run's sock/ (reached through a short link: a socket's - path is at most 107 bytes). No agent pid file: the sandboxed CLI's processes are not this host's to pause.""" + is `tree` (outside every sandbox), and with the socket in the run's sock/ (reached through a short link: a + socket's path is at most 107 bytes). No agent pid file: the sandboxed CLI's processes are not this host's to + pause.""" link = self.links / uuid.uuid4().hex[:12] link.symlink_to(mine / "sock", target_is_directory=True) socket = mine / "sock" / SOCKET socket.unlink(missing_ok=True) info_read, info_write = os.pipe() - args = ["bwrap", "--dev-bind", "/", "/", "--bind", str(mine / "published"), str(config.root / "published"), + args = ["bwrap", "--dev-bind", "/", "/", "--bind", str(tree), str(config.root / "published"), "--info-fd", str(info_write), "--", sys.executable, "-m", "services.controller.frontend", "--config", str(config.root / "configuration.json"), @@ -327,18 +351,23 @@ def register(self, body: dict) -> dict: old.stop() # the call run again: its first session ends here operator_input = self._configure(row) config, archive = self._workspace(operator_input) - frontend = self._start_frontend(config, workspace, mine) + tree = self._tree() + try: + frontend = self._start_frontend(config, workspace, mine, tree) + except BaseException: + shutil.rmtree(tree, ignore_errors=True) + raise from services.mcp_contract import Contract with self.ledger.lock: self.frontends[key] = frontend self.ledger.data[key] = {"task": row["id"], "rax_task": row["task"], "rollout": str(rollout), - "root": str(config.root), "session": config.root.name, + "root": str(config.root), "session": config.root.name, "tree": str(tree), "started": time.time(), "finished": None, "frontend_pid": frontend.pid, "superseded": ([*previous.get("superseded", []), previous["root"]] if previous else [])} self.ledger.save() - return {"ok": True, "workspace": archive, "session": config.root.name, "cpus": config.training.cpus, - "subagents": Contract.from_config(config).subagent_cap} + return {"ok": True, "workspace": archive, "session": config.root.name, "tree": str(tree), + "cpus": config.training.cpus, "subagents": Contract.from_config(config).subagent_cap} def finish(self, body: dict) -> dict: key = str(Path(str(body.get("workspace", ""))).resolve()) @@ -360,6 +389,20 @@ def lease(self, body: dict) -> tuple[str, str]: raise ValueError("no open session of this workspace by that name") return key, session + def explored(self, body: dict) -> dict: + """Whether a session's exploration is closed (its Stop hook asks), by RAX's launcher's rule on the session's + directory (services/agent_formal/checkpoint.py exploration_closed: the marker RAX's frontend writes once + exploration is closed, or the submission), never by asking the frontend, which a long call can hold.""" + key = str(Path(str(body.get("workspace", ""))).resolve()) + with self.ledger.lock: + entry = self.ledger.data.get(key) + if entry is None or entry.get("session") != str(body.get("session") or ""): + raise ValueError("no session of this workspace by that name") + from services.agent_formal.checkpoint import exploration_closed + from services.controller.frontend import load_configuration + config = load_configuration(Path(entry["root"]) / "configuration.json") + return {"ok": True, "closed": bool(exploration_closed(config))} + def lease_ended(self, key: str, session: str) -> None: """A lease's connection closed: the process that ran the session is gone. The session, if `collect` did not end it and the workspace did not register again since, is ended now (`abandoned`).""" @@ -410,7 +453,8 @@ def do_POST(self): pass service.lease_ended(*held) return - route = {"/register": service.register, "/finish": service.finish}.get(self.path) + route = {"/register": service.register, "/explored": service.explored, + "/finish": service.finish}.get(self.path) self._reply(route(body) if route else {"ok": False, "error": f"no route {self.path}"}) except Exception as exc: # a bad request is the session's error, not the service's end self._reply({"ok": False, "error": f"{type(exc).__name__}: {exc}"}) diff --git a/examples/libero/rax/smoke.yaml b/examples/libero/rax/smoke.yaml index ce373df5..a7872e63 100644 --- a/examples/libero/rax/smoke.yaml +++ b/examples/libero/rax/smoke.yaml @@ -25,6 +25,8 @@ agent: claude: web_search: false # RAX's agent works offline (its DENIED_TOOLS: WebFetch, WebSearch) timeout_s: 10800 # Hermit's cap on the smoke's session + retries: 1 # no second attempt: it would remove the session's workspace and log, + # and RAX never starts a session again (docs/methods/rax.md) args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] # RAX's: only the session's servers (prepare writes them) env: # RAX's Claude Code session (harness/claude_cli/auto_research.py agent_environment) MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: (CALL_SECONDS + 300) ms @@ -34,11 +36,12 @@ agent: CLAUDE_CODE_AUTO_COMPACT_WINDOW: "250000" ENABLE_PROMPT_CACHING_1H: "1" CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: 1h -environment: # the task sandbox: RAX's agent Python, MCP bridge and start prompt, nothing else +environment: # the task sandbox: RAX's agent Python, MCP bridge, start prompt and run trees read: - $RAX_ROOT/runtime/envs/host - $RAX_ROOT/harness/mcp_bridge.py - $RAX_ROOT/auto_research_agent/START_PROMPT.md + - $RAX_STATE/run-trees # the sessions' run trees (the service's): read-only, never listed env: [RAX_SERVICE_URL] # the host's RAX service (launch.sh): its 127.0.0.1 port is forwarded judge: path: judge.py # on the host: RAX's formal batch of the submitted bundle on the row's layouts diff --git a/hermit/adapter/templates/rax/ADAPTER.md b/hermit/adapter/templates/rax/ADAPTER.md index 413d9358..fee28caa 100644 --- a/hermit/adapter/templates/rax/ADAPTER.md +++ b/hermit/adapter/templates/rax/ADAPTER.md @@ -15,4 +15,6 @@ skill with its evidence and images, or improve the library skill you used; commi before the session ends. Follow [continual-learning](.agents/skills/continual-learning/SKILL.md). On this robot a skill's frames are under `runtime/autonomous_controller/runs/<run>/frames/`, and a run is unattended -when its code ran from start to end with no help from you, as in a rehearsal. +when its code ran from start to end with no help from you, as in a rehearsal. A rehearsal and the formal evaluation +run your registered bundle in a sandbox that shows only the bundle's own directory and `api/runtime.py`, never +`skill-library/`: copy into the bundle what it uses of a library skill instead of importing it from there. diff --git a/hermit/agent/evolver/methods/rax/actor.py b/hermit/agent/evolver/methods/rax/actor.py index c499ca4a..574e599d 100644 --- a/hermit/agent/evolver/methods/rax/actor.py +++ b/hermit/agent/evolver/methods/rax/actor.py @@ -8,18 +8,22 @@ prepare registers the session: the service makes RAX's configuration of the task row (scripts/ configure_auto_research.py) and RAX's workspace for it (harness/codex_cli/auto_research.py prepare_workspace), and starts RAX's frontend on a socket in this run's own directory, with RAX's run - tree (published/) there too, where the session reads it as runtime/autonomous_controller. It writes RAX's - workspace here beside the deployment and wires the session as RAX's Claude Code launcher does + tree (published/) in a directory of the service's that the task sandbox shows read-only + (environment.read): the session reads it as runtime/autonomous_controller and cannot write it, as RAX's + agent cannot. Nothing an earlier attempt left is removed before the service has accepted this one (it + refuses a workspace whose session spent anything: a RAX session is never started again). It writes + RAX's workspace here beside the deployment and wires the session as RAX's Claude Code launcher does (harness/claude_cli/auto_research.py): CLAUDE.md reads AGENTS.md, .claude/skills is .agents/skills, the frontend's MCP server through RAX's bridge (harness/mcp_bridge.py), RAX's agent environment for the session's commands (harness/agent_host.py `environment`), and RAX's relaunch policy as a Stop hook - (stop_hook.py). With an adapter (the `rax` template), it makes the session's library repository of the - adapter's files and RAX's clone of it, skill-library/, adds RAX's continual-learning skill (library.py) - and serves RAX's skill_library_merge tool (library_server.py), as RAX's harness does for a workspace with a - library. Without one (`--adapter none`) the session is RAX's on LIBERO as published. Last, it takes the - session's lease (`_lease`): a connection to the service this process holds while the session runs, so - that a session whose worker ends without `collect` (the CLI failed before its session, the call was - stopped: everything in the task sandbox goes with its worker) is ended by the service. + (stop_hook.py, which asks the service whether exploration is closed). With an adapter (the `rax` + template), it makes the session's library repository of the adapter's files and RAX's clone of it, + skill-library/, adds RAX's continual-learning skill (library.py) and serves RAX's skill_library_merge + tool (library_server.py), as RAX's harness does for a workspace with a library. Without one + (`--adapter none`) the session is RAX's on LIBERO as published. Last, it takes the session's lease + (`_lease`): a connection to the service this process holds while the session runs, so that a session + whose worker ends without `collect` (the CLI failed before its session, the call was stopped: + everything in the task sandbox goes with its worker) is ended by the service. prompt RAX's START_PROMPT.md as its launcher gives it in code mode (`startup_prompt`) answer the agent's last message collect ends the session at the service (RAX's frontend stopped, as RAX stops it when the agent ends) and lets @@ -55,7 +59,7 @@ MCP_SERVER = "auto_research" # RAX's name of the frontend's MCP server LIBRARY_SERVER = "skill_library" # skill_library_merge's server (RAX's frontend serves it with the robot's) CLAUDE_MCP = ".rax-mcp.json" # the session's servers (claude.args: --mcp-config .rax-mcp.json) -PUBLISHED_PARTS = ("runs", "episode_reviews") # RAX's PUBLISHED_PARTS: the run tree the frontend writes +HOOK_FILE = "hook.json" # <run>/rax/hook.json: what the Stop hook asks the service with NOTES = ("memory", "code") # the session's notes and controller code, kept in the log DENIED_TOOLS = ("WebFetch", "WebSearch") # RAX's Claude Code launcher's SUBAGENT_TOOLS = ("Agent", "Task") # ...and these when the session's subagent cap is 0 ('Task': the old name) @@ -133,7 +137,8 @@ def agent_python(rax: Path) -> Path: def own(work: Path) -> Path: - """This run's RAX directory beside the workspace (<run>/rax): the socket, the run tree, the library repository.""" + """This run's RAX directory beside the workspace (<run>/rax): the socket's directory, the library repository, the + session's record and the Stop hook's files (its run tree is the service's: `prepare`).""" return Path(work).resolve().parent / "rax" @@ -270,13 +275,22 @@ def prepare(task: dict, work: Path, params: dict) -> list: # this one is not this session's, and is never removed. raise RuntimeError(f"{SOCKET_DIR} exists and is not this session's link: the RAX session runs in the task " "sandbox (sandbox.enabled), whose /tmp is its own") - shutil.rmtree(mine, ignore_errors=True) # a retry of the call starts its session afresh - for part in (*(f"published/{p}" for p in PUBLISHED_PARTS), "sock"): - (mine / part).mkdir(parents=True, mode=0o700) + (mine / "sock").mkdir(parents=True, exist_ok=True, mode=0o700) url = _service(params) + # The service refuses a workspace whose session spent anything (a RAX session is never started again): nothing an + # earlier attempt left is removed before it has accepted this one reply = _post(url + "/register", {"workspace": str(work), "task": task["id"]}) try: + for stale in ("library", "session.json", "relaunches", HOOK_FILE): # an earlier attempt's, which spent nothing + path = mine / stale + if path.is_dir() and not path.is_symlink(): + shutil.rmtree(path) + else: + path.unlink(missing_ok=True) _wire(task, work, params, rax, mine, reply) + # the Stop hook asks the service whether exploration is closed (stop_hook.py) + (mine / HOOK_FILE).write_text(json.dumps({"url": url, "workspace": str(work), + "session": str(reply.get("session") or "")}) + "\n") lease = _lease(url, str(work), str(reply.get("session") or "")) except BaseException: # No session follows (the call fails, and `collect` is not run): RAX's frontend is stopped now @@ -299,10 +313,10 @@ def _wire(task: dict, work: Path, params: dict, rax: Path, mine: Path, reply: di given = work / "START_PROMPT.md" if given.is_file() and given.read_text().strip() != expected: raise RuntimeError("RAX's workspace renders START_PROMPT.md otherwise than this port's prompt: re-pin RAX") - link = work / "runtime" / "autonomous_controller" # RAX's run tree, as its workspace names it + link = work / "runtime" / "autonomous_controller" # RAX's run tree, as its workspace names it: read-only here link.parent.mkdir(parents=True, exist_ok=True) link.unlink(missing_ok=True) - link.symlink_to(mine / "published", target_is_directory=True) + link.symlink_to(Path(reply["tree"]), target_is_directory=True) SOCKET_DIR.unlink(missing_ok=True) # a link of a run before this one (checked above) SOCKET_DIR.parent.mkdir(parents=True, exist_ok=True) SOCKET_DIR.symlink_to(mine / "sock", target_is_directory=True) @@ -365,7 +379,7 @@ def collect(task: dict, work: Path, log: Path, params: dict) -> dict: lease.close() facts = {"workspace": str(work), **{k: reply.get(k) for k in ("session", "submitted_bundle", "rehearsals", "exploration_used", "exploration_budget", - "gemini_usd")}, + "gemini_usd", "run_tree")}, **({"finish_error": reply["finish_error"]} if "finish_error" in reply else {})} record_path = own(work) / "session.json" record = json.loads(record_path.read_text()) if record_path.is_file() else {} diff --git a/hermit/agent/evolver/methods/rax/evolver.py b/hermit/agent/evolver/methods/rax/evolver.py index a0d5ce09..21d52550 100644 --- a/hermit/agent/evolver/methods/rax/evolver.py +++ b/hermit/agent/evolver/methods/rax/evolver.py @@ -23,5 +23,8 @@ class RaxEvolver(CommandEvolver): def step(self, ctx: StepContext) -> StepResult: + from hermit.hosts.inputs import PACKAGE_ROOT command = [sys.executable, "-m", "hermit.agent.evolver.methods.rax.merge"] - return super().step(dataclasses.replace(ctx, params={**ctx.params, "command": command})) + # this hermit's merge, not another one the interpreter has installed (as the task functions start their server) + env = {**(ctx.params.get("env") or {}), "PYTHONPATH": PACKAGE_ROOT} + return super().step(dataclasses.replace(ctx, params={**ctx.params, "command": command, "env": env})) diff --git a/hermit/agent/evolver/methods/rax/library.py b/hermit/agent/evolver/methods/rax/library.py index f33c9ab4..b08071d2 100644 --- a/hermit/agent/evolver/methods/rax/library.py +++ b/hermit/agent/evolver/methods/rax/library.py @@ -84,8 +84,10 @@ def located(repository: Path): def library_files(tree: Path) -> list[str]: """The library's files in `tree` (an adapter, or its copy in a workspace): README.md, INDEX.md and every file under - skills/ (none when there is no skills/: an empty library), as sorted POSIX paths. A link anywhere is refused: none - is ever read through.""" + skills/ (none when there is no skills/: an empty library), as sorted POSIX paths, without Python's caches (the + __pycache__ directories and .pyc files the deployment leaves out: hermit.hosts.inputs), so an adapter and its + deployed copy are the same library. A link anywhere is refused: none is ever read through.""" + from hermit.hosts.inputs import CACHES tree = Path(tree) found = [] for name in ROOT_FILES: @@ -101,7 +103,8 @@ def library_files(tree: Path) -> list[str]: for entry in [*dirs, *files]: if (here / entry).is_symlink(): raise rax.LibraryError(f"{(here / entry).relative_to(tree)}: links are not allowed in the library") - found += [(here / f).relative_to(tree).as_posix() for f in files] + dirs[:] = [d for d in dirs if d not in CACHES] + found += [(here / f).relative_to(tree).as_posix() for f in files if not f.endswith(".pyc")] return sorted(found) diff --git a/hermit/agent/evolver/methods/rax/stop_hook.py b/hermit/agent/evolver/methods/rax/stop_hook.py index 3d4ebc99..727836b6 100644 --- a/hermit/agent/evolver/methods/rax/stop_hook.py +++ b/hermit/agent/evolver/methods/rax/stop_hook.py @@ -3,44 +3,43 @@ MAX_RELAUNCHES times. RAX runs the CLI again on the same conversation; a Stop hook keeps the same CLI going, so the prompt leaves out RAX's clause that the turn's background workers were stopped (here they keep running). -Exploration is open as RAX's frontend says: its `status` names a `next_step` once exploration is closed (the bundle -submitted, or the episode budget spent with nothing running). The robot socket is the session's (RAX_MCP_SOCKET, by -the RAX task functions /tmp/rax/robot.sock). Anything that fails lets the turn end, as RAX ends a run it cannot -continue. Standard library only: the RAX task functions' `prepare` installs it as the session's Stop hook (Claude -Code's .claude/settings.json in the workspace), run by the framework's Python in isolated mode (-I: nothing of the -workspace is imported) in the session's workspace, and it keeps its count beside the workspace (<run>/rax/relaunches). +Exploration is open as RAX's launcher decides it (services/agent_formal/checkpoint.py `exploration_closed`: the marker +RAX's frontend writes once exploration is closed, or the submission), which the RAX service applies to the session's +directory on the host (POST /explored), never by asking the frontend, which a long call can keep busy. When the +service gives no answer, exploration counts as open, as RAX's launcher counts a session state it cannot read. The RAX +task functions' `prepare` installs it as the session's Stop hook (Claude Code's .claude/settings.json in the +workspace) and writes what it asks with beside the workspace (<run>/rax/hook.json: the service's URL, the workspace, +the service's name of the session); it keeps its count there too (<run>/rax/relaunches). Standard library only, run by +the framework's Python in isolated mode (-I: nothing of the workspace is imported) in the session's workspace. """ from __future__ import annotations import json -import os from pathlib import Path -import socket import sys +import urllib.request MAX_RELAUNCHES = 3 CONTINUE_PROMPT = ("Your previous turn ended while exploration is still open, and your open episodes kept running. " "Call status, reread memory/PROGRESS.md, and continue from the live state until exploration is " "closed.") -SOCKET = "/tmp/rax/robot.sock" +HOOK_FILE = "hook.json" -def status(path: str, timeout: float = 30.0) -> dict: - """RAX's `status` over the session's robot socket (newline-delimited JSON-RPC, as api/runtime.py speaks it).""" - with socket.socket(socket.AF_UNIX) as conn: - conn.settimeout(timeout) - conn.connect(path) - reader, writer = conn.makefile("r"), conn.makefile("w") - for ident, method, params in ((1, "initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, - "clientInfo": {"name": "rax-stop-hook", "version": "1"}}), - (2, "tools/call", {"name": "status", "arguments": {}})): - writer.write(json.dumps({"jsonrpc": "2.0", "id": ident, "method": method, "params": params}) + "\n") - writer.flush() - reply = json.loads(reader.readline(32 * 1024 * 1024)) - if "error" in reply: - raise RuntimeError(json.dumps(reply["error"])[:300]) - text = next(c["text"] for c in reply["result"]["content"] if c.get("type") == "text") - return json.loads(text) +def closed(mine: Path, timeout: float = 30.0) -> bool: + """Whether the session's exploration is closed, as the RAX service answers by RAX's rule (POST /explored), straight + to its loopback port (no proxy).""" + asked = json.loads((mine / HOOK_FILE).read_text()) + request = urllib.request.Request(str(asked["url"]).rstrip("/") + "/explored", method="POST", + data=json.dumps({"workspace": asked["workspace"], + "session": asked["session"]}).encode(), + headers={"Content-Type": "application/json"}) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open(request, timeout=timeout) as response: + reply = json.loads(response.read()) + if not reply.get("ok"): + raise RuntimeError(str(reply.get("error"))[:300]) + return bool(reply["closed"]) def main() -> int: @@ -48,15 +47,18 @@ def main() -> int: json.load(sys.stdin) # the host's hook input: nothing in it is needed except ValueError: pass - workspace = Path.cwd().resolve() # a hook runs where the session started: its workspace - count_file = workspace.parent / "rax" / "relaunches" + mine = Path.cwd().resolve().parent / "rax" # a hook runs where the session started: its workspace + count_file = mine / "relaunches" try: count = int(count_file.read_text().strip() or 0) if count_file.is_file() else 0 - value = status(os.environ.get("RAX_MCP_SOCKET") or SOCKET) - except Exception as exc: # no robot to ask: the turn ends + except (OSError, ValueError): + count = MAX_RELAUNCHES # a count that cannot be read: no relaunch is owed + try: + if closed(mine): + return 0 + except Exception as exc: # no answer: open, as RAX counts a state it cannot read print(f"rax stop hook: {type(exc).__name__}: {exc}", file=sys.stderr) - return 0 - if "next_step" in value or count >= MAX_RELAUNCHES: + if count >= MAX_RELAUNCHES: return 0 count_file.write_text(f"{count + 1}\n") print(json.dumps({"decision": "block", "reason": CONTINUE_PROMPT})) diff --git a/tests/methods/rax/test_rax.py b/tests/methods/rax/test_rax.py index 487b77e0..9bd40cd9 100644 --- a/tests/methods/rax/test_rax.py +++ b/tests/methods/rax/test_rax.py @@ -208,6 +208,12 @@ def test_a_library_built_from_the_same_files_is_the_same_commit(tmp_path): assert {line.split("\t")[1] for line in tree} == {*L.library_files(adapter), L.KEEP} (adapter / L.KEEP).write_text("") # an adapter a step wrote back holds main's .gitkeep assert L.build(adapter, tmp_path / "k" / L.ROBOT) == first + # Python's caches (a skill's code run in the adapter), which the deployment does not copy: not the library's + cache = adapter / "skills" / "grasp-bowl" / "code" / "__pycache__" + cache.mkdir() + (cache / "run.cpython-312.pyc").write_bytes(b"\0") + (adapter / "skills" / "grasp-bowl" / "code" / "run.pyc").write_bytes(b"\0") + assert L.build(adapter, tmp_path / "p" / L.ROBOT) == first with open(adapter / "INDEX.md", "a") as f: f.write("\n") assert L.build(adapter, tmp_path / "c" / L.ROBOT) != first @@ -341,62 +347,47 @@ def test_the_merge_tool_serves_on_stdio_as_the_sessions_mcp_configuration_starts # ---------- the Stop hook ---------- -class Robot: - """The session's robot socket as RAX's frontend serves `status` on it (newline-delimited JSON-RPC).""" - - def __init__(self, path: Path, status: dict): - self.status, self.path = status, path - self.server = socket.socket(socket.AF_UNIX) - self.server.bind(str(path)) - self.server.listen() - threading.Thread(target=self._serve, daemon=True).start() - - def _serve(self): - while True: - try: - conn, _ = self.server.accept() - except OSError: - return - with conn, conn.makefile("r") as reader, conn.makefile("w") as writer: - for line in reader: - request = json.loads(line) - result = ({"content": [{"type": "text", "text": json.dumps(self.status)}]} - if request["method"] == "tools/call" else {"protocolVersion": "2025-06-18"}) - writer.write(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}) + "\n") - writer.flush() - - def close(self): - self.server.close() - - -def test_the_stop_hook_continues_an_open_exploration_at_most_three_times(tmp_path): - """While RAX's status names no next step, the turn's end is blocked with RAX's continue prompt, at most three - times (RAX's MAX_RELAUNCHES); once exploration is closed, or with no robot to ask, the turn ends.""" - work = tmp_path / "run" / "work" - work.mkdir(parents=True) - (tmp_path / "run" / "rax").mkdir() - path = tmp_path / "r.sock" - robot = Robot(path, {"exploration_remaining": 4}) +def test_the_stop_hook_continues_an_open_exploration_at_most_three_times(tmp_path, service): + """While RAX's launcher's rule says exploration is open (the service's /explored: RAX's marker of a closed + exploration, or the submission), the turn's end is blocked with RAX's continue prompt, at most three times (RAX's + MAX_RELAUNCHES); once it is closed the turn ends. The hook never asks the frontend (a robot socket that takes the + call and never answers, as RAX's frontend while a long call holds it, is not waited on), and a service that gives + no answer counts as open, as RAX counts a session state it cannot read.""" + service.state = {} # nothing submitted yet + work = _registration(tmp_path, f"{TASK}-0c0c0c0c", f"{TASK}-1d1d1d1d") + reply = service.register({"workspace": str(work), "task": TASK}) + mine = work.parent / "rax" + asked = {"url": service.url, "workspace": str(work), "session": reply["session"]} + (mine / H.HOOK_FILE).write_text(json.dumps(asked)) + robot = socket.socket(socket.AF_UNIX) # takes connections, answers nothing + robot.bind(str(tmp_path / "r.sock")) + robot.listen() def hook(): done = subprocess.run([sys.executable, "-I", str(METHOD / "stop_hook.py")], input='{"hook_event_name":"Stop"}', - capture_output=True, text=True, cwd=work, timeout=60, - env={**os.environ, "RAX_MCP_SOCKET": str(path)}) + capture_output=True, text=True, cwd=work, timeout=20, + env={**os.environ, "RAX_MCP_SOCKET": str(tmp_path / "r.sock")}) assert done.returncode == 0, done.stderr return json.loads(done.stdout) if done.stdout.strip() else None try: for n in (1, 2, 3): assert hook() == {"decision": "block", "reason": H.CONTINUE_PROMPT} - assert (tmp_path / "run" / "rax" / "relaunches").read_text().strip() == str(n) - assert hook() is None - (tmp_path / "run" / "rax" / "relaunches").write_text("0\n") - robot.status = {"next_step": "Exploration is closed: end your turn."} + assert (mine / "relaunches").read_text().strip() == str(n) + assert hook() is None # three relaunches: the turn ends + (mine / "relaunches").write_text("0\n") + (service.made[0] / "exploration-complete.json").write_text("{}") # RAX's frontend closed exploration assert hook() is None + (service.made[0] / "exploration-complete.json").unlink() + (service.made[0] / "state.json").write_text(json.dumps({"submission": {"bundle": "b1"}})) + assert hook() is None # the bundle submitted + assert A._post(service.url + "/explored", {"workspace": str(work), "session": reply["session"]})["closed"] + with pytest.raises(RuntimeError, match="no session of this workspace by that name"): + A._post(service.url + "/explored", {"workspace": str(work), "session": "another"}) + (mine / H.HOOK_FILE).write_text(json.dumps({**asked, "url": "http://127.0.0.1:9"})) # no service answers + assert hook() == {"decision": "block", "reason": H.CONTINUE_PROMPT} finally: robot.close() - path.unlink() - assert hook() is None # no robot: the turn ends assert "Your previous turn ended while exploration is still open" in H.CONTINUE_PROMPT @@ -495,8 +486,17 @@ def service(tmp_path, rax_root, monkeypatch): monkeypatch.setattr(sys, "path", [*sys.path]) # the service puts RAX's checkout first contract = ModuleType("services.mcp_contract") contract.Contract = SimpleNamespace(from_config=lambda config: SimpleNamespace(subagent_cap=0)) - monkeypatch.setitem(sys.modules, "services", ModuleType("services")) - monkeypatch.setitem(sys.modules, "services.mcp_contract", contract) + checkpoint = ModuleType("services.agent_formal.checkpoint") # RAX's exploration_closed, as it reads a session + checkpoint.exploration_closed = lambda config: (config.root / "exploration-complete.json").is_file() or bool( + json.loads((config.root / "state.json").read_text()).get("submission")) + frontend = ModuleType("services.controller.frontend") + frontend.load_configuration = lambda path: SimpleNamespace(root=Path(path).parent) + for name, module in (("services", ModuleType("services")), ("services.mcp_contract", contract), + ("services.agent_formal", ModuleType("services.agent_formal")), + ("services.agent_formal.checkpoint", checkpoint), + ("services.controller", ModuleType("services.controller")), + ("services.controller.frontend", frontend)): + monkeypatch.setitem(sys.modules, name, module) for name in ("NO_PROXY", "no_proxy"): monkeypatch.setenv(name, "127.0.0.1,localhost") args = SimpleNamespace(rax_root=rax_root, workspaces=[tmp_path / "logs"], state=tmp_path / "state", @@ -522,9 +522,9 @@ def workspace(_): "START_PROMPT.md": (CODE_MODE + "\n").encode(), ".agents/skills/robot-tools/SKILL.md": b"tools\n"} return SimpleNamespace(root=root, training=SimpleNamespace(cpus=2)), _tar(files) - def start(config, workspace_, mine): + def start(config, workspace_, mine, tree): frontend = Frontend(config.root, svc.state) - frontend.pid, frontend.workspace, frontend.mine = None, workspace_, mine + frontend.pid, frontend.workspace, frontend.mine, frontend.tree = None, workspace_, mine, tree svc.frontends_started.append(frontend) return frontend @@ -546,7 +546,7 @@ def start(config, workspace_, mine): # skill's files are in the script itself: a task sandbox shows the CLI, not the files beside it. SKILL_JSON = json.dumps({k: base64.b64encode(v).decode() for k, v in skill_files("grasp-bowl").items()}) FAKE_CLAUDE = f'''#!{sys.executable} -import base64, json, os, subprocess, sys +import base64, errno, json, os, subprocess, sys from pathlib import Path SKILL = {SKILL_JSON!r} args = sys.argv[1:] @@ -560,6 +560,16 @@ def start(config, workspace_, mine): "run_tree": os.readlink("runtime/autonomous_controller"), "socket_dir": os.readlink(os.path.dirname( json.loads(Path(".claude/settings.json").read_text())["env"]["RAX_MCP_SOCKET"]))}} +def refused(call): + try: + call() + return None + except OSError as exc: + return errno.errorcode.get(exc.errno, str(exc.errno)) +tree = Path("runtime/autonomous_controller") +saw["run_tree_parts"] = sorted(p.name for p in tree.iterdir()) +saw["run_tree_write"] = refused(lambda: (tree / "runs" / "forged.json").write_text("{{}}")) +saw["run_trees_listed"] = refused(lambda: os.listdir(os.path.dirname(os.readlink(tree)))) servers = json.loads(Path(args[args.index("--mcp-config") + 1]).read_text())["mcpServers"] saw["servers"] = servers library = Path("skill-library/skills") @@ -657,7 +667,11 @@ def test_a_rax_session_runs_on_the_frameworks_claude_code_agent_and_its_merges_r assert sorted(saw["servers"]) == [A.MCP_SERVER, A.LIBRARY_SERVER], saw.get("merge_stderr") merged = json.loads(saw["merge"][1]["result"]["content"][0]["text"]) assert merged["merged"] and merged["skills"] == ["grasp-bowl"], saw["merge"] - assert saw["run_tree"] == str(work.parent / "rax" / "published") # links out of the workspace, removed after + tree = service.frontends_started[0].tree # the service's, bound onto RAX's published/ for its frontend + assert saw["run_tree"] == str(tree) == out.extra["task"]["run_tree"] + assert saw["run_tree_parts"] == ["episode_reviews", "runs"] and tree.parent == tmp_path / "state" / "run-trees" + assert stat.S_IMODE(tree.parent.stat().st_mode) == 0o300 + assert saw["run_trees_listed"] == ("EACCES" if os.geteuid() else None) # no session can list the others' trees assert saw["socket_dir"] == str(work.parent / "rax" / "sock") == os.readlink(socket_dir) assert not (work / "runtime" / "autonomous_controller").is_symlink() # links out: removed after the run @@ -749,6 +763,25 @@ def test_prepare_refuses_another_agent_a_foreign_socket_directory_and_ends_a_ses assert ledger[str(work.resolve())]["finished"] and service.frontends_started[0].stops == 1 +def test_a_call_run_again_on_a_session_that_spent_something_is_refused_and_removes_nothing( + tmp_path, rax_root, socket_dir, service, claude): + """A second attempt of a call whose session started an episode: the service refuses it (a RAX session is never + started again) before `prepare` removes anything the first left (its library repository, its record, the Stop + hook's files), so the session's own record stays as it was.""" + from hermit.task import load_pipeline + run = load_pipeline("hermit.agent.acting.workspace:run", EXAMPLE, _params(tmp_path, rax_root, f"{TASK}-2468aceb")) + out = run(_row(TASK), seed(tmp_path)) # the stand-in session: two episodes, a bundle submitted + work = Path(out.extra["workspace"]) + mine = work.parent / "rax" + (mine / "relaunches").write_text("2\n") + kept = {p.relative_to(mine).as_posix(): p.read_bytes() for p in mine.rglob("*") if p.is_file()} + assert {"session.json", H.HOOK_FILE, "relaunches"} <= set(kept) and any(k.startswith("library/") for k in kept) + work.mkdir(exist_ok=True) + with pytest.raises(RuntimeError, match="never started again"): + A.prepare({"id": TASK}, work, {"backend": "claude", "rax_root": str(rax_root)}) + assert {p.relative_to(mine).as_posix(): p.read_bytes() for p in mine.rglob("*") if p.is_file()} == kept + + def test_collect_keeps_the_session_when_the_service_cannot_end_it(tmp_path, monkeypatch): """The service gone: the facts say so, and the library's merges and the notes are still kept.""" adapter = seed(tmp_path) @@ -771,6 +804,24 @@ def test_collect_keeps_the_session_when_the_service_cannot_end_it(tmp_path, monk # ---------- the Evolver ---------- +def test_the_evolver_runs_this_hermits_merge_program(tmp_path, monkeypatch): + """The merge program is this checkout's (its package root first on PYTHONPATH, as the task functions start their + server), with the config's own variables kept.""" + from hermit.agent.evolver import loader + from hermit.agent.evolver.agent import CommandEvolver + from hermit.agent.evolver.base import Access, StepContext, Workspace + from hermit.hosts.inputs import PACKAGE_ROOT + ran = {} + monkeypatch.setattr(CommandEvolver, "step", lambda self, ctx: ran.update(ctx.params) or "ran") + places = {k: tmp_path / k for k in ("task_info", "history", "state", "scratch", "output")} + evolver, params = loader.instantiate(loader.find("rax"), {"env": {"GIT_TRACE": "0"}}) + ctx = StepContext(workspace=Workspace(adapter=tmp_path / "a", learning_material=tmp_path / "m", **places), + access=Access(), tools={}, params=params) + assert evolver.step(ctx) == "ran" + assert ran["command"] == [sys.executable, "-m", "hermit.agent.evolver.methods.rax.merge"] + assert ran["env"] == {"GIT_TRACE": "0", "PYTHONPATH": PACKAGE_ROOT} + + def test_the_evolver_takes_in_the_steps_sessions_in_order_and_says_why_it_left_one_out(tmp_path, monkeypatch): """Two sessions of one step from the same library: the first is merged, the second's index row conflicts with it (RAX's merge aborts and names INDEX.md); a session that started from another library, one that merged nothing and @@ -891,8 +942,8 @@ def _registration(tmp_path, rollout: str, inner: str, *, made: bool = True) -> P """A rollout's workspace where the framework makes it, with the run directory `prepare` makes beside it.""" work = tmp_path / "logs" / "acting" / rollout / "workspaces" / inner / "work" work.mkdir(parents=True, exist_ok=True) - for part in ("published/runs", "published/episode_reviews", "sock") if made else (): - (work.parent / "rax" / part).mkdir(parents=True, exist_ok=True) + if made: + (work.parent / "rax" / "sock").mkdir(parents=True, exist_ok=True) return work @@ -1112,8 +1163,9 @@ def test_the_judge_runs_the_formal_batch_on_raxs_python_without_raxs_session_var def test_the_configs_run_raxs_session_on_claude_code_in_the_task_sandbox_with_their_splits(tmp_path, rax_root, monkeypatch): """Every config: RAX's task functions on the Claude Code agent, one session at a time, RAX's session variables, - no web tools, the task sandbox required and shown only RAX's agent Python, bridge and start prompt, the judge on - the host, the rax template and Evolver; training on the train split, and each evaluation on its own split.""" + no web tools, one attempt, the task sandbox required and shown only RAX's agent Python, bridge and start prompt + and the service's run trees (read-only), the judge on the host, the rax template and Evolver; training on the + train split, and each evaluation on its own split.""" from hermit.agent.acting import workspace as cli from hermit.config import Config monkeypatch.setenv("RAX_ROOT", str(rax_root)) @@ -1137,7 +1189,9 @@ def test_the_configs_run_raxs_session_on_claude_code_in_the_task_sandbox_with_th assert params["web_search"] is False and params["args"] == ["--mcp-config", A.CLAUDE_MCP, "--strict-mcp-config"] assert params["env"] == run_env and params["rax_root"] == "$RAX_ROOT", name assert d["environment"]["read"] == ["$RAX_ROOT/runtime/envs/host", "$RAX_ROOT/harness/mcp_bridge.py", - "$RAX_ROOT/auto_research_agent/START_PROMPT.md"], name + "$RAX_ROOT/auto_research_agent/START_PROMPT.md", + "$RAX_STATE/run-trees"], name + assert params["retries"] == 1, name # a second attempt would start RAX's session again assert d["environment"]["env"] == ["RAX_SERVICE_URL"] assert d["sandbox"]["enabled"] is True and d["sandbox"]["enforce"] == "required" assert config.path(d["judge"]["path"]) == (EXAMPLE / "judge.py").resolve() and d["judge"]["mode"] == "host" @@ -1298,6 +1352,9 @@ def test_a_run_trains_through_the_trainer_in_the_sandboxes_and_evaluates_its_fin [trained] = (tmp_path / "logs").glob("*/smoke-libero_spatial_0-*/workspaces/*/saw.json") saw = json.loads(trained.read_text()) assert saw["library"] == [] and saw["socket_dir"] == str(trained.parent / "rax" / "sock") + # its run tree in the task sandbox: read, never written, and the other sessions' trees never listed + assert saw["run_tree_parts"] == ["episode_reviews", "runs"] and saw["run_tree_write"] == "EROFS" + assert saw["run_trees_listed"] == ("EACCES" if os.geteuid() else None) merged = json.loads(saw["merge"][1]["result"]["content"][0]["text"]) assert merged["merged"] and merged["skills"] == ["grasp-bowl"], saw.get("merge_stderr") From ccac84ed0b103066ea320c37fc3f272137592a27 Mon Sep 17 00:00:00 2001 From: iamziyuzhao <iamziyuzhao@gmail.com> Date: Sun, 29 Nov 2026 14:27:51 -0500 Subject: [PATCH 4/7] RAX: the Stop hook given its directory; a broken library or a key kept out, not fatal Round 2 of the post-PR audit (4f3158f): no P1, 1 P2, 8 P3. - The Stop hook is given the run's RAX directory by its path. It found it from the current directory, which follows the agent's cd in Claude Code: after a cd the hook failed and the turn ended with exploration open. A relaunch count it cannot write now ends the turn, not the hook. - The Evolver undoes a merge RAX's merge accepts that leaves no library (INDEX.md deleted, a link straight under skills/), says why, and goes on with the step's other sessions; a git that times out is a reason too. - collect records a library it cannot export, or a session record it cannot read, and the session is still judged. - The export holds back a session's merges whose git objects carry the value of a key the session was given: Hermit's redaction scrubs files, not git's compressed objects. - The merge tool's errors have RAX's public_failure shape. - The service makes the run trees' directory listable again when it stops, so a run can be removed; the README says what to do after a killed one. - The tests pin RAX's LICENSE and NOTICE too (from its main: 36c926c has neither). - Method page: the setup snippet has claude.retries and the run trees; the permission model (bypassPermissions in the task sandbox in place of RAX's acceptEdits, allow list and Claude Code sandbox); a session Hermit's clock ends is judged, RAX resumes its conversations after errors and usage limits; the library's guarantee is the Evolver's and the template's checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/methods/rax.md | 43 +++-- examples/libero/rax/README.md | 4 +- examples/libero/rax/eval_official.yaml | 2 +- examples/libero/rax/eval_val.yaml | 2 +- examples/libero/rax/run.yaml | 2 +- examples/libero/rax/service.py | 19 ++- examples/libero/rax/smoke.yaml | 2 +- hermit/agent/evolver/methods/rax/actor.py | 37 +++-- hermit/agent/evolver/methods/rax/library.py | 83 ++++++++-- .../evolver/methods/rax/library_server.py | 29 +++- hermit/agent/evolver/methods/rax/merge.py | 13 +- hermit/agent/evolver/methods/rax/stop_hook.py | 25 ++- tests/methods/rax/test_rax.py | 148 ++++++++++++++++-- 13 files changed, 336 insertions(+), 73 deletions(-) diff --git a/docs/methods/rax.md b/docs/methods/rax.md index 8b4ff114..b74b7fb9 100644 --- a/docs/methods/rax.md +++ b/docs/methods/rax.md @@ -28,9 +28,14 @@ agent: answer: hermit.agent.evolver.methods.rax.actor:answer collect: hermit.agent.evolver.methods.rax.actor:collect rax_root: $RAX_ROOT - claude: {web_search: false, args: [--mcp-config, .rax-mcp.json, --strict-mcp-config], env: {MCP_TOOL_TIMEOUT: "1728300000", ...}} -environment: # the task sandbox: RAX's agent Python, bridge and start prompt - read: [$RAX_ROOT/runtime/envs/host, $RAX_ROOT/harness/mcp_bridge.py, $RAX_ROOT/auto_research_agent/START_PROMPT.md] + claude: # RAX's Claude Code session + web_search: false + retries: 1 # one attempt: a second would start the session again + args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] + env: {MCP_TOOL_TIMEOUT: "1728300000", ...} +environment: # the task sandbox: RAX's agent Python, bridge, start prompt, run trees + read: [$RAX_ROOT/runtime/envs/host, $RAX_ROOT/harness/mcp_bridge.py, $RAX_ROOT/auto_research_agent/START_PROMPT.md, + $RAX_STATE/run-trees] env: [RAX_SERVICE_URL] judge: {path: judge.py} # on the host: RAX's formal batch of the submitted bundle evolver: {name: rax} @@ -44,7 +49,7 @@ splits and the host service; its README gives RAX's setup and the commands. `rax` is RAX's skill library as RAX's `services/skill_library.py` lays it out (robot-agent-exploration/rax `real/rainbow` 36c926c, vendored unchanged in `hermit/agent/evolver/methods/rax/upstream/` with RAX's license and -notice): `README.md` (RAX's, for this robot), `INDEX.md` (one row per skill) and `skills/<slug>/` with `SKILL.md` +notice, from its `main`: 36c926c has neither): `README.md` (RAX's, for this robot), `INDEX.md` (one row per skill) and `skills/<slug>/` with `SKILL.md` (frontmatter `name`, `description`, `status` draft, verified or deprecated, `robot`, `entry`; RAX's sections), `code/` (an entry `main(ctx, ...)` returning `{ok, measured, why}`) and `evidence/` (`runs.jsonl`, at least one image; a `verified` skill has two unattended successful runs with images). `INDEX.md` and `skills/**` are learnable; the rest is @@ -80,14 +85,16 @@ The session runs in the task sandbox (`hermit/agent/evolver/methods/rax/actor.py service, writes RAX's workspace beside the deployment, and wires Claude Code as RAX's Claude Code launcher does: `CLAUDE.md` reads `AGENTS.md`, `.claude/skills` is `.agents/skills`, RAX's bridge (`harness/mcp_bridge.py`) to the socket as the MCP server `auto_research`, RAX's agent environment for its commands (RAX's Python first, the robot -socket, offline package tools, thread limits) and RAX's relaunch policy as a Stop hook (`stop_hook.py`: whether -exploration is closed is RAX's launcher's own rule, `exploration_closed`, which the service applies to the session's -directory; a service that does not answer counts as open). With an adapter it builds the session's library repository -from the adapter's files, clones it with RAX's `checkout`, and serves `skill_library_merge` (`library_server.py`: RAX's -name, description, schema and refusal, and RAX's `merge` against that repository). The prompt is RAX's `START_PROMPT.md` -in code mode. `collect` ends the session at the service and writes what the session merged into its library (a git -bundle of the repository's main past its first commit, made in a fresh repository from copied objects) and the session's -notes and code into the log. The judge, on the host, runs RAX's formal batch of the submitted bundle (the supervisor's +socket, offline package tools, thread limits) and RAX's relaunch policy as a Stop hook (`stop_hook.py`, given +`<run>/rax` by its path, since a hook runs wherever the agent's shell has gone: whether exploration is closed is RAX's +launcher's own rule, `exploration_closed`, which the service applies to the session's directory; a service that does not +answer counts as open). With an adapter it builds the session's library repository from the adapter's files, clones it +with RAX's `checkout`, and serves `skill_library_merge` (`library_server.py`: RAX's name, description, schema and +refusal, and RAX's `merge` against that repository). The prompt is RAX's `START_PROMPT.md` in code mode. `collect` ends +the session at the service and writes what the session merged into its library (a git bundle of the repository's main +past its first commit, made in a fresh repository from copied objects; none when those objects hold the value of a key +the session was given, which Hermit's redaction cannot scrub out of git's compressed objects) and the session's notes +and code into the log. The judge, on the host, runs RAX's formal batch of the submitted bundle (the supervisor's `run_submission`, `formal.py`) on the row's formal layouts: the share of successful episodes, LIBERO's own binary check, errors counted as failures. @@ -114,7 +121,9 @@ flowchart TD 3. The Evolver (`merge.py`, a program in the evolver sandbox) builds a repository from the adapter (one commit of its library files, with a fixed identity and date, so it is the commit the session started from), fetches each session's bundle onto `session/<name>` and runs RAX's merge, which checks every changed skill again. A session that - started from another library, or whose bundle is not what it recorded, is not taken in. + started from another library, or whose bundle is not what it recorded, is not taken in; a merge that leaves no + library this port can keep as an adapter (`INDEX.md` gone, a link: RAX's merge checks only the skills a branch + changed) is undone, and the step goes on without that session. 4. The merged main's `INDEX.md` and `skills/` are the next adapter, checked by the template's check. The final adapter is the library after the last session. A step of several sessions merges them in order; a session @@ -138,11 +147,11 @@ URL, default `RAX_SERVICE_URL`) and `bin` (the CLI). The session's settings are | Dimension | RAX (robot-agent-exploration/rax) | This port | Why | |---|---|---|---| | Code | `libero-pro/native` 1767412 (LIBERO); the skill library of `real/rainbow` 36c926c | the same commits: RAX's operator script, workspace, frontend, supervisor, simulators, formal batch and skill library, unchanged | — | -| Agent | Claude Code, Claude Opus 5.5 at xhigh, its own home, its servers alone (`--strict-mcp-config`); denied: the web tools, the subagent tools at a subagent cap of 0, edits of the workspace's `.claude/` and `.mcp.json`; its commands in Claude Code's own sandbox (writes in the workspace and the socket's directory) | the same model, effort, flags and deny rules (the project's `.claude/settings.json`, with `.rax-mcp.json` guarded too), on Hermit's Claude Code agent; its commands in the task sandbox (bubblewrap), so a command, unlike a file tool, can still write `.claude/`, and what it writes there runs in the same sandbox | the task sandbox is the boundary | +| Agent | Claude Code, Claude Opus 5.5 at xhigh, its own home, its servers alone (`--strict-mcp-config`); `acceptEdits` with an allow list (its MCP server, reads of its readable paths); denied: the web tools, the subagent tools at a subagent cap of 0, edits of the workspace's `.claude/` and `.mcp.json`; its commands in Claude Code's own sandbox, allowed without asking (writes in the workspace and the socket's directory, no network) | the same model, effort, MCP flags and deny rules (the project's `.claude/settings.json`, with `.rax-mcp.json` guarded too), on Hermit's Claude Code agent, whose `bypassPermissions` takes the place of RAX's `acceptEdits`, allow list and Claude Code sandbox: the CLI and all it runs are in the task sandbox (bubblewrap), which shows only declared paths, lets it write only its run's directory (workspace, the CLI's home, log, `<run>/rax`) and its own `/tmp`, and reaches only the model provider's hosts and the service's forwarded port; so a command, unlike a file tool, can still write `.claude/`, and what it writes there runs in the same sandbox | the task sandbox is the boundary | | Prompt and workspace | `START_PROMPT.md`; `prepare_workspace` | the same, byte for byte; with an adapter, the library's clone, RAX's continual-learning skill and the two library paragraphs of `real/rainbow`'s `AGENTS.md` (`ADAPTER.md`) | the library is `real/rainbow`'s, which `libero-pro/native` lacks | | Robot tools | RAX's frontend, through RAX's bridge on a socket | the same, on the host; the run tree in the service's directory, shown read-only in the task sandbox (RAX's agent writes only its workspace and the socket's directory) | the task sandbox shows only declared paths | | Relaunch | the launcher runs the CLI again (`--resume`) with `CONTINUE_PROMPT` while exploration is open, at most 3 times | a Stop hook continues the same CLI with the same prompt, without its clause about stopped background workers (here they run on); exploration closed by the launcher's own rule (`exploration_closed`), which the service applies | Hermit runs one CLI per call | -| Error relaunch, adaptation stage | relaunch after a provider error; up to 5 adaptation episodes on swap layouts (collection 6) | not ported: a session the provider stops serving ends there, scored 0 with its merges left out (Hermit judges no failed session, even one that submitted); Hermit's own second attempt is off (`claude.retries: 1`): it would remove the session's workspace and log and start the session again, which RAX never does; no adaptation | Hermit runs one CLI per call; scope | +| Error relaunch, adaptation stage | after a provider error, the same conversation resumed after a pause (`ERROR_PROMPT`, up to 5 in a row); after the login's usage limit, the same conversation resumed once the window resets (`USAGE_PROMPT`, up to 10 times); up to 5 adaptation episodes on swap layouts (collection 6) | in part: a session the login's plan refuses (its usage window) runs again in the same workspace once the plan allows (Hermit's Claude Code agent, `plan_rerun`), as a new conversation from RAX's start prompt, not RAX's resumed one: RAX's session, its budget and the agent's notes (`memory/PROGRESS.md`, which RAX's prompts send it back to) are as they were, the conversation's context is not. A session the CLI reports as failed (an error result, a crash) is scored 0 without its bundle judged (Hermit judges no failed session), and its merges are taken in; one Hermit's clock ends is judged as any other; one the provider stops serving past Claude Code's own retries fails the call before `collect`: scored 0, its merges left out. Hermit's second attempt of a call is off (`claude.retries: 1`): it would remove the session's workspace and log and start the session again, which RAX never does. No adaptation | Hermit runs one CLI per call and resumes no conversation; scope | | Agent pause | the agent CLI and its processes are stopped (SIGSTOP) while a bundle is copied and rehearsed | not paused: the main turn waits on the call, but background commands and subagents run on; the bundle copied is the registered snapshot | the CLI's processes are in the task sandbox's process namespace, which the host's frontend cannot signal | | Bundles | run at the agent's workspace path, in a fresh bubblewrap sandbox and simulator per episode | run at RAX's session workspace path (not the Hermit workspace's); the same sandbox, which shows none of the skill library: `ADAPTER.md` says to copy into the bundle what it uses of a library skill | RAX's supervisor names that path; RAX's library comes from `real/rainbow`, whose controllers run in the agent's workspace | | Exploration | ≤ 20 episodes on fresh layouts (`env.seed(1000 + i)`), two environments, 600 s + 5 s per step | the same; each split's layouts its own (train 100-119, val 200-219, test 0-19) | disjoint splits | @@ -159,7 +168,9 @@ The session never sees its formal layouts, their scores or another session's: th the Evolver reads only what each session merged (no scores, no evaluation frames). The test split's swap states are neither played nor scored by any training or validation session; `TASK.md` says, as RAX's does for every LIBERO-PRO session, that formal layouts may swap objects. The library is the only thing a session leaves the next, and every -skill in it passed RAX's checks twice (in the session and in the Evolver). RAX's evidence is the agent's own record: +skill in it passed RAX's merge in the Evolver (over each skill a session changed) and the template's check (over every +skill); the session's merge tool runs the same checks, but the session can also write its repository directly, so +only these two hold. RAX's evidence is the agent's own record: the checks hold its format, not that the runs happened. The service trusts a session only with its workspace and task: it registers the one workspace the framework makes for a diff --git a/examples/libero/rax/README.md b/examples/libero/rax/README.md index 5f674daa..17c0dfed 100644 --- a/examples/libero/rax/README.md +++ b/examples/libero/rax/README.md @@ -111,7 +111,9 @@ every session the empty library, its clone and the merge tool. Runs go to `RAX_O trainer's records, the sessions' logs (`actor-logs/`: the CLI's stream, the session's notes and code, its library bundle), the service's ledger and log (`rax-service/`, `rax-service.log`), and each session's run tree, its exploration's frames and traces (`rax-service/run-trees/<random>`, `run_tree` in its facts: the task sandbox shows the -trees read-only and cannot list them). RAX's own session directories (its state, bundles and formal reports) stay +trees read-only and cannot list them; the service makes their directory unlistable while it runs and listable again +when it stops, so after a service that was killed, `chmod u+r "$RAX_OUT/rax-service/run-trees"` before removing a +run). RAX's own session directories (its state, bundles and formal reports) stay under `$RAX_ROOT/runtime/auto-research/`, named in the ledger. One launch at a time on a `RAX_OUT`: its service holds a lock in `rax-service/`, and a service started after one that was killed first ends the sessions that one left open. diff --git a/examples/libero/rax/eval_official.yaml b/examples/libero/rax/eval_official.yaml index 2f1eacf1..082a1b75 100644 --- a/examples/libero/rax/eval_official.yaml +++ b/examples/libero/rax/eval_official.yaml @@ -27,7 +27,7 @@ agent: # and RAX never starts a session again (docs/methods/rax.md) args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] # RAX's: only the session's servers (prepare writes them) env: # RAX's Claude Code session (harness/claude_cli/auto_research.py agent_environment) - MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: (CALL_SECONDS + 300) ms + MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: CALL_SECONDS + 300 s in ms BASH_MAX_TIMEOUT_MS: "1728000000" DISABLE_AUTOUPDATER: "1" CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: "0" diff --git a/examples/libero/rax/eval_val.yaml b/examples/libero/rax/eval_val.yaml index dc30294f..11fce057 100644 --- a/examples/libero/rax/eval_val.yaml +++ b/examples/libero/rax/eval_val.yaml @@ -28,7 +28,7 @@ agent: # and RAX never starts a session again (docs/methods/rax.md) args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] # RAX's: only the session's servers (prepare writes them) env: # RAX's Claude Code session (harness/claude_cli/auto_research.py agent_environment) - MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: (CALL_SECONDS + 300) ms + MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: CALL_SECONDS + 300 s in ms BASH_MAX_TIMEOUT_MS: "1728000000" DISABLE_AUTOUPDATER: "1" CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: "0" diff --git a/examples/libero/rax/run.yaml b/examples/libero/rax/run.yaml index 8f3543f7..f650276a 100644 --- a/examples/libero/rax/run.yaml +++ b/examples/libero/rax/run.yaml @@ -37,7 +37,7 @@ agent: # and RAX never starts a session again (docs/methods/rax.md) args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] # RAX's: only the session's servers (prepare writes them) env: # RAX's Claude Code session (harness/claude_cli/auto_research.py agent_environment) - MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: (CALL_SECONDS + 300) ms + MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: CALL_SECONDS + 300 s in ms BASH_MAX_TIMEOUT_MS: "1728000000" DISABLE_AUTOUPDATER: "1" CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: "0" diff --git a/examples/libero/rax/service.py b/examples/libero/rax/service.py index d8c92e72..eb089d2d 100644 --- a/examples/libero/rax/service.py +++ b/examples/libero/rax/service.py @@ -415,15 +415,22 @@ def lease_ended(self, key: str, session: str) -> None: self._end(entry, frontend, abandoned=True) def stop(self) -> None: - """The service's end (launch.sh's trap): every session still open is ended.""" + """The service's end (launch.sh's trap): every session still open is ended, and the run trees' directory can be + listed again (a run is removed with `rm -rf`; a service started on the same state hides it again).""" with self.ledger.lock: open_ = [(self.ledger.data.get(k), f) for k, f in self.frontends.items()] self.frontends.clear() - for entry, frontend in open_: - if entry is not None: - self._end(entry, frontend) - else: - frontend.stop() + try: + for entry, frontend in open_: + if entry is not None: + self._end(entry, frontend) + else: + frontend.stop() + finally: + try: + self.trees.chmod(0o700) + except OSError: # removed under it: nothing to show again + pass def handler(service: Service): diff --git a/examples/libero/rax/smoke.yaml b/examples/libero/rax/smoke.yaml index a7872e63..5707267e 100644 --- a/examples/libero/rax/smoke.yaml +++ b/examples/libero/rax/smoke.yaml @@ -29,7 +29,7 @@ agent: # and RAX never starts a session again (docs/methods/rax.md) args: [--mcp-config, .rax-mcp.json, --strict-mcp-config] # RAX's: only the session's servers (prepare writes them) env: # RAX's Claude Code session (harness/claude_cli/auto_research.py agent_environment) - MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: (CALL_SECONDS + 300) ms + MCP_TOOL_TIMEOUT: "1728300000" # a robot call (a rehearsal) may block for days: CALL_SECONDS + 300 s in ms BASH_MAX_TIMEOUT_MS: "1728000000" DISABLE_AUTOUPDATER: "1" CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: "0" diff --git a/hermit/agent/evolver/methods/rax/actor.py b/hermit/agent/evolver/methods/rax/actor.py index 574e599d..285f9986 100644 --- a/hermit/agent/evolver/methods/rax/actor.py +++ b/hermit/agent/evolver/methods/rax/actor.py @@ -215,10 +215,12 @@ def servers(rax: Path, work: Path, with_library: bool) -> dict: return out -def stop_hook() -> dict: - """RAX's relaunch policy as the session's Stop hook (stop_hook.py), on the framework's Python in isolated mode.""" +def stop_hook(mine: Path) -> dict: + """RAX's relaunch policy as the session's Stop hook (stop_hook.py), on the framework's Python in isolated mode, + given the run's RAX directory (`own`) by its path: Claude Code runs a hook in the shell's current directory, which + follows the agent's `cd`.""" return {"type": "command", "timeout": 60, - "command": f"{shlex.quote(sys.executable)} -I {shlex.quote(str(HERE / 'stop_hook.py'))}"} + "command": " ".join(shlex.quote(str(a)) for a in (sys.executable, "-I", HERE / "stop_hook.py", mine))} def permissions(work: Path, subagents: int) -> dict: @@ -258,7 +260,7 @@ def wire_claude(work: Path, rax: Path, env: dict, with_library: bool, subagents: value.setdefault("env", {}).update(env) deny = value.setdefault("permissions", {}).setdefault("deny", []) deny += [r for r in permissions(work, subagents)["deny"] if r not in deny] - value.setdefault("hooks", {}).setdefault("Stop", []).append({"hooks": [stop_hook()]}) + value.setdefault("hooks", {}).setdefault("Stop", []).append({"hooks": [stop_hook(own(work))]}) settings.unlink(missing_ok=True) settings.write_text(json.dumps(value, indent=2) + "\n") @@ -381,12 +383,29 @@ def collect(task: dict, work: Path, log: Path, params: dict) -> dict: "exploration_used", "exploration_budget", "gemini_usd", "run_tree")}, **({"finish_error": reply["finish_error"]} if "finish_error" in reply else {})} - record_path = own(work) / "session.json" - record = json.loads(record_path.read_text()) if record_path.is_file() else {} - if record.get("repository") and record.get("base"): - exported = library.export(Path(record["repository"]), record["base"], log) + # The session could write all of <run>/rax and its notes: what it left there that cannot be read is recorded, and + # the session is judged as any other (the Evolver takes in no export with an error). + try: + record_path = own(work) / "session.json" + record = json.loads(record_path.read_text()) if record_path.is_file() else {} + except (OSError, ValueError) as exc: + record = {"error": f"the session's record cannot be read: {type(exc).__name__}: {exc}"[:500]} + exported = None + if record.get("error"): + exported = {"base": None, "head": None, "bundle": None, "error": record["error"]} + elif record.get("repository") and record.get("base"): + try: + exported = library.export(Path(record["repository"]), record["base"], log) + except Exception as exc: # noqa: BLE001 - a repository the agent broke + (log / library.BUNDLE).unlink(missing_ok=True) + exported = {"base": record["base"], "head": None, "bundle": None, + "error": f"the library cannot be exported: {type(exc).__name__}: {exc}"[:500]} + if exported is not None: exported["name"] = record.get("name") (log / library.RECORD).write_text(json.dumps(exported, indent=1) + "\n") facts["library"] = {k: exported.get(k) for k in ("base", "head", "bundle", "error")} - facts["notes"] = _keep_notes(work, log) + try: + facts["notes"] = _keep_notes(work, log) + except OSError as exc: + facts["notes"] = {"error": f"{type(exc).__name__}: {exc}"[:500]} return facts diff --git a/hermit/agent/evolver/methods/rax/library.py b/hermit/agent/evolver/methods/rax/library.py index b08071d2..78b48baf 100644 --- a/hermit/agent/evolver/methods/rax/library.py +++ b/hermit/agent/evolver/methods/rax/library.py @@ -9,10 +9,12 @@ - in the session: the agent's `skill_library_merge` tool is RAX's `merge` against that repository: the same format and evidence checks, the same replies, and later commits of the same session see what it merged; - after it (`collect`): `export` writes what the session merged (a git bundle of the repository's main past its first - commit) into the run's log, without running git in a repository the agent could write; + commit) into the run's log, without running git in a repository the agent could write, and none of it when it holds + the value of a key the session was given (`holds_key`: Hermit's redaction cannot reach a compressed object); - the Evolver (`merge.py`, in the evolver sandbox): `build` makes the same repository of the step's adapter, and RAX's - `merge` takes in each session's bundle on a branch of its own, checking every changed skill again; the merged tree - is the next adapter (`write_tree`). + `merge` takes in each session's bundle on a branch of its own, checking every changed skill again, and a merge whose + tree is no library this port can keep as an adapter (`library_files`) is undone; the merged tree is the next adapter + (`write_tree`). Every repository starts from one commit of the adapter's library files with a fixed author, date and file mode, so a session and the Evolver that start from the same adapter start from the same commit: RAX's merge base. Only the @@ -192,12 +194,54 @@ def export(repository: Path, base: str, out: Path) -> dict: if not ancestor: record["error"] = "the library's main does not descend from the commit the session started from" return record + held = holds_key(bare, base, head) + if held: + record["error"] = (f"the session's merges hold the value of {held}, which git keeps compressed where " + "Hermit's redaction cannot scrub it: none of them is exported") + return record Path(out).mkdir(parents=True, exist_ok=True) git("bundle", "create", "-q", str(Path(out).resolve() / BUNDLE), "main", f"^{base}", cwd=bare) record["bundle"] = BUNDLE return record +def holds_key(repository: Path, base: str, head: str) -> str | None: + """The name of a key-like variable of this process (hermit.redact.key_values: the keys the session was given) + whose value is in one of the objects from `base` to `head` (their commits, trees and files, read one by one), or + None. Hermit scrubs key values out of the files a run keeps; a git object is compressed, out of its reach.""" + from hermit.redact import key_values + values = key_values() + if not values: + return None + ids = git("rev-list", "--objects", "--no-object-names", head, f"^{base}", cwd=repository) + with tempfile.TemporaryFile() as given: + given.write(ids.encode()) + given.seek(0) + reader = subprocess.Popen(["git", "cat-file", "--batch"], cwd=repository, stdin=given, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + env={**os.environ, **rax.GIT_ENV}) + read_all = False + try: + while header := reader.stdout.readline(): + parts = header.split() + if len(parts) != 3: + raise rax.LibraryError(f"git cat-file: {header[:200]!r}") + content = reader.stdout.read(int(parts[2])) + reader.stdout.read(1) # the newline after each object + held = next((name for name, value in values.items() if value in content), None) + if held: + return held + read_all = True + finally: + if not read_all: + reader.kill() + reader.stdout.close() + reader.wait() + if reader.returncode: + raise rax.LibraryError(f"git cat-file exited {reader.returncode}") + return None + + def take_in(repository: Path, bundle: Path, record: dict, name: str, message: str) -> dict: """The Evolver's side: a session's bundle, fetched as data into a fresh clone of the Evolver's repository on branch session/<name>, merged by RAX's merge (every changed skill checked again). Returns RAX's reply.""" @@ -211,7 +255,30 @@ def take_in(repository: Path, bundle: Path, record: dict, name: str, message: st fetched = git("rev-parse", f"refs/heads/session/{name}", cwd=clone).strip() if fetched != record.get("head"): return {"merged": False, "reason": f"the bundle's main is {fetched}, not the recorded {record.get('head')}"} - return merge(repository, name, workspace, message) + reply = merge(repository, name, workspace, message) + if reply.get("merged"): + # RAX's merge checks the skills a branch changed; the adapter is the whole tree (library_files): a merge + # that leaves no library (INDEX.md gone, a link) is undone, and the step goes on without it + try: + main_tree(repository, Path(scratch) / "merged") + except (rax.LibraryError, subprocess.SubprocessError, OSError) as exc: + git("reset", "-q", "--hard", str(reply["previous_main"]), cwd=repository) + return {"merged": False, "head": reply.get("head"), + "reason": f"RAX's merge took it in, but the merged library is no adapter: {exc}"[:500]} + return reply + + +def main_tree(repository: Path, into: Path) -> list[str]: + """The repository's main written out into `into` (a new directory); returns its library files (library_files, + which refuses a tree that is no library).""" + into = Path(into) + into.mkdir() + archive = subprocess.run(["git", "archive", "--format=tar", "main"], cwd=repository, capture_output=True, + timeout=600, env={**os.environ, **rax.GIT_ENV}) + if archive.returncode: + raise rax.LibraryError("git archive failed: " + archive.stderr.decode(errors="replace")[:300]) + subprocess.run(["tar", "-x", "-C", str(into)], input=archive.stdout, check=True, timeout=600) + return library_files(into) def write_tree(repository: Path, adapter: Path) -> list[str]: @@ -220,13 +287,7 @@ def write_tree(repository: Path, adapter: Path) -> list[str]: adapter = Path(adapter) with tempfile.TemporaryDirectory(prefix="rax-tree-") as scratch: tree = Path(scratch) / "tree" - tree.mkdir() - archive = subprocess.run(["git", "archive", "--format=tar", "main"], cwd=repository, capture_output=True, - timeout=600, env={**os.environ, **rax.GIT_ENV}) - if archive.returncode: - raise rax.LibraryError("git archive failed: " + archive.stderr.decode(errors="replace")[:300]) - subprocess.run(["tar", "-x", "-C", str(tree)], input=archive.stdout, check=True, timeout=600) - files = library_files(tree) + files = main_tree(repository, tree) if (adapter / SKILLS).is_symlink(): (adapter / SKILLS).unlink() shutil.rmtree(adapter / SKILLS, ignore_errors=True) diff --git a/hermit/agent/evolver/methods/rax/library_server.py b/hermit/agent/evolver/methods/rax/library_server.py index 7cc7fccf..f640ce69 100644 --- a/hermit/agent/evolver/methods/rax/library_server.py +++ b/hermit/agent/evolver/methods/rax/library_server.py @@ -3,7 +3,9 @@ workspace has a clone of the skill library (skill-library/.git), and answers it with RAX's `merge` of the session's branch into the library's main (upstream/skill_library.py, through library.merge): `merged: true` with the merged commit, or the format and evidence `problems` to fix, or the `conflicts` to resolve. The tool's name, description, -schema, refusal and replies are RAX's; the MCP exchange is RAX's frontend's (newline-delimited JSON-RPC on stdio). +schema, refusal and replies are RAX's, its errors too (RAX's public_failure at the tool's stage, services/controller/ +errors.py: the whole message, an unexpected error's innermost frames, no URL, host directory or credential); the MCP +exchange is RAX's frontend's (newline-delimited JSON-RPC on stdio). The library repository is this session's (<run>/rax/library/<robot>, made by the RAX task functions' `prepare` and named in <run>/rax/session.json); what the session merged reaches the adapter through the rax Evolver, which runs the @@ -16,10 +18,14 @@ import argparse import json from pathlib import Path +import re import sys +import traceback PROTOCOL_VERSION = "2025-06-18" # RAX's frontend's NAME = "skill_library_merge" +STAGE = "validation" # RAX's frontend's stage of a skill_library_merge call +MAX_REASON = 8000 # RAX's errors.py TOOL = {"name": NAME, "description": "Merge your session branch of the skill library (the clone in skill-library/) into the " "library's main, so later sessions get your skills. Only committed changes count (git add, git " @@ -40,6 +46,24 @@ def session(workspace: Path) -> dict: return record +def failure(exc: BaseException) -> dict: + """RAX's public_failure of a skill_library_merge call (real/rainbow 36c926c services/controller/errors.py, at the + frontend's stage of the call): an expected refusal's message alone, anything else with its innermost frames; URLs, + the host's directories and credentials removed.""" + reason = str(exc) or type(exc).__name__ + if not isinstance(exc, (ValueError, PermissionError)) and exc.__traceback__ is not None: + frames = traceback.extract_tb(exc.__traceback__)[-4:] + reason += "\nTraceback (innermost last):\n" + "\n".join(f" {f.filename}:{f.lineno} in {f.name}" + for f in frames) + reason = re.sub(r"https?://\S+", "[redacted URL]", reason) + reason = re.sub(r"(?<![\w.])/(?:[^\s,;\]\)\"\'/]+/)+", "", reason) + reason = re.sub(r"(?i)(bearer\s+|(?:api[_-]?key|authorization|token)\s*[=:]\s*)[^\s,;]+", r"\1[redacted]", reason) + reason = re.sub(r"\bsk-[A-Za-z0-9_-]+", "[redacted key]", reason) + if len(reason) > MAX_REASON: + reason = reason[:MAX_REASON // 4] + "\n...\n" + reason[-(MAX_REASON * 3 // 4):] + return {"type": type(exc).__name__, "operation": NAME, "stage": STAGE, "reason": reason} + + def call(workspace: Path, arguments: dict) -> dict: """RAX's handler: one-line message only, then RAX's merge of the session's branch.""" from hermit.agent.evolver.methods.rax import library @@ -76,8 +100,7 @@ def handle(workspace: Path, request) -> dict | None: value = call(workspace, params.get("arguments", {})) result = {"content": [{"type": "text", "text": json.dumps(value, allow_nan=False)}]} except Exception as exc: # the agent's error to read, as RAX's frontend returns one - error = {"type": type(exc).__name__, "message": str(exc)[-4000:], "operation": NAME} - result = {"isError": True, "content": [{"type": "text", "text": json.dumps({"error": error})}]} + result = {"isError": True, "content": [{"type": "text", "text": json.dumps({"error": failure(exc)})}]} else: raise PermissionError("Unsupported method") return {"jsonrpc": "2.0", "id": ident, "result": result} diff --git a/hermit/agent/evolver/methods/rax/merge.py b/hermit/agent/evolver/methods/rax/merge.py index 6bd14782..135fba2d 100644 --- a/hermit/agent/evolver/methods/rax/merge.py +++ b/hermit/agent/evolver/methods/rax/merge.py @@ -2,15 +2,18 @@ adapter is changed in place and output/step_result.json says what was taken in. For each task of the step (learning_material/current, in the step's order): the export record `collect` wrote into the -run's log (library.json) and its bundle; RAX's merge of the bundle's main into the step's library (library.take_in). -The step's library is rebuilt from the adapter first (library.build): the commit each session started from, unless -the adapter changed since (a session that started elsewhere is not taken in).""" +run's log (library.json) and its bundle; RAX's merge of the bundle's main into the step's library (library.take_in, +which undoes a merge that leaves no library). A session whose merges cannot be read or taken in is recorded with the +reason, and the step goes on without it. The step's library is rebuilt from the adapter first (library.build): the +commit each session started from, unless the adapter changed since (a session that started elsewhere is not taken +in).""" from __future__ import annotations import json import os from pathlib import Path import shutil +import subprocess import sys from hermit.agent.evolver.methods.rax import library @@ -52,8 +55,8 @@ def take_in(step: Path, repository: Path, base: str, task_id: str, record: dict) name = str(exported.get("name") or task_id) try: reply = library.take_in(repository, bundle, exported, name, f"the merges of task {task_id}'s session") - except (library.rax.LibraryError, ValueError, OSError) as exc: - return {"task": task_id, "merged": False, "reason": str(exc)[:500]} + except (library.rax.LibraryError, ValueError, OSError, subprocess.SubprocessError) as exc: + return {"task": task_id, "merged": False, "reason": f"{type(exc).__name__}: {exc}"[:500]} keep = ("merged", "reason", "problems", "conflicts", "skills", "changed_files", "head", "library_main") return {"task": task_id, **{k: reply[k] for k in keep if k in reply}} diff --git a/hermit/agent/evolver/methods/rax/stop_hook.py b/hermit/agent/evolver/methods/rax/stop_hook.py index 727836b6..b5e8a644 100644 --- a/hermit/agent/evolver/methods/rax/stop_hook.py +++ b/hermit/agent/evolver/methods/rax/stop_hook.py @@ -8,9 +8,13 @@ directory on the host (POST /explored), never by asking the frontend, which a long call can keep busy. When the service gives no answer, exploration counts as open, as RAX's launcher counts a session state it cannot read. The RAX task functions' `prepare` installs it as the session's Stop hook (Claude Code's .claude/settings.json in the -workspace) and writes what it asks with beside the workspace (<run>/rax/hook.json: the service's URL, the workspace, -the service's name of the session); it keeps its count there too (<run>/rax/relaunches). Standard library only, run by -the framework's Python in isolated mode (-I: nothing of the workspace is imported) in the session's workspace. +workspace), with the run's RAX directory as its argument, and writes what it asks with there (<run>/rax/hook.json: +the service's URL, the workspace, the service's name of the session); it keeps its count there too +(<run>/rax/relaunches). The directory is named, never found from where the hook runs: Claude Code runs a hook in the +shell's current directory, which follows the agent's `cd`. Standard library only, run by the framework's Python in +isolated mode (-I: nothing of the current directory is imported): + + <framework python> -I stop_hook.py <run>/rax """ from __future__ import annotations @@ -42,12 +46,16 @@ def closed(mine: Path, timeout: float = 30.0) -> bool: return bool(reply["closed"]) -def main() -> int: +def main(argv: list[str] | None = None) -> int: + args = sys.argv[1:] if argv is None else argv try: json.load(sys.stdin) # the host's hook input: nothing in it is needed except ValueError: pass - mine = Path.cwd().resolve().parent / "rax" # a hook runs where the session started: its workspace + if len(args) != 1 or not Path(args[0]).is_absolute(): + print("rax stop hook: give the run's RAX directory (<run>/rax), as prepare installs it", file=sys.stderr) + return 0 + mine = Path(args[0]) count_file = mine / "relaunches" try: count = int(count_file.read_text().strip() or 0) if count_file.is_file() else 0 @@ -60,7 +68,12 @@ def main() -> int: print(f"rax stop hook: {type(exc).__name__}: {exc}", file=sys.stderr) if count >= MAX_RELAUNCHES: return 0 - count_file.write_text(f"{count + 1}\n") + try: + count_file.write_text(f"{count + 1}\n") + except OSError as exc: # a relaunch it cannot count could be owed again and again + print(f"rax stop hook: the relaunch count cannot be kept ({type(exc).__name__}: {exc}): the turn ends", + file=sys.stderr) + return 0 print(json.dumps({"decision": "block", "reason": CONTINUE_PROMPT})) return 0 diff --git a/tests/methods/rax/test_rax.py b/tests/methods/rax/test_rax.py index 9bd40cd9..6d2e2d21 100644 --- a/tests/methods/rax/test_rax.py +++ b/tests/methods/rax/test_rax.py @@ -19,6 +19,7 @@ import os from pathlib import Path import py_compile +import shlex import shutil import socket import stat @@ -148,9 +149,12 @@ def session(tmp: Path, adapter: Path, name: str, *, run: str = "run") -> tuple[P def test_the_vendored_files_are_raxs_own_at_the_pinned_commits(): """RAX's library module and its continual-learning skill are RAX's (real/rainbow 36c926c) byte for byte, with - RAX's license and notice; the method page and the launcher name the commits.""" + RAX's license and notice (from its main, db744f5: 36c926c has neither); the method page and the launcher name the + commits.""" vendored = {"skill_library.py": "4a91f721cdcc32e1a0b1631733b3e0606d1d0e72796d5eb80da2a80f29ec7475", - "continual-learning.SKILL.md": "86151e017553648912b806ad95be62cf1a58532a7160a025f4b94ced3dc0588d"} + "continual-learning.SKILL.md": "86151e017553648912b806ad95be62cf1a58532a7160a025f4b94ced3dc0588d", + "LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "NOTICE": "f1dbb9a9ad02acd1c975f986d4a324b8a6075eaa0152fcefcbd03b23a8ca03d0"} for name, digest in vendored.items(): assert hashlib.sha256((METHOD / "upstream" / name).read_bytes()).hexdigest() == digest, name assert "Apache License" in (METHOD / "upstream" / "LICENSE").read_text() @@ -272,6 +276,34 @@ def test_the_export_says_when_nothing_was_merged_and_refuses_a_main_off_the_base assert "no main branch" in L.export(repository, base, tmp_path / "log3")["error"] +def test_the_export_holds_back_merges_that_carry_a_key_the_session_was_given(tmp_path, monkeypatch): + """A key's value in what a session merged (a file that a later commit removed, a merge's message) is in git's + compressed objects, where Hermit's redaction cannot scrub it: no bundle is made, and the record names the variable, + never its value. A key in none of the objects changes nothing.""" + secret = "sk-test-" + "9" * 24 + monkeypatch.setenv("RAX_TEST_API_KEY", secret) + adapter = seed(tmp_path) + repository, work, base = session(tmp_path, adapter, "s1") + clone = work / rax.LIBRARY_DIR + add_skill(clone, "grasp-bowl") + (clone / "skills" / "grasp-bowl" / "code" / "notes.py").write_text(f"KEY = '{secret}'\n") + commit(clone, "grasp-bowl with a key") + (clone / "skills" / "grasp-bowl" / "code" / "notes.py").unlink() # gone from main's tree, kept in its history + commit(clone, "the key removed") + assert L.merge(repository, "s1", work, "grasp-bowl: draft")["merged"] + record = L.export(repository, base, tmp_path / "log") + assert record["bundle"] is None and "RAX_TEST_API_KEY" in record["error"] and secret not in json.dumps(record) + assert not (tmp_path / "log" / L.BUNDLE).exists() + repository, work, base = session(tmp_path, adapter, "s2", run="run2") + add_skill(work / rax.LIBRARY_DIR, "grasp-bowl") + commit(work / rax.LIBRARY_DIR, "grasp-bowl") + assert L.merge(repository, "s2", work, f"grasp-bowl, tried with {secret}")["merged"] # in the merge's message + assert "RAX_TEST_API_KEY" in L.export(repository, base, tmp_path / "log2")["error"] + monkeypatch.delenv("RAX_TEST_API_KEY") + monkeypatch.setenv("RAX_TEST_TOKEN", "t" * 24) # a key in none of the objects + assert L.export(repository, base, tmp_path / "log3")["bundle"] == L.BUNDLE + + def test_raxs_merge_answers_a_broken_skill_and_a_change_outside_the_library_with_its_problems(tmp_path): """RAX's merge refuses what its format forbids and says what to do; nothing reaches main.""" adapter = seed(tmp_path) @@ -311,8 +343,9 @@ def test_the_merge_tool_is_raxs_skill_library_merge(tmp_path): assert tool["inputSchema"]["additionalProperties"] is False for arguments in ({}, {"message": " "}, {"message": "x", "force": True}): result = rpc("tools/call", {"name": "skill_library_merge", "arguments": arguments})["result"] - assert result["isError"] and json.loads(result["content"][0]["text"])["error"]["message"] == \ - "skill_library_merge takes message (one line)" + assert result["isError"] and json.loads(result["content"][0]["text"])["error"] == { + "type": "ValueError", "operation": "skill_library_merge", "stage": "validation", + "reason": "skill_library_merge takes message (one line)"} # RAX's public_failure add_skill(work / rax.LIBRARY_DIR, "grasp-bowl") commit(work / rax.LIBRARY_DIR, "grasp-bowl") result = rpc("tools/call", {"name": "skill_library_merge", "arguments": {"message": "grasp-bowl: draft"}})["result"] @@ -324,6 +357,18 @@ def test_the_merge_tool_is_raxs_skill_library_merge(tmp_path): _session_record(work, {"name": name}) # a session without the adapter has no library result = rpc("tools/call", {"name": "skill_library_merge", "arguments": {"message": "m"}})["result"] assert result["isError"] and "no skill library" in result["content"][0]["text"] + error = S.failure(_raised(RuntimeError(f"git fetch {repository}: token=abc123 at https://example.test/x"))) + assert error["type"] == "RuntimeError" and error["stage"] == "validation" + assert str(repository.parent) not in error["reason"] and "libero-panda" in error["reason"] + assert "[redacted]" in error["reason"] and "[redacted URL]" in error["reason"] + assert "Traceback (innermost last):" in error["reason"] # an unexpected error: where it came from + + +def _raised(exc: BaseException) -> BaseException: + try: + raise exc + except BaseException as caught: + return caught def test_the_merge_tool_serves_on_stdio_as_the_sessions_mcp_configuration_starts_it(tmp_path): @@ -352,7 +397,8 @@ def test_the_stop_hook_continues_an_open_exploration_at_most_three_times(tmp_pat exploration, or the submission), the turn's end is blocked with RAX's continue prompt, at most three times (RAX's MAX_RELAUNCHES); once it is closed the turn ends. The hook never asks the frontend (a robot socket that takes the call and never answers, as RAX's frontend while a long call holds it, is not waited on), and a service that gives - no answer counts as open, as RAX counts a session state it cannot read.""" + no answer counts as open, as RAX counts a session state it cannot read. It finds its files by the path it is given, + wherever it runs: Claude Code runs a hook in the shell's current directory, which follows the agent's `cd`.""" service.state = {} # nothing submitted yet work = _registration(tmp_path, f"{TASK}-0c0c0c0c", f"{TASK}-1d1d1d1d") reply = service.register({"workspace": str(work), "task": TASK}) @@ -363,16 +409,19 @@ def test_the_stop_hook_continues_an_open_exploration_at_most_three_times(tmp_pat robot.bind(str(tmp_path / "r.sock")) robot.listen() - def hook(): - done = subprocess.run([sys.executable, "-I", str(METHOD / "stop_hook.py")], input='{"hook_event_name":"Stop"}', - capture_output=True, text=True, cwd=work, timeout=20, - env={**os.environ, "RAX_MCP_SOCKET": str(tmp_path / "r.sock")}) + installed = shlex.split(A.stop_hook(mine)["command"]) # as prepare installs it + assert installed == [sys.executable, "-I", str(METHOD / "stop_hook.py"), str(mine)] + (work / "code" / "grasp").mkdir(parents=True) + + def hook(where=work): + done = subprocess.run(installed, input='{"hook_event_name":"Stop"}', capture_output=True, text=True, + cwd=where, timeout=20, env={**os.environ, "RAX_MCP_SOCKET": str(tmp_path / "r.sock")}) assert done.returncode == 0, done.stderr return json.loads(done.stdout) if done.stdout.strip() else None try: - for n in (1, 2, 3): - assert hook() == {"decision": "block", "reason": H.CONTINUE_PROMPT} + for n, where in ((1, work), (2, work / "code" / "grasp"), (3, tmp_path)): # wherever the agent cd'd to + assert hook(where) == {"decision": "block", "reason": H.CONTINUE_PROMPT} assert (mine / "relaunches").read_text().strip() == str(n) assert hook() is None # three relaunches: the turn ends (mine / "relaunches").write_text("0\n") @@ -386,6 +435,12 @@ def hook(): A._post(service.url + "/explored", {"workspace": str(work), "session": "another"}) (mine / H.HOOK_FILE).write_text(json.dumps({**asked, "url": "http://127.0.0.1:9"})) # no service answers assert hook() == {"decision": "block", "reason": H.CONTINUE_PROMPT} + (mine / "relaunches").unlink() + (mine / "relaunches").mkdir() # a count it cannot keep: no relaunch it cannot bound + assert hook() is None + (mine / "relaunches").rmdir() + lost = subprocess.run(installed[:3], input="{}", capture_output=True, text=True, cwd=work, timeout=20) + assert lost.returncode == 0 and not lost.stdout.strip() and "<run>/rax" in lost.stderr # no directory given finally: robot.close() assert "Your previous turn ended while exploration is still open" in H.CONTINUE_PROMPT @@ -660,7 +715,8 @@ def test_a_rax_session_runs_on_the_frameworks_claude_code_agent_and_its_merges_r assert deny[:4] == ["WebFetch", "WebSearch", "Agent", "Task"] and "--strict-mcp-config" in saw["args"] assert f"Edit(/{work}/.claude/**)" in deny and f"Edit(/{work}/{A.CLAUDE_MCP})" in deny hook = saw["settings"]["hooks"]["Stop"][-1]["hooks"][0] - assert hook["command"].endswith("stop_hook.py") and " -I " in hook["command"] + assert shlex.split(hook["command"]) == [sys.executable, "-I", str(METHOD / "stop_hook.py"), + str(work.parent / "rax")] bridge = saw["servers"][A.MCP_SERVER] assert bridge["command"] == str(A.agent_python(rax_root)) assert bridge["args"] == ["-I", str(rax_root / "harness" / "mcp_bridge.py"), str(socket_dir / "robot.sock")] @@ -801,6 +857,17 @@ def test_collect_keeps_the_session_when_the_service_cannot_end_it(tmp_path, monk assert "finish_error" in facts and facts["session"] is None and facts["notes"]["files"] == 1 assert facts["library"] == {"base": base, "head": base, "bundle": None, "error": None} + # a library the session broke (it can write all of <run>/rax): recorded, the session judged as any other + def broken(*_): + raise rax.LibraryError("git bundle create: fatal: inflate: data stream error") + monkeypatch.setattr(A.library, "export", broken) + facts = A.collect({"id": TASK}, work, log, {}) + assert facts["library"]["bundle"] is None and "cannot be exported" in facts["library"]["error"] + assert json.loads((log / L.RECORD).read_text())["error"] == facts["library"]["error"] # the Evolver's reason + (work.parent / "rax" / "session.json").write_text("{not json") + facts = A.collect({"id": TASK}, work, log, {}) + assert "record cannot be read" in facts["library"]["error"] and facts["notes"]["files"] == 1 + # ---------- the Evolver ---------- @@ -875,6 +942,55 @@ def logged(task_id: str, record: dict | None, bundle: Path | None = None) -> Non assert json.loads((places["output"] / "step_result.json").read_text())["summary"].startswith("no change") +def test_the_evolver_undoes_a_merge_that_leaves_no_library_and_goes_on_with_the_step(tmp_path, monkeypatch): + """RAX's merge checks the skills a branch changed, so it takes in a session that only deleted INDEX.md, or only put + a link straight under skills/. The adapter is the whole library tree (library_files): the Evolver undoes such a + merge with its reason, and the step's other sessions are still taken in. A git that times out is a reason too.""" + adapter = seed(tmp_path) + step = tmp_path / "material" / "step_0001" + (step / "tasks").mkdir(parents=True) + ids = [f"train-libero_spatial_{n}" for n in range(3)] + for n, change in enumerate(("index", "link", "skill")): + repository, work, base = session(tmp_path, adapter, f"s{n}", run=f"run{n}") + clone = work / rax.LIBRARY_DIR + if change == "index": + (clone / "INDEX.md").unlink() + elif change == "link": + (clone / "skills" / "elsewhere").symlink_to("/etc") + else: + add_skill(clone, "grasp-bowl") + commit(clone, change) + assert L.merge(repository, f"s{n}", work, change)["merged"] # RAX's merge takes each of them in + log = step / "trajectories" / _safe(ids[n]) + record = {**L.export(repository, base, log), "name": f"s{n}"} + (log / L.RECORD).write_text(json.dumps(record)) + (step / "tasks" / f"{_safe(ids[n])}.json").write_text(json.dumps( + {"id": ids[n], "trajectory": f"trajectories/{_safe(ids[n])}"})) + (step / "summary.json").write_text(json.dumps({"tasks": ids})) + (tmp_path / "material" / "current").symlink_to("step_0001") + places = {k: tmp_path / "ws" / k for k in ("scratch", "output")} + context = tmp_path / "context.json" + material = str(tmp_path / "material") + context.write_text(json.dumps({"workspace": {"adapter": str(adapter), "learning_material": material, + **{k: str(v) for k, v in places.items()}}})) + monkeypatch.setenv("HA_CONTEXT", str(context)) + assert M.main() == 0 + sessions = json.loads((places["output"] / "step_result.json").read_text())["extra"]["sessions"] + assert sessions[0]["merged"] is False and "INDEX.md must be a file" in sessions[0]["reason"] + assert sessions[1]["merged"] is False and "links are not allowed" in sessions[1]["reason"] + assert sessions[2]["merged"] and sessions[2]["skills"] == ["grasp-bowl"] + assert (adapter / "INDEX.md").is_file() and not (adapter / "skills" / "elsewhere").is_symlink() + assert (adapter / "skills" / "grasp-bowl").is_dir() and spec(adapter)["passed"] + + def slow(*_): + raise subprocess.TimeoutExpired(["git", "fetch"], 600) + monkeypatch.setattr(M.library, "take_in", slow) + built = tmp_path / "again" / L.ROBOT + first = L.build(seed(tmp_path, "original"), built) + reply = M.take_in(step, built, first, ids[2], {"trajectory": f"trajectories/{_safe(ids[2])}"}) + assert reply["merged"] is False and reply["reason"].startswith("TimeoutExpired") + + def test_the_evolver_reads_no_log_outside_the_step(tmp_path, monkeypatch): """A record whose trajectory leaves the step, or has none, is not read.""" step = tmp_path / "current" @@ -997,6 +1113,14 @@ def test_the_service_registers_only_a_rollouts_own_workspace_and_one_session_a_r assert service.frontends_started[1].stops == 1 +def test_the_run_trees_cannot_be_listed_while_the_service_runs_and_can_once_it_stops(service): + """While the service runs, its run trees' directory can be passed through, not listed (no session learns another's + tree); once it stops, it can be listed again, so a run's directory can be removed.""" + assert stat.S_IMODE(service.trees.stat().st_mode) == 0o300 + service.stop() + assert stat.S_IMODE(service.trees.stat().st_mode) == 0o700 + + def test_a_service_started_again_ends_what_the_last_one_left_open_and_two_never_share_a_state(tmp_path, service): """The ledger's unfinished sessions of a service that was killed: a frontend still running (its command line names the session's configuration) is stopped, a process that is not one is left alone, and each is ended with its facts; From 7293cf7aea4349bac215fe615c88b6030715e5f9 Mon Sep 17 00:00:00 2001 From: iamziyuzhao <iamziyuzhao@gmail.com> Date: Sun, 29 Nov 2026 15:11:51 -0500 Subject: [PATCH 5/7] RAX: the Evolver checks every skill after a merge; no key left in a session's git Round 3 of the post-PR audit (ccac84e): no P1, 1 P2, 3 P3. - The Evolver runs the template's whole check (RAX's validate_tree over every skill, library_files) after each merge and undoes a merge it refuses, with the problems. RAX's merge checks only the skills a branch changed as git diff --name-only names them, and git names a rename by its new path alone: a session that renamed a skill another one uses, or moved a skill's only image away, was merged, the next adapter failed the template check, and the Trainer's repair raised IsADirectoryError on the skill directory the check named, which stopped hermit train. - The template check names no file for a skill's or the library's problem (path ""), so repair goes back to the parent's library; a test runs repair. - collect treats a session record that is valid JSON but not an object as unreadable, instead of raising. - collect removes the .git of a session repository (its library repository, its clone; found where prepare makes them) whose objects hold the value of a key the session was given, or cannot be read to tell: the run's directory is kept, and Hermit's redaction cannot reach git's compressed objects. - Method page: Hermit's deployment in the workspace (hermit/rax/, its managed CLAUDE.md block), the rename gap and the Evolver's check, the repository scrub. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/methods/rax.md | 59 +++++++------ hermit/adapter/templates/rax/.hermit/check.py | 19 +---- hermit/agent/evolver/methods/rax/actor.py | 15 +++- hermit/agent/evolver/methods/rax/library.py | 77 ++++++++++++++--- tests/methods/rax/test_rax.py | 85 +++++++++++++++++-- 5 files changed, 192 insertions(+), 63 deletions(-) diff --git a/docs/methods/rax.md b/docs/methods/rax.md index b74b7fb9..eaea1105 100644 --- a/docs/methods/rax.md +++ b/docs/methods/rax.md @@ -49,25 +49,30 @@ splits and the host service; its README gives RAX's setup and the commands. `rax` is RAX's skill library as RAX's `services/skill_library.py` lays it out (robot-agent-exploration/rax `real/rainbow` 36c926c, vendored unchanged in `hermit/agent/evolver/methods/rax/upstream/` with RAX's license and -notice, from its `main`: 36c926c has neither): `README.md` (RAX's, for this robot), `INDEX.md` (one row per skill) and `skills/<slug>/` with `SKILL.md` -(frontmatter `name`, `description`, `status` draft, verified or deprecated, `robot`, `entry`; RAX's sections), `code/` -(an entry `main(ctx, ...)` returning `{ok, measured, why}`) and `evidence/` (`runs.jsonl`, at least one image; a -`verified` skill has two unattended successful runs with images). `INDEX.md` and `skills/**` are learnable; the rest is -fixed. The template has no `skills/` (a package keeps no dotfile): the library's first commit adds RAX's empty -`skills/.gitkeep`, as RAX's `ensure_library` starts a library. The template's check runs RAX's `validate_tree` over -every skill, as RAX's merge does over a branch's changed ones, and refuses links. - -What reaches the acting session: `ADAPTER.md` in its context, and through the RAX task functions the library's clone -`skill-library/` on the session's branch, RAX's `continual-learning` agent skill and RAX's `skill_library_merge` tool. -`ADAPTER.md` holds RAX's two library paragraphs of `real/rainbow`'s `AGENTS.md` (the reading one with its lead-in -shortened, "Teach later sessions" verbatim) between two of the port's: where the clone is, and where a LIBERO run's -frames are (`runtime/autonomous_controller/runs/<run>/frames/`, where RAX's skill, written for its real robots, says -`runtime/frames/`) and that a bundle sees none of the library. RAX's skill lets a controller import library skills, as -on its real robots, whose controllers run in the agent's workspace; on LIBERO a rehearsal and the formal batch run the -bundle in RAX's bundle sandbox, which shows only the bundle's directory and `api/runtime.py`, so `ADAPTER.md` says to -copy into the bundle what it uses of a library skill. Without an adapter (`--adapter none`) the session has none of -these: it is RAX's LIBERO session as published. No existing template fits: none holds a repository of skills that -sessions merge into through a checked merge. +notice, from its `main`: 36c926c has neither): `README.md` (RAX's, for this robot), `INDEX.md` (one row per skill) and +`skills/<slug>/` with `SKILL.md` (frontmatter `name`, `description`, `status` draft, verified or deprecated, `robot`, +`entry`; RAX's sections), `code/` (an entry `main(ctx, ...)` returning `{ok, measured, why}`) and `evidence/` +(`runs.jsonl`, at least one image; a `verified` skill has two unattended successful runs with images). `INDEX.md` and +`skills/**` are learnable; the rest is fixed. The template has no `skills/` (a package keeps no dotfile): the library's +first commit adds RAX's empty `skills/.gitkeep`, as RAX's `ensure_library` starts a library. The template's check runs +RAX's `validate_tree` over every skill, as RAX's merge does over a branch's changed ones, and refuses links. Its +problems are a skill's or the library's, not one file's, so the Trainer's repair of an adapter that fails it goes back +to the parent's library. + +What reaches the acting session: Hermit's deployment of the adapter (its copy `hermit/rax/`, and in `CLAUDE.md`, after +RAX's `@AGENTS.md`, Hermit's managed block: its header, a note that the adapter's paths are relative to `hermit/rax/`, +`ADAPTER.md` under a `###` heading, and the adapter's other files by name), and through the RAX task functions the +library's clone `skill-library/` on the session's branch, RAX's `continual-learning` agent skill and RAX's +`skill_library_merge` tool. `ADAPTER.md` says that its paths are the workspace's and that `hermit/rax/` is only the +library as the session started. `ADAPTER.md` holds RAX's two library paragraphs of `real/rainbow`'s `AGENTS.md` (the +reading one with its lead-in shortened, "Teach later sessions" verbatim) between two of the port's: where the clone is, +and where a LIBERO run's frames are (`runtime/autonomous_controller/runs/<run>/frames/`, where RAX's skill, written for +its real robots, says `runtime/frames/`) and that a bundle sees none of the library. RAX's skill lets a controller +import library skills, as on its real robots, whose controllers run in the agent's workspace; on LIBERO a rehearsal and +the formal batch run the bundle in RAX's bundle sandbox, which shows only the bundle's directory and `api/runtime.py`, +so `ADAPTER.md` says to copy into the bundle what it uses of a library skill. Without an adapter (`--adapter none`) the +session has none of these: it is RAX's LIBERO session as published. No existing template fits: none holds a repository +of skills that sessions merge into through a checked merge. ## The session @@ -94,9 +99,10 @@ refusal, and RAX's `merge` against that repository). The prompt is RAX's `START_ the session at the service and writes what the session merged into its library (a git bundle of the repository's main past its first commit, made in a fresh repository from copied objects; none when those objects hold the value of a key the session was given, which Hermit's redaction cannot scrub out of git's compressed objects) and the session's notes -and code into the log. The judge, on the host, runs RAX's formal batch of the submitted bundle (the supervisor's -`run_submission`, `formal.py`) on the row's formal layouts: the share of successful episodes, LIBERO's own binary check, -errors counted as failures. +and code into the log; a repository of the session's (its library repository, its clone) whose objects hold such a value +loses its `.git`, since the run's directory is kept. The judge, on the host, runs RAX's formal batch of the submitted +bundle (the supervisor's `run_submission`, `formal.py`) on the row's formal layouts: the share of successful episodes, +LIBERO's own binary check, errors counted as failures. ## The step @@ -121,9 +127,10 @@ flowchart TD 3. The Evolver (`merge.py`, a program in the evolver sandbox) builds a repository from the adapter (one commit of its library files, with a fixed identity and date, so it is the commit the session started from), fetches each session's bundle onto `session/<name>` and runs RAX's merge, which checks every changed skill again. A session that - started from another library, or whose bundle is not what it recorded, is not taken in; a merge that leaves no - library this port can keep as an adapter (`INDEX.md` gone, a link: RAX's merge checks only the skills a branch - changed) is undone, and the step goes on without that session. + started from another library, or whose bundle is not what it recorded, is not taken in; a merge whose library the + template's check refuses (`INDEX.md` gone, a link, a skill another one uses renamed) is undone, and the step goes + on without that session. RAX's merge checks only the skills a branch changed, as git names them, and git names a + renamed skill by its new path alone. 4. The merged main's `INDEX.md` and `skills/` are the next adapter, checked by the template's check. The final adapter is the library after the last session. A step of several sessions merges them in order; a session @@ -148,7 +155,7 @@ URL, default `RAX_SERVICE_URL`) and `bin` (the CLI). The session's settings are |---|---|---|---| | Code | `libero-pro/native` 1767412 (LIBERO); the skill library of `real/rainbow` 36c926c | the same commits: RAX's operator script, workspace, frontend, supervisor, simulators, formal batch and skill library, unchanged | — | | Agent | Claude Code, Claude Opus 5.5 at xhigh, its own home, its servers alone (`--strict-mcp-config`); `acceptEdits` with an allow list (its MCP server, reads of its readable paths); denied: the web tools, the subagent tools at a subagent cap of 0, edits of the workspace's `.claude/` and `.mcp.json`; its commands in Claude Code's own sandbox, allowed without asking (writes in the workspace and the socket's directory, no network) | the same model, effort, MCP flags and deny rules (the project's `.claude/settings.json`, with `.rax-mcp.json` guarded too), on Hermit's Claude Code agent, whose `bypassPermissions` takes the place of RAX's `acceptEdits`, allow list and Claude Code sandbox: the CLI and all it runs are in the task sandbox (bubblewrap), which shows only declared paths, lets it write only its run's directory (workspace, the CLI's home, log, `<run>/rax`) and its own `/tmp`, and reaches only the model provider's hosts and the service's forwarded port; so a command, unlike a file tool, can still write `.claude/`, and what it writes there runs in the same sandbox | the task sandbox is the boundary | -| Prompt and workspace | `START_PROMPT.md`; `prepare_workspace` | the same, byte for byte; with an adapter, the library's clone, RAX's continual-learning skill and the two library paragraphs of `real/rainbow`'s `AGENTS.md` (`ADAPTER.md`) | the library is `real/rainbow`'s, which `libero-pro/native` lacks | +| Prompt and workspace | `START_PROMPT.md`; `prepare_workspace` | RAX's, byte for byte; with an adapter, also the library's clone, RAX's continual-learning skill and the two library paragraphs of `real/rainbow`'s `AGENTS.md` (`ADAPTER.md`), and Hermit's deployment: the adapter's copy `hermit/rax/` and Hermit's managed block in `CLAUDE.md` after `@AGENTS.md` (a note that the adapter's paths are relative to `hermit/rax/`, which `ADAPTER.md` overrides for its own) | the library is `real/rainbow`'s, which `libero-pro/native` lacks | | Robot tools | RAX's frontend, through RAX's bridge on a socket | the same, on the host; the run tree in the service's directory, shown read-only in the task sandbox (RAX's agent writes only its workspace and the socket's directory) | the task sandbox shows only declared paths | | Relaunch | the launcher runs the CLI again (`--resume`) with `CONTINUE_PROMPT` while exploration is open, at most 3 times | a Stop hook continues the same CLI with the same prompt, without its clause about stopped background workers (here they run on); exploration closed by the launcher's own rule (`exploration_closed`), which the service applies | Hermit runs one CLI per call | | Error relaunch, adaptation stage | after a provider error, the same conversation resumed after a pause (`ERROR_PROMPT`, up to 5 in a row); after the login's usage limit, the same conversation resumed once the window resets (`USAGE_PROMPT`, up to 10 times); up to 5 adaptation episodes on swap layouts (collection 6) | in part: a session the login's plan refuses (its usage window) runs again in the same workspace once the plan allows (Hermit's Claude Code agent, `plan_rerun`), as a new conversation from RAX's start prompt, not RAX's resumed one: RAX's session, its budget and the agent's notes (`memory/PROGRESS.md`, which RAX's prompts send it back to) are as they were, the conversation's context is not. A session the CLI reports as failed (an error result, a crash) is scored 0 without its bundle judged (Hermit judges no failed session), and its merges are taken in; one Hermit's clock ends is judged as any other; one the provider stops serving past Claude Code's own retries fails the call before `collect`: scored 0, its merges left out. Hermit's second attempt of a call is off (`claude.retries: 1`): it would remove the session's workspace and log and start the session again, which RAX never does. No adaptation | Hermit runs one CLI per call and resumes no conversation; scope | diff --git a/hermit/adapter/templates/rax/.hermit/check.py b/hermit/adapter/templates/rax/.hermit/check.py index e031c07f..f60155a5 100644 --- a/hermit/adapter/templates/rax/.hermit/check.py +++ b/hermit/adapter/templates/rax/.hermit/check.py @@ -8,23 +8,12 @@ def check(adapter_path: str) -> list[dict]: from hermit.agent.evolver.methods.rax import library - from hermit.agent.evolver.methods.rax.upstream import skill_library as rax adapter = Path(adapter_path).resolve() if not (adapter / "INDEX.md").is_file() or not (adapter / "README.md").is_file(): # Never pass an adapter this check cannot see (under bubblewrap, /tmp is an empty tmpfs). skills/ may be # absent: an empty library (the template has none; the library's first commit adds RAX's skills/.gitkeep). - return [{"path": "INDEX.md", "problem": f"no rax adapter at {adapter} (INDEX.md or README.md missing or not " - f"visible)"}] - try: - files = library.library_files(adapter) - except rax.LibraryError as exc: - return [{"path": "skills", "problem": str(exc)}] - problems, _ = rax.validate_tree(adapter, [f for f in files if f != "README.md"]) - return [{"path": _path(p), "problem": p} for p in problems] - - -def _path(problem: str) -> str: - """The library path a RAX problem names (`skills/<slug>: ...` or INDEX.md), for the Trainer's repair.""" - head = problem.split(":", 1)[0] - return head if head.startswith("skills/") else "INDEX.md" if "INDEX.md" in problem else "skills" + return [{"path": "", "problem": f"no rax adapter at {adapter} (INDEX.md or README.md missing or not visible)"}] + # A problem is a skill's or the library's, not one file's: the path is "", and the Trainer's repair goes back to + # the parent's library (hermit/spec.py `repair`, which restores named files only) + return [{"path": "", "problem": p} for p in library.problems(adapter)] diff --git a/hermit/agent/evolver/methods/rax/actor.py b/hermit/agent/evolver/methods/rax/actor.py index 285f9986..fb3a0d66 100644 --- a/hermit/agent/evolver/methods/rax/actor.py +++ b/hermit/agent/evolver/methods/rax/actor.py @@ -29,7 +29,8 @@ collect ends the session at the service (RAX's frontend stopped, as RAX stops it when the agent ends) and lets its lease go, and returns the session's facts (the judge scores its submitted bundle with RAX's formal batch); writes what the session merged into its library (library.export) and the session's notes and - code into the log + code into the log, and removes the .git of a session repository whose objects hold a key's value + (library.scrub); what it cannot read is recorded, and the session is judged as any other RAX's own checkout comes from agent.params.rax_root (its START_PROMPT.md, bridge and agent environment must be declared readable: environment.read). The config gives the Claude Code session RAX's frontend server on the command line @@ -60,6 +61,7 @@ LIBRARY_SERVER = "skill_library" # skill_library_merge's server (RAX's frontend serves it with the robot's) CLAUDE_MCP = ".rax-mcp.json" # the session's servers (claude.args: --mcp-config .rax-mcp.json) HOOK_FILE = "hook.json" # <run>/rax/hook.json: what the Stop hook asks the service with +LIBRARY_CLONE = library.rax.LIBRARY_DIR # skill-library/: the session's clone of its library repository NOTES = ("memory", "code") # the session's notes and controller code, kept in the log DENIED_TOOLS = ("WebFetch", "WebSearch") # RAX's Claude Code launcher's SUBAGENT_TOOLS = ("Agent", "Task") # ...and these when the session's subagent cap is 0 ('Task': the old name) @@ -388,6 +390,8 @@ def collect(task: dict, work: Path, log: Path, params: dict) -> dict: try: record_path = own(work) / "session.json" record = json.loads(record_path.read_text()) if record_path.is_file() else {} + if not isinstance(record, dict): + raise ValueError(f"not an object but {type(record).__name__}") except (OSError, ValueError) as exc: record = {"error": f"the session's record cannot be read: {type(exc).__name__}: {exc}"[:500]} exported = None @@ -404,6 +408,15 @@ def collect(task: dict, work: Path, log: Path, params: dict) -> dict: exported["name"] = record.get("name") (log / library.RECORD).write_text(json.dumps(exported, indent=1) + "\n") facts["library"] = {k: exported.get(k) for k in ("base", "head", "bundle", "error")} + # The run's directory is kept: a repository of the session's whose objects hold a key's value loses its .git. The + # two are found where `prepare` makes them, never where the (agent-writable) record says. + removed = {} + for name, repository in (("repository", own(work) / "library" / library.ROBOT), ("clone", work / LIBRARY_CLONE)): + held = library.scrub(repository) + if held: + removed[name] = held + if removed: + facts.setdefault("library", {})["removed_git"] = removed try: facts["notes"] = _keep_notes(work, log) except OSError as exc: diff --git a/hermit/agent/evolver/methods/rax/library.py b/hermit/agent/evolver/methods/rax/library.py index 78b48baf..60c25baf 100644 --- a/hermit/agent/evolver/methods/rax/library.py +++ b/hermit/agent/evolver/methods/rax/library.py @@ -10,11 +10,13 @@ evidence checks, the same replies, and later commits of the same session see what it merged; - after it (`collect`): `export` writes what the session merged (a git bundle of the repository's main past its first commit) into the run's log, without running git in a repository the agent could write, and none of it when it holds - the value of a key the session was given (`holds_key`: Hermit's redaction cannot reach a compressed object); + the value of a key the session was given (`holds_key`: Hermit's redaction cannot reach a compressed object); a + session repository whose objects hold one loses its .git (`scrub`), since the run's directory is kept; - the Evolver (`merge.py`, in the evolver sandbox): `build` makes the same repository of the step's adapter, and RAX's - `merge` takes in each session's bundle on a branch of its own, checking every changed skill again, and a merge whose - tree is no library this port can keep as an adapter (`library_files`) is undone; the merged tree is the next adapter - (`write_tree`). + `merge` takes in each session's bundle on a branch of its own, checking every changed skill again; a merge whose + tree the template's check refuses (`problems`: RAX's checks over every skill, which a merge runs only over the + skills a branch changed, as git names them: a renamed skill's old path is not among them) is undone; the merged tree + is the next adapter (`write_tree`). Every repository starts from one commit of the adapter's library files with a fixed author, date and file mode, so a session and the Evolver that start from the same adapter start from the same commit: RAX's merge base. Only the @@ -205,19 +207,24 @@ def export(repository: Path, base: str, out: Path) -> dict: return record -def holds_key(repository: Path, base: str, head: str) -> str | None: +def holds_key(repository: Path, base: str | None = None, head: str | None = None) -> str | None: """The name of a key-like variable of this process (hermit.redact.key_values: the keys the session was given) whose value is in one of the objects from `base` to `head` (their commits, trees and files, read one by one), or - None. Hermit scrubs key values out of the files a run keeps; a git object is compressed, out of its reach.""" + in any object of the repository when no range is given, or None. Hermit scrubs key values out of the files a run + keeps; a git object is compressed, out of its reach.""" from hermit.redact import key_values values = key_values() if not values: return None - ids = git("rev-list", "--objects", "--no-object-names", head, f"^{base}", cwd=repository) + if head is None: + command, ids = ["git", "cat-file", "--batch-all-objects", "--batch"], "" + else: + command = ["git", "cat-file", "--batch"] + ids = git("rev-list", "--objects", "--no-object-names", head, f"^{base}", cwd=repository) with tempfile.TemporaryFile() as given: given.write(ids.encode()) given.seek(0) - reader = subprocess.Popen(["git", "cat-file", "--batch"], cwd=repository, stdin=given, + reader = subprocess.Popen(command, cwd=repository, stdin=given, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env={**os.environ, **rax.GIT_ENV}) read_all = False @@ -242,6 +249,31 @@ def holds_key(repository: Path, base: str, head: str) -> str | None: return None +def scrub(repository: Path) -> str | None: + """A session's git repository (its library repository, its clone), kept with the run's directory: when one of its + objects holds the value of a key the session was given (`holds_key`), or they cannot be read to tell, its .git is + removed, since Hermit's redaction scrubs the files a run keeps, not git's compressed objects. The objects are read + from a copy without links (RAX's _copy_objects), as `export` reads them: no git runs in the agent's repository. + Returns what was found (the variable's name, or why the objects could not be read), or None.""" + git_dir = Path(repository) / ".git" + if git_dir.is_symlink() or not git_dir.is_dir(): + return None + try: + with tempfile.TemporaryDirectory(prefix="rax-scan-") as scratch: + bare = Path(scratch) / "objects.git" + bare.mkdir() + rax._copy_objects(git_dir / "objects", bare / "objects") + (bare / "refs").mkdir() + (bare / "HEAD").write_text("ref: refs/heads/main\n") + (bare / "config").write_text("[core]\n\trepositoryformatversion = 0\n\tbare = true\n") + held = holds_key(bare) + except (rax.LibraryError, OSError, subprocess.SubprocessError) as exc: + held = f"unreadable ({type(exc).__name__})" + if held: + shutil.rmtree(git_dir, ignore_errors=True) + return held + + def take_in(repository: Path, bundle: Path, record: dict, name: str, message: str) -> dict: """The Evolver's side: a session's bundle, fetched as data into a fresh clone of the Evolver's repository on branch session/<name>, merged by RAX's merge (every changed skill checked again). Returns RAX's reply.""" @@ -257,19 +289,36 @@ def take_in(repository: Path, bundle: Path, record: dict, name: str, message: st return {"merged": False, "reason": f"the bundle's main is {fetched}, not the recorded {record.get('head')}"} reply = merge(repository, name, workspace, message) if reply.get("merged"): - # RAX's merge checks the skills a branch changed; the adapter is the whole tree (library_files): a merge - # that leaves no library (INDEX.md gone, a link) is undone, and the step goes on without it + # RAX's merge checks the skills a branch changed, as git names them (a renamed skill's old path is not + # among them); the adapter must pass the template's check over every skill: a merge it refuses (INDEX.md + # gone, a link, a skill another uses renamed) is undone, and the step goes on without it try: - main_tree(repository, Path(scratch) / "merged") + tree = Path(scratch) / "merged" + main_tree(repository, tree) + found = problems(tree) except (rax.LibraryError, subprocess.SubprocessError, OSError) as exc: + found = [f"{type(exc).__name__}: {exc}"] + if found: git("reset", "-q", "--hard", str(reply["previous_main"]), cwd=repository) - return {"merged": False, "head": reply.get("head"), - "reason": f"RAX's merge took it in, but the merged library is no adapter: {exc}"[:500]} + return {"merged": False, "head": reply.get("head"), "problems": found[:20], + "reason": f"RAX's merge took it in, but the merged library fails the template's check: " + f"{found[0]}"[:500]} return reply +def problems(tree: Path) -> list[str]: + """The library's problems as the template's check finds them (.hermit/check.py): its files (`library_files`: the + root files, no link) and RAX's `validate_tree` over every skill (RAX's merge checks a branch's changed ones).""" + try: + files = library_files(tree) + except rax.LibraryError as exc: + return [str(exc)] + found, _ = rax.validate_tree(Path(tree), [f for f in files if f != "README.md"]) + return found + + def main_tree(repository: Path, into: Path) -> list[str]: - """The repository's main written out into `into` (a new directory); returns its library files (library_files, + """The repository's main written out into `into` (a new directory); returns its library files (`library_files`, which refuses a tree that is no library).""" into = Path(into) into.mkdir() diff --git a/tests/methods/rax/test_rax.py b/tests/methods/rax/test_rax.py index 6d2e2d21..c52d2512 100644 --- a/tests/methods/rax/test_rax.py +++ b/tests/methods/rax/test_rax.py @@ -179,22 +179,29 @@ def test_the_template_root_passes_its_own_check_and_is_raxs_empty_library(tmp_pa def test_the_check_runs_raxs_checks_on_every_skill_and_refuses_links(tmp_path): """A valid skill passes; a verified skill short of its runs, a skill without its index row and a link are - refused, each naming the path the Trainer repairs.""" + refused. A problem is a skill's or the library's, not one file's (path ""), so the Trainer's repair, which + restores named files only, goes back to the parent's library, and never trips over a skill's directory.""" + from hermit.spec import repair adapter = seed(tmp_path) add_skill(adapter, "grasp-bowl") add_skill(adapter, "place-plate", status="verified", runs=2) assert spec(adapter) == {"passed": True, "issues": []} + parent = tmp_path / "parent" + shutil.copytree(adapter, parent) add_skill(adapter, "open-drawer", status="verified", runs=1) add_skill(adapter, "close-drawer", index=False) issues = spec(adapter)["issues"] - assert any(i["path"] == "skills/open-drawer" and "verified needs at least 2" in i["problem"] for i in issues) - assert any(i["path"] == "INDEX.md" and "skills/close-drawer/SKILL.md" in i["problem"] for i in issues) - shutil.rmtree(adapter / "skills" / "open-drawer") - shutil.rmtree(adapter / "skills" / "close-drawer") + assert {i["path"] for i in issues} == {""} + assert any("skills/open-drawer" in i["problem"] and "verified needs at least 2" in i["problem"] for i in issues) + assert any("INDEX.md needs a row linking skills/close-drawer/SKILL.md" in i["problem"] for i in issues) + final, repaired = repair(adapter, TEMPLATE, parent) + assert final.passed and repaired and L.library_files(adapter) == L.library_files(parent) (adapter / "skills" / "grasp-bowl" / "code" / "alias.py").symlink_to("run.py") assert not spec(adapter)["passed"] with pytest.raises(rax.LibraryError, match="links are not allowed"): L.library_files(adapter) + final, _ = repair(adapter, TEMPLATE, parent) + assert final.passed and not (adapter / "skills" / "grasp-bowl" / "code" / "alias.py").is_symlink() # ---------- the library on both sides of a step ---------- @@ -864,9 +871,38 @@ def broken(*_): facts = A.collect({"id": TASK}, work, log, {}) assert facts["library"]["bundle"] is None and "cannot be exported" in facts["library"]["error"] assert json.loads((log / L.RECORD).read_text())["error"] == facts["library"]["error"] # the Evolver's reason - (work.parent / "rax" / "session.json").write_text("{not json") + for broken_record in ("{not json", "[]", '"a string"'): + (work.parent / "rax" / "session.json").write_text(broken_record) + facts = A.collect({"id": TASK}, work, log, {}) + assert "record cannot be read" in facts["library"]["error"] and facts["notes"]["files"] == 1 + + +def test_collect_removes_the_git_of_a_session_repository_that_holds_a_key(tmp_path, monkeypatch): + """The run's directory is kept, and Hermit's redaction scrubs its files, not git's compressed objects: a key's value + the session committed (here into its clone, then deleted) costs the clone its .git, wherever the record points; a + repository that holds no key keeps its own.""" + secret = "sk-test-" + "7" * 24 + monkeypatch.setenv("RAX_TEST_API_KEY", secret) + adapter = seed(tmp_path) + repository, work, base = session(tmp_path, adapter, "s1") + _session_record(work, {"name": "s1", "repository": str(tmp_path / "elsewhere"), "base": base}) + clone = work / rax.LIBRARY_DIR + (clone / "notes.txt").write_text(secret) + commit(clone, "a key") + (clone / "notes.txt").unlink() + commit(clone, "the key removed") + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + monkeypatch.setenv("RAX_SERVICE_URL", f"http://127.0.0.1:{s.getsockname()[1]}") + for name in ("NO_PROXY", "no_proxy"): + monkeypatch.setenv(name, "127.0.0.1,localhost") + log = tmp_path / "log" + log.mkdir() facts = A.collect({"id": TASK}, work, log, {}) - assert "record cannot be read" in facts["library"]["error"] and facts["notes"]["files"] == 1 + assert facts["library"]["removed_git"] == {"clone": "RAX_TEST_API_KEY"} and secret not in json.dumps(facts) + assert not (clone / ".git").exists() and (clone / "INDEX.md").is_file() # the files stay (Hermit scrubs them) + assert (repository / ".git").is_dir() # it holds no key + assert L.scrub(repository) is None and (repository / ".git").is_dir() # ---------- the Evolver ---------- @@ -991,6 +1027,41 @@ def slow(*_): assert reply["merged"] is False and reply["reason"].startswith("TimeoutExpired") +def test_the_evolver_undoes_a_merge_the_template_check_refuses_though_raxs_merge_saw_no_problem(tmp_path): + """RAX's merge checks the skills a branch changed, as `git diff --name-only` names them: a renamed skill's old path + is not among them. A session that renames a skill another one uses, or moves a skill's only image into another, + is merged in its own repository and accepted by RAX's merge again in the Evolver; the merged library fails the + template's check (RAX's checks over every skill), so the Evolver undoes the merge and says why.""" + adapter = seed(tmp_path) + add_skill(adapter, "base-skill") + add_skill(adapter, "user-skill") + used = adapter / "skills" / "user-skill" / "SKILL.md" + used.write_text(used.read_text().replace("entry: code/run.py\n", "entry: code/run.py\nuses: [base-skill]\n")) + assert spec(adapter)["passed"] + for n, change in enumerate(("rename", "image")): + repository, work, base = session(tmp_path, adapter, f"s{n}", run=f"run{n}") + clone = work / rax.LIBRARY_DIR + if change == "rename": + L.git("mv", "skills/base-skill", "skills/better-skill", cwd=clone) + for name in ("INDEX.md", "skills/better-skill/SKILL.md"): + (clone / name).write_text((clone / name).read_text().replace("base-skill", "better-skill")) + else: + L.git("mv", "skills/base-skill/evidence/images/start.png", + "skills/user-skill/evidence/images/from-base.png", cwd=clone) + commit(clone, change) + merged = L.merge(repository, f"s{n}", work, change) + assert merged["merged"], merged # RAX's merge, in the session + record = L.export(repository, base, tmp_path / f"log{n}") + evolver = tmp_path / f"evolver{n}" / L.ROBOT + assert L.build(adapter, evolver) == base + taken = L.take_in(evolver, tmp_path / f"log{n}" / L.BUNDLE, record, f"s{n}", "m") + assert taken["merged"] is False and "fails the template's check" in taken["reason"], taken + assert any(("uses 'base-skill'" if change == "rename" else "needs at least one image") in p + for p in taken["problems"]), taken["problems"] + assert L.git("rev-parse", "main", cwd=evolver).strip() == base # undone + assert spec(adapter)["passed"] + + def test_the_evolver_reads_no_log_outside_the_step(tmp_path, monkeypatch): """A record whose trajectory leaves the step, or has none, is not read.""" step = tmp_path / "current" From 1db75f82059b00ae8f72baaa87d96d296b150676 Mon Sep 17 00:00:00 2001 From: iamziyuzhao <iamziyuzhao@gmail.com> Date: Sun, 29 Nov 2026 15:51:06 -0500 Subject: [PATCH 6/7] RAX: RAX's refund note on relaunch; no git store in the notes; cleaner restarts and tests Round 4 of the post-PR audit (7293cf7): no P1, no P2; 4 P3 and 5 nits. - The Stop hook's relaunch carries the note RAX's launcher adds to a run's prompt: the episodes that ended uncharged, each told once. The service runs RAX's own report_refunds (services/exploration/pool.py) when the hook would relaunch the session (POST /explored with relaunch). - The session's notes keep no git repository's own directory (.git, or any directory with a HEAD and objects/): the learning material is scrubbed of key values as text, which git's compressed objects are not. - A service started after a killed one stops the frontends that one left all at once, within STOP_SECONDS in all, and launch.sh waits 180 s for it instead of 30 s. - Tests: the restart test stops its second service, and the test directory is removed whole (a run-trees directory without its read bit included), or the test fails. - Nits: the merge tool refuses arguments that are not an object as RAX's frontend does (stage request); the eval configs carry no checkpoint setting; collect exports from where prepare made the repository; a Gemini call counts as spent, so it blocks a second registration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/methods/rax.md | 2 +- examples/libero/rax/eval_official.yaml | 1 - examples/libero/rax/eval_val.yaml | 1 - examples/libero/rax/launch.sh | 2 +- examples/libero/rax/service.py | 39 +++++++++------- hermit/agent/evolver/methods/rax/actor.py | 15 ++++--- .../evolver/methods/rax/library_server.py | 17 ++++--- hermit/agent/evolver/methods/rax/stop_hook.py | 25 ++++++----- tests/methods/rax/test_rax.py | 45 ++++++++++++++++--- 9 files changed, 101 insertions(+), 46 deletions(-) diff --git a/docs/methods/rax.md b/docs/methods/rax.md index eaea1105..5061f638 100644 --- a/docs/methods/rax.md +++ b/docs/methods/rax.md @@ -157,7 +157,7 @@ URL, default `RAX_SERVICE_URL`) and `bin` (the CLI). The session's settings are | Agent | Claude Code, Claude Opus 5.5 at xhigh, its own home, its servers alone (`--strict-mcp-config`); `acceptEdits` with an allow list (its MCP server, reads of its readable paths); denied: the web tools, the subagent tools at a subagent cap of 0, edits of the workspace's `.claude/` and `.mcp.json`; its commands in Claude Code's own sandbox, allowed without asking (writes in the workspace and the socket's directory, no network) | the same model, effort, MCP flags and deny rules (the project's `.claude/settings.json`, with `.rax-mcp.json` guarded too), on Hermit's Claude Code agent, whose `bypassPermissions` takes the place of RAX's `acceptEdits`, allow list and Claude Code sandbox: the CLI and all it runs are in the task sandbox (bubblewrap), which shows only declared paths, lets it write only its run's directory (workspace, the CLI's home, log, `<run>/rax`) and its own `/tmp`, and reaches only the model provider's hosts and the service's forwarded port; so a command, unlike a file tool, can still write `.claude/`, and what it writes there runs in the same sandbox | the task sandbox is the boundary | | Prompt and workspace | `START_PROMPT.md`; `prepare_workspace` | RAX's, byte for byte; with an adapter, also the library's clone, RAX's continual-learning skill and the two library paragraphs of `real/rainbow`'s `AGENTS.md` (`ADAPTER.md`), and Hermit's deployment: the adapter's copy `hermit/rax/` and Hermit's managed block in `CLAUDE.md` after `@AGENTS.md` (a note that the adapter's paths are relative to `hermit/rax/`, which `ADAPTER.md` overrides for its own) | the library is `real/rainbow`'s, which `libero-pro/native` lacks | | Robot tools | RAX's frontend, through RAX's bridge on a socket | the same, on the host; the run tree in the service's directory, shown read-only in the task sandbox (RAX's agent writes only its workspace and the socket's directory) | the task sandbox shows only declared paths | -| Relaunch | the launcher runs the CLI again (`--resume`) with `CONTINUE_PROMPT` while exploration is open, at most 3 times | a Stop hook continues the same CLI with the same prompt, without its clause about stopped background workers (here they run on); exploration closed by the launcher's own rule (`exploration_closed`), which the service applies | Hermit runs one CLI per call | +| Relaunch | the launcher runs the CLI again (`--resume`) with `CONTINUE_PROMPT` while exploration is open, at most 3 times, adding to a run's prompt its note of the episodes that ended uncharged (`report_refunds`, each told once) | a Stop hook continues the same CLI with the same prompt, without its clause about stopped background workers (here they run on), with RAX's note (the service runs `report_refunds` when the hook relaunches); exploration closed by the launcher's own rule (`exploration_closed`), which the service applies | Hermit runs one CLI per call | | Error relaunch, adaptation stage | after a provider error, the same conversation resumed after a pause (`ERROR_PROMPT`, up to 5 in a row); after the login's usage limit, the same conversation resumed once the window resets (`USAGE_PROMPT`, up to 10 times); up to 5 adaptation episodes on swap layouts (collection 6) | in part: a session the login's plan refuses (its usage window) runs again in the same workspace once the plan allows (Hermit's Claude Code agent, `plan_rerun`), as a new conversation from RAX's start prompt, not RAX's resumed one: RAX's session, its budget and the agent's notes (`memory/PROGRESS.md`, which RAX's prompts send it back to) are as they were, the conversation's context is not. A session the CLI reports as failed (an error result, a crash) is scored 0 without its bundle judged (Hermit judges no failed session), and its merges are taken in; one Hermit's clock ends is judged as any other; one the provider stops serving past Claude Code's own retries fails the call before `collect`: scored 0, its merges left out. Hermit's second attempt of a call is off (`claude.retries: 1`): it would remove the session's workspace and log and start the session again, which RAX never does. No adaptation | Hermit runs one CLI per call and resumes no conversation; scope | | Agent pause | the agent CLI and its processes are stopped (SIGSTOP) while a bundle is copied and rehearsed | not paused: the main turn waits on the call, but background commands and subagents run on; the bundle copied is the registered snapshot | the CLI's processes are in the task sandbox's process namespace, which the host's frontend cannot signal | | Bundles | run at the agent's workspace path, in a fresh bubblewrap sandbox and simulator per episode | run at RAX's session workspace path (not the Hermit workspace's); the same sandbox, which shows none of the skill library: `ADAPTER.md` says to copy into the bundle what it uses of a library skill | RAX's supervisor names that path; RAX's library comes from `real/rainbow`, whose controllers run in the agent's workspace | diff --git a/examples/libero/rax/eval_official.yaml b/examples/libero/rax/eval_official.yaml index 082a1b75..e47d6d9d 100644 --- a/examples/libero/rax/eval_official.yaml +++ b/examples/libero/rax/eval_official.yaml @@ -52,7 +52,6 @@ sandbox: trainer: run_name: rax-libero-official epochs: 1 - save_freq: {steps: 10, epochs: 1} # rax-libero/ckpt-step-10, -20, -30: the checkpoints eval_val.yaml compares call_timeout_min: 60 # the Evolver's merge budget: {usd: null, hours: 2000} eval: diff --git a/examples/libero/rax/eval_val.yaml b/examples/libero/rax/eval_val.yaml index 11fce057..8b958a91 100644 --- a/examples/libero/rax/eval_val.yaml +++ b/examples/libero/rax/eval_val.yaml @@ -53,7 +53,6 @@ sandbox: trainer: run_name: rax-libero-val epochs: 1 - save_freq: {steps: 10, epochs: 1} # rax-libero/ckpt-step-10, -20, -30: the checkpoints eval_val.yaml compares call_timeout_min: 60 # the Evolver's merge budget: {usd: null, hours: 2000} eval: diff --git a/examples/libero/rax/launch.sh b/examples/libero/rax/launch.sh index 6853e2f3..47cfeef6 100755 --- a/examples/libero/rax/launch.sh +++ b/examples/libero/rax/launch.sh @@ -91,7 +91,7 @@ PATH="$RAX_BIN:$PATH" "$RAX_PYTHON" "$HERE/service.py" --port "$PORT" --rax-root SERVICE=$! trap 'kill "$SERVICE" 2>/dev/null || true; wait "$SERVICE" 2>/dev/null || true' EXIT ours() { curl -sf "http://127.0.0.1:$PORT/health" 2>/dev/null | grep -qF "\"nonce\": \"$NONCE\""; } -for _ in $(seq 1 30); do +for _ in $(seq 1 180); do # it first stops what a killed service left (STOP_SECONDS, 120 s) ours && break kill -0 "$SERVICE" 2>/dev/null || { echo "the RAX service failed (port taken?): $OUT/rax-service.log" >&2; exit 1; } sleep 1 diff --git a/examples/libero/rax/service.py b/examples/libero/rax/service.py index eb089d2d..7dbcfe20 100644 --- a/examples/libero/rax/service.py +++ b/examples/libero/rax/service.py @@ -97,10 +97,10 @@ def gemini_usd(state: dict) -> float: def spent(root: Path) -> bool: """Whether a RAX session has spent anything: an episode started (or charged in its parallel pool), a bundle - registered, a result, a submission.""" + registered, a result, a submission, a Gemini call.""" state, pool = _json(Path(root) / "state.json"), _json(Path(root) / "exploration" / "state.json") return bool(state.get("exploration_started") or state.get("bundles") or state.get("results") - or state.get("submission") or pool.get("episodes")) + or state.get("submission") or pool.get("episodes") or gemini_usd(state)) class Ledger: @@ -176,18 +176,19 @@ def __init__(self, args, rows: dict): def _reap(self) -> None: """What a service before this one left open (it ended without stopping its sessions: killed, or its machine - restarted): each unfinished session's frontend, if still running, is stopped, and the session ended.""" - for key, entry in list(self.ledger.data.items()): - if entry.get("finished"): - continue - pid = entry.get("frontend_pid") - if _is_frontend(pid, entry["root"]): - os.kill(int(pid), signal.SIGTERM) - deadline = time.monotonic() + STOP_SECONDS - while _is_frontend(pid, entry["root"]) and time.monotonic() < deadline: - time.sleep(0.2) - if _is_frontend(pid, entry["root"]): - os.kill(int(pid), signal.SIGKILL) + restarted): each unfinished session's frontend, if still running, is stopped (all at once, within STOP_SECONDS + in all: launch.sh waits that long for the service), and the session ended.""" + left = [entry for entry in self.ledger.data.values() if not entry.get("finished")] + running = [(int(e["frontend_pid"]), e["root"]) for e in left if _is_frontend(e.get("frontend_pid"), e["root"])] + for pid, _ in running: + os.kill(pid, signal.SIGTERM) + deadline = time.monotonic() + STOP_SECONDS + while any(_is_frontend(pid, root) for pid, root in running) and time.monotonic() < deadline: + time.sleep(0.2) + for pid, root in running: + if _is_frontend(pid, root): + os.kill(pid, signal.SIGKILL) + for entry in left: self._end(entry, None, abandoned=True) def _end(self, entry: dict, frontend: Frontend | None, **mark) -> dict: @@ -392,7 +393,9 @@ def lease(self, body: dict) -> tuple[str, str]: def explored(self, body: dict) -> dict: """Whether a session's exploration is closed (its Stop hook asks), by RAX's launcher's rule on the session's directory (services/agent_formal/checkpoint.py exploration_closed: the marker RAX's frontend writes once - exploration is closed, or the submission), never by asking the frontend, which a long call can hold.""" + exploration is closed, or the submission), never by asking the frontend, which a long call can hold. With + `relaunch` (the hook continues the session if it is open), also the note RAX's launcher adds to a run's prompt + (services/exploration/pool.py report_refunds: the episodes that ended uncharged, each told once).""" key = str(Path(str(body.get("workspace", ""))).resolve()) with self.ledger.lock: entry = self.ledger.data.get(key) @@ -401,7 +404,11 @@ def explored(self, body: dict) -> dict: from services.agent_formal.checkpoint import exploration_closed from services.controller.frontend import load_configuration config = load_configuration(Path(entry["root"]) / "configuration.json") - return {"ok": True, "closed": bool(exploration_closed(config))} + closed = bool(exploration_closed(config)) + if closed or not body.get("relaunch"): + return {"ok": True, "closed": closed} + from services.exploration.pool import report_refunds + return {"ok": True, "closed": closed, "note": report_refunds(Path(config.root) / "exploration")} def lease_ended(self, key: str, session: str) -> None: """A lease's connection closed: the process that ran the session is gone. The session, if `collect` did not diff --git a/hermit/agent/evolver/methods/rax/actor.py b/hermit/agent/evolver/methods/rax/actor.py index fb3a0d66..f98340dc 100644 --- a/hermit/agent/evolver/methods/rax/actor.py +++ b/hermit/agent/evolver/methods/rax/actor.py @@ -349,7 +349,9 @@ def answer(last_message: str, task: dict) -> dict: def _keep_notes(work: Path, log: Path) -> dict: """The session's notes and code (memory/, code/) in the log: regular files up to NOTE_FILE_BYTES each and - NOTE_BYTES in all, never through a link.""" + NOTE_BYTES in all, never through a link, and no git repository's own directory (.git, or any directory with a + HEAD and objects/): the learning material is scrubbed of key values as text, which git's compressed objects + are not.""" kept, total = 0, 0 for name in NOTES: top = work / name @@ -357,7 +359,8 @@ def _keep_notes(work: Path, log: Path) -> dict: continue for directory, dirs, files in os.walk(top, followlinks=False): here = Path(directory) - dirs[:] = sorted(d for d in dirs if not (here / d).is_symlink() and d != "__pycache__") + dirs[:] = sorted(d for d in dirs if not (here / d).is_symlink() and d not in ("__pycache__", ".git") + and not ((here / d / "HEAD").is_file() and (here / d / "objects").is_dir())) for file in sorted(files): path = here / file if path.is_symlink() or not path.is_file(): @@ -398,8 +401,8 @@ def collect(task: dict, work: Path, log: Path, params: dict) -> dict: if record.get("error"): exported = {"base": None, "head": None, "bundle": None, "error": record["error"]} elif record.get("repository") and record.get("base"): - try: - exported = library.export(Path(record["repository"]), record["base"], log) + try: # where prepare made it, whatever the record says + exported = library.export(own(work) / "library" / library.ROBOT, record["base"], log) except Exception as exc: # noqa: BLE001 - a repository the agent broke (log / library.BUNDLE).unlink(missing_ok=True) exported = {"base": record["base"], "head": None, "bundle": None, @@ -408,8 +411,8 @@ def collect(task: dict, work: Path, log: Path, params: dict) -> dict: exported["name"] = record.get("name") (log / library.RECORD).write_text(json.dumps(exported, indent=1) + "\n") facts["library"] = {k: exported.get(k) for k in ("base", "head", "bundle", "error")} - # The run's directory is kept: a repository of the session's whose objects hold a key's value loses its .git. The - # two are found where `prepare` makes them, never where the (agent-writable) record says. + # The run's directory is kept: a repository of the session's whose objects hold a key's value loses its .git (the + # two where `prepare` makes them, as the export reads the first) removed = {} for name, repository in (("repository", own(work) / "library" / library.ROBOT), ("clone", work / LIBRARY_CLONE)): held = library.scrub(repository) diff --git a/hermit/agent/evolver/methods/rax/library_server.py b/hermit/agent/evolver/methods/rax/library_server.py index f640ce69..2ef12fda 100644 --- a/hermit/agent/evolver/methods/rax/library_server.py +++ b/hermit/agent/evolver/methods/rax/library_server.py @@ -46,7 +46,7 @@ def session(workspace: Path) -> dict: return record -def failure(exc: BaseException) -> dict: +def failure(exc: BaseException, stage: str = STAGE) -> dict: """RAX's public_failure of a skill_library_merge call (real/rainbow 36c926c services/controller/errors.py, at the frontend's stage of the call): an expected refusal's message alone, anything else with its innermost frames; URLs, the host's directories and credentials removed.""" @@ -61,14 +61,16 @@ def failure(exc: BaseException) -> dict: reason = re.sub(r"\bsk-[A-Za-z0-9_-]+", "[redacted key]", reason) if len(reason) > MAX_REASON: reason = reason[:MAX_REASON // 4] + "\n...\n" + reason[-(MAX_REASON * 3 // 4):] - return {"type": type(exc).__name__, "operation": NAME, "stage": STAGE, "reason": reason} + return {"type": type(exc).__name__, "operation": NAME, "stage": stage, "reason": reason} def call(workspace: Path, arguments: dict) -> dict: """RAX's handler: one-line message only, then RAX's merge of the session's branch.""" from hermit.agent.evolver.methods.rax import library - if not isinstance(arguments, dict) or set(arguments) - {"message"} or not str(arguments.get("message", "")).strip(): + if not isinstance(arguments, dict): + raise ValueError("Arguments must be an object") + if set(arguments) - {"message"} or not str(arguments.get("message", "")).strip(): raise ValueError("skill_library_merge takes message (one line)") record = session(workspace) return library.merge(Path(record["repository"]), str(record["name"]), workspace, str(arguments["message"])) @@ -96,11 +98,16 @@ def handle(workspace: Path, request) -> dict | None: params = request.get("params") or {} if params.get("name") != NAME: raise PermissionError("Unknown tool") + arguments, stage = params.get("arguments", {}), "request" try: - value = call(workspace, params.get("arguments", {})) + if not isinstance(arguments, dict): # RAX's frontend refuses it first, at the request stage + raise ValueError("Arguments must be an object") + stage = STAGE + value = call(workspace, arguments) result = {"content": [{"type": "text", "text": json.dumps(value, allow_nan=False)}]} except Exception as exc: # the agent's error to read, as RAX's frontend returns one - result = {"isError": True, "content": [{"type": "text", "text": json.dumps({"error": failure(exc)})}]} + error = failure(exc, stage) + result = {"isError": True, "content": [{"type": "text", "text": json.dumps({"error": error})}]} else: raise PermissionError("Unsupported method") return {"jsonrpc": "2.0", "id": ident, "result": result} diff --git a/hermit/agent/evolver/methods/rax/stop_hook.py b/hermit/agent/evolver/methods/rax/stop_hook.py index b5e8a644..a9da65b5 100644 --- a/hermit/agent/evolver/methods/rax/stop_hook.py +++ b/hermit/agent/evolver/methods/rax/stop_hook.py @@ -1,7 +1,9 @@ """RAX's relaunch policy as the session's Stop hook (harness/codex_cli/auto_research.py `run_agent`, libero-pro/native 1767412): while exploration is open, a session whose turn ends goes on with RAX's CONTINUE_PROMPT, at most -MAX_RELAUNCHES times. RAX runs the CLI again on the same conversation; a Stop hook keeps the same CLI going, so the -prompt leaves out RAX's clause that the turn's background workers were stopped (here they keep running). +MAX_RELAUNCHES times, and with the note RAX's launcher adds to a run's prompt when episodes ended uncharged +(services/exploration/pool.py report_refunds, which the service runs). RAX runs the CLI again on the same +conversation; a Stop hook keeps the same CLI going, so the prompt leaves out RAX's clause that the turn's background +workers were stopped (here they keep running). Exploration is open as RAX's launcher decides it (services/agent_formal/checkpoint.py `exploration_closed`: the marker RAX's frontend writes once exploration is closed, or the submission), which the RAX service applies to the session's @@ -30,20 +32,20 @@ HOOK_FILE = "hook.json" -def closed(mine: Path, timeout: float = 30.0) -> bool: - """Whether the session's exploration is closed, as the RAX service answers by RAX's rule (POST /explored), straight - to its loopback port (no proxy).""" +def explored(mine: Path, relaunch: bool, timeout: float = 30.0) -> dict: + """The RAX service's answer (POST /explored), straight to its loopback port (no proxy): whether the session's + exploration is closed, by RAX's rule, and, when the hook would relaunch it, RAX's note for the next prompt.""" asked = json.loads((mine / HOOK_FILE).read_text()) request = urllib.request.Request(str(asked["url"]).rstrip("/") + "/explored", method="POST", - data=json.dumps({"workspace": asked["workspace"], - "session": asked["session"]}).encode(), + data=json.dumps({"workspace": asked["workspace"], "session": asked["session"], + "relaunch": relaunch}).encode(), headers={"Content-Type": "application/json"}) opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) with opener.open(request, timeout=timeout) as response: reply = json.loads(response.read()) if not reply.get("ok"): raise RuntimeError(str(reply.get("error"))[:300]) - return bool(reply["closed"]) + return reply def main(argv: list[str] | None = None) -> int: @@ -61,9 +63,12 @@ def main(argv: list[str] | None = None) -> int: count = int(count_file.read_text().strip() or 0) if count_file.is_file() else 0 except (OSError, ValueError): count = MAX_RELAUNCHES # a count that cannot be read: no relaunch is owed + note = "" try: - if closed(mine): + reply = explored(mine, relaunch=count < MAX_RELAUNCHES) + if reply["closed"]: return 0 + note = str(reply.get("note") or "") except Exception as exc: # no answer: open, as RAX counts a state it cannot read print(f"rax stop hook: {type(exc).__name__}: {exc}", file=sys.stderr) if count >= MAX_RELAUNCHES: @@ -74,7 +79,7 @@ def main(argv: list[str] | None = None) -> int: print(f"rax stop hook: the relaunch count cannot be kept ({type(exc).__name__}: {exc}): the turn ends", file=sys.stderr) return 0 - print(json.dumps({"decision": "block", "reason": CONTINUE_PROMPT})) + print(json.dumps({"decision": "block", "reason": f"{CONTINUE_PROMPT}\n\n{note}" if note else CONTINUE_PROMPT})) return 0 diff --git a/tests/methods/rax/test_rax.py b/tests/methods/rax/test_rax.py index c52d2512..6c90e2b8 100644 --- a/tests/methods/rax/test_rax.py +++ b/tests/methods/rax/test_rax.py @@ -66,7 +66,17 @@ def tmp_path(): path = Path(tempfile.mkdtemp(dir=base, prefix="rax-")).resolve() yield path if not os.environ.get("KEEP_TEST_DIRS"): - shutil.rmtree(path, ignore_errors=True) + _remove(path) + + +def _remove(path: Path) -> None: + """A test's directory removed whole: a directory without its read bit (a service's run trees) is opened first.""" + def opened(function, name, exc): + if isinstance(exc, PermissionError) and os.path.isdir(name) and not os.path.islink(name): + os.chmod(name, 0o700) + shutil.rmtree(name, ignore_errors=True) + shutil.rmtree(path, onexc=opened) + assert not path.exists(), f"{path} was left behind" @pytest.fixture(autouse=True) @@ -353,6 +363,10 @@ def test_the_merge_tool_is_raxs_skill_library_merge(tmp_path): assert result["isError"] and json.loads(result["content"][0]["text"])["error"] == { "type": "ValueError", "operation": "skill_library_merge", "stage": "validation", "reason": "skill_library_merge takes message (one line)"} # RAX's public_failure + result = rpc("tools/call", {"name": "skill_library_merge", "arguments": ["grasp-bowl"]})["result"] + assert json.loads(result["content"][0]["text"])["error"] == { + "type": "ValueError", "operation": "skill_library_merge", "stage": "request", + "reason": "Arguments must be an object"} # RAX's frontend, before the tool add_skill(work / rax.LIBRARY_DIR, "grasp-bowl") commit(work / rax.LIBRARY_DIR, "grasp-bowl") result = rpc("tools/call", {"name": "skill_library_merge", "arguments": {"message": "grasp-bowl: draft"}})["result"] @@ -426,11 +440,17 @@ def hook(where=work): assert done.returncode == 0, done.stderr return json.loads(done.stdout) if done.stdout.strip() else None + note = ("Harness note: these exploration episodes ended without running to their own end, because the session " + "stopped or the episode worker failed: episode 2 (failed: worker died).") + service.refunds["notes"].append(note) # RAX's launcher's note, with the next prompt only try: for n, where in ((1, work), (2, work / "code" / "grasp"), (3, tmp_path)): # wherever the agent cd'd to - assert hook(where) == {"decision": "block", "reason": H.CONTINUE_PROMPT} + assert hook(where) == {"decision": "block", + "reason": f"{H.CONTINUE_PROMPT}\n\n{note}" if n == 1 else H.CONTINUE_PROMPT} assert (mine / "relaunches").read_text().strip() == str(n) + assert service.refunds["asked"] == [service.made[0] / "exploration"] * 3 # only when it relaunches assert hook() is None # three relaunches: the turn ends + assert len(service.refunds["asked"]) == 3 (mine / "relaunches").write_text("0\n") (service.made[0] / "exploration-complete.json").write_text("{}") # RAX's frontend closed exploration assert hook() is None @@ -553,11 +573,17 @@ def service(tmp_path, rax_root, monkeypatch): json.loads((config.root / "state.json").read_text()).get("submission")) frontend = ModuleType("services.controller.frontend") frontend.load_configuration = lambda path: SimpleNamespace(root=Path(path).parent) + refunds = {"notes": [], "asked": []} # RAX's report_refunds: each note told once + pool = ModuleType("services.exploration.pool") + pool.report_refunds = lambda root: refunds["asked"].append(Path(root)) or ( + refunds["notes"].pop(0) if refunds["notes"] else "") for name, module in (("services", ModuleType("services")), ("services.mcp_contract", contract), ("services.agent_formal", ModuleType("services.agent_formal")), ("services.agent_formal.checkpoint", checkpoint), ("services.controller", ModuleType("services.controller")), - ("services.controller.frontend", frontend)): + ("services.controller.frontend", frontend), + ("services.exploration", ModuleType("services.exploration")), + ("services.exploration.pool", pool)): monkeypatch.setitem(sys.modules, name, module) for name in ("NO_PROXY", "no_proxy"): monkeypatch.setenv(name, "127.0.0.1,localhost") @@ -567,6 +593,7 @@ def service(tmp_path, rax_root, monkeypatch): args.state.mkdir() rows = {row["id"]: row for group in _load("rax_rows", EXAMPLE / "rows.py").rows().values() for row in group} svc = S_.Service(args, rows) + svc.refunds = refunds svc.made, svc.frontends_started, svc.configured = [], [], [] svc.state = {"exploration_started": 2, "results": [{"mode": "rehearsal"}, {"mode": "interactive"}], "submission": {"bundle": "bundle-1", "sha256": "ab"}, "gemini_spend": {"reported": 1_500_000_000}} @@ -852,6 +879,10 @@ def test_collect_keeps_the_session_when_the_service_cannot_end_it(tmp_path, monk _session_record(work, {"name": "s1", "repository": str(repository), "base": base}) (work / "memory").mkdir() (work / "memory" / "PROGRESS.md").write_text("notes\n") + for store in ("code/controller/.git", "code/hidden.git"): # git's own directories: not kept + (work / store / "objects" / "0c").mkdir(parents=True) + (work / store / "HEAD").write_text("ref: refs/heads/main\n") + (work / store / "objects" / "0c" / "7a89").write_bytes(b"x\x9c compressed") with socket.socket() as s: s.bind(("127.0.0.1", 0)) port = s.getsockname()[1] # a port nothing listens on @@ -863,6 +894,7 @@ def test_collect_keeps_the_session_when_the_service_cannot_end_it(tmp_path, monk facts = A.collect({"id": TASK}, work, log, {}) assert "finish_error" in facts and facts["session"] is None and facts["notes"]["files"] == 1 assert facts["library"] == {"base": base, "head": base, "bundle": None, "error": None} + assert not (log / "session" / "code").exists() # nothing of the two git stores # a library the session broke (it can write all of <run>/rax): recorded, the session judged as any other def broken(*_): @@ -1222,6 +1254,7 @@ def test_a_service_started_again_ends_what_the_last_one_left_open_and_two_never_ assert data["/w/other"]["abandoned"] and data["/w/done"] == ledger["/w/done"] with pytest.raises(RuntimeError, match="another RAX service uses"): service.module.Service(args, service.rows) + again.stop() # its run trees can be listed (and removed) again again.held.close() finally: left.kill() @@ -1277,14 +1310,16 @@ def test_the_services_routes_refuse_with_their_reason_and_its_health_names_its_l def test_a_session_has_spent_something_once_any_of_raxs_records_says_so(tmp_path): - """An episode started, one charged in the parallel pool, a bundle, a result or a submission: no second session.""" + """An episode started, one charged in the parallel pool, a bundle, a result, a submission or a Gemini call: no + second session.""" S_ = _load("rax_service", EXAMPLE / "service.py") root = tmp_path / "session" (root / "exploration").mkdir(parents=True) assert S_.spent(root) is False and S_.spent(tmp_path / "nowhere") is False (root / "state.json").write_text(json.dumps({"exploration_started": 0, "bundles": {}, "results": []})) assert S_.spent(root) is False - for state in ({"exploration_started": 1}, {"bundles": {"b": {}}}, {"results": [{}]}, {"submission": {"b": 1}}): + for state in ({"exploration_started": 1}, {"bundles": {"b": {}}}, {"results": [{}]}, {"submission": {"b": 1}}, + {"gemini_spend": {"reported": 1000}}): (root / "state.json").write_text(json.dumps(state)) assert S_.spent(root) is True, state (root / "state.json").write_text("{}") From 32ccaafea1016255b00de55155acba708077033c Mon Sep 17 00:00:00 2001 From: iamziyuzhao <iamziyuzhao@gmail.com> Date: Sun, 29 Nov 2026 16:41:47 -0500 Subject: [PATCH 7/7] RAX: no key in any git store of the run; a bounded re-registration the lease still covers Round 5 of the post-PR audit (1db75f8): no P1, no P2; 2 P3 and 4 nits. - Every git store in the run's directory and the log (a .git, or any directory git takes for one: the session's library repository and clone, a repository of the agent's own, memory/ made a bare one) whose objects hold a key's value loses its objects/ (library.git_stores, library.scrub); collect reads the notes first, and the notes keep nothing of a store, memory/ or code/ itself included. - A workspace whose session spent nothing registers again at most MAX_REGISTRATIONS (3) times in all: the service cannot tell Hermit's retry from the session's own request. The workspace's last open lease closing ends its session, also one the workspace registered since without a lease of its own, and a lease is let go even when its reply fails. The method page and the service no longer say a workspace registers once. - Nits: the Stop hook counts the relaunch before it asks for RAX's refund note, which is told once; a Gemini call RAX counted or still holds a reservation for counts as spent (its usage's calls, as RAX's supervisor tells an old state's spend); a frontend that ends between the check and the signal no longer stops a restarted service; the method page says the working directory names the session's row. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/methods/rax.md | 53 ++++--- examples/libero/rax/service.py | 79 ++++++---- hermit/agent/evolver/methods/rax/actor.py | 40 ++--- hermit/agent/evolver/methods/rax/library.py | 58 ++++++-- hermit/agent/evolver/methods/rax/stop_hook.py | 22 ++- tests/methods/rax/test_rax.py | 140 ++++++++++++++++-- 6 files changed, 295 insertions(+), 97 deletions(-) diff --git a/docs/methods/rax.md b/docs/methods/rax.md index 5061f638..3473e650 100644 --- a/docs/methods/rax.md +++ b/docs/methods/rax.md @@ -99,10 +99,11 @@ refusal, and RAX's `merge` against that repository). The prompt is RAX's `START_ the session at the service and writes what the session merged into its library (a git bundle of the repository's main past its first commit, made in a fresh repository from copied objects; none when those objects hold the value of a key the session was given, which Hermit's redaction cannot scrub out of git's compressed objects) and the session's notes -and code into the log; a repository of the session's (its library repository, its clone) whose objects hold such a value -loses its `.git`, since the run's directory is kept. The judge, on the host, runs RAX's formal batch of the submitted -bundle (the supervisor's `run_submission`, `formal.py`) on the row's formal layouts: the share of successful episodes, -LIBERO's own binary check, errors counted as failures. +and code into the log, without any git store's files; every git store in the run's directory and the log (the session's +library repository and clone, and any the agent made) whose objects hold such a value loses its objects, since the run's +directory is kept. The judge, on the host, runs RAX's formal batch of the submitted bundle (the supervisor's +`run_submission`, `formal.py`) on the row's formal layouts: the share of successful episodes, LIBERO's own binary check, +errors counted as failures. ## The step @@ -171,26 +172,30 @@ URL, default `RAX_SERVICE_URL`) and `bin` (the CLI). The session's settings are ## Boundaries -The session never sees its formal layouts, their scores or another session's: the judge plays them on the host, and -the Evolver reads only what each session merged (no scores, no evaluation frames). The test split's swap states are -neither played nor scored by any training or validation session; `TASK.md` says, as RAX's does for every LIBERO-PRO -session, that formal layouts may swap objects. The library is the only thing a session leaves the next, and every -skill in it passed RAX's merge in the Evolver (over each skill a session changed) and the template's check (over every -skill); the session's merge tool runs the same checks, but the session can also write its repository directly, so -only these two hold. RAX's evidence is the agent's own record: -the checks hold its format, not that the runs happened. - -The service trusts a session only with its workspace and task: it registers the one workspace the framework makes for a -rollout, once (again only for a call run again whose session spent nothing; the configs run each call once), so a -session cannot start a second session or a fresh budget. The sessions' run trees are the service's: the task sandbox -shows them read-only and cannot list them, so a session reads its own and writes none. A session `prepare` registered -but could not set up is ended at once; one whose `collect` cannot reach the service is ended by the judge; and one whose -worker ends without `collect` (the CLI failed before its session, the call was stopped) is ended by the service when the -worker's lease closes: a connection `prepare` opens and the worker holds, which goes with everything in the task -sandbox. Gemini's calls (RAX's frontend on the host, OpenRouter) are outside Hermit's model layer and its usage -accounting; their cost is in each session's facts and score (`gemini_usd`). The session's Claude Code calls go through -Hermit's Claude Code agent (Model: the Claude login's model; Base Agent: Claude Code; Acting Agent: the CLI agent with -RAX's task functions), with its login plan, timeout and usage. The Evolver calls no model. +The session never sees its formal layouts, their scores or another session's: the judge plays them on the host, and the +Evolver reads only what each session merged (no scores, no evaluation frames). The test split's swap states are neither +played nor scored by any training or validation session; `TASK.md` says, as RAX's does for every LIBERO-PRO session, +that formal layouts may swap objects. The session's working directory, which Claude Code puts in the model's context, +names its task's row and so its split (`.../test-libero_spatial_0-<hex>/work`), as for every method run by Hermit's CLI +agents; the rows' layouts and collections are not in the sandbox (`rows.py`, these pages). The library is the only thing +a session leaves the next, and every skill in it passed RAX's merge in the Evolver (over each skill a session changed) +and the template's check (over every skill); the session's merge tool runs the same checks, but the session can also +write its repository directly, so only these two hold. RAX's evidence is the agent's own record: the checks hold its +format, not that the runs happened. + +The service trusts a session only with its workspace and task: it registers only the one workspace the framework makes +for a rollout, and that one again only while its session has spent nothing, three times at most (a call Hermit runs +again; the configs run each call once). It cannot tell such a retry from a request of the session's own, which can only +replace the session with a fresh one of the same row (the same layouts, seeds and budget): no session gains a budget. +The sessions' run trees are the service's: the task sandbox shows them read-only and cannot list them, so a session +reads its own and writes none. A session `prepare` registered but could not set up is ended at once; one whose `collect` +cannot reach the service is ended by the judge; and one whose worker ends without `collect` (the CLI failed before its +session, the call was stopped) is ended by the service when the worker's lease closes: a connection `prepare` opens and +the worker holds, which goes with everything in the task sandbox. Gemini's calls (RAX's frontend on the host, +OpenRouter) are outside Hermit's model layer and its usage accounting; their cost is in each session's facts and score +(`gemini_usd`). The session's Claude Code calls go through Hermit's Claude Code agent (Model: the Claude login's model; +Base Agent: Claude Code; Acting Agent: the CLI agent with RAX's task functions), with its login plan, timeout and usage. +The Evolver calls no model. ## Example diff --git a/examples/libero/rax/service.py b/examples/libero/rax/service.py index 7dbcfe20..51c0642f 100644 --- a/examples/libero/rax/service.py +++ b/examples/libero/rax/service.py @@ -5,7 +5,7 @@ bundle and Gemini tools), its supervisor and the LIBERO simulators run here, as RAX's own launcher runs them (robot-agent-exploration/rax libero-pro/native 1767412, on its host environment's Python). The service trusts nothing a session sends but its workspace and its task's id: the session's settings are the task row's (--tasks, read here) and -the launcher's, and only the one workspace the framework makes for a rollout registers, once: +the launcher's, and only the one workspace the framework makes for a rollout registers: <workspaces>/<role>/<task id>-<hex>/workspaces/<task id>-<hex>/work, where <workspaces>/<role>/<task id>-<hex> is the rollout's directory, made outside the sandbox and named for its task. @@ -20,12 +20,14 @@ outside every sandbox: the task sandbox shows <state>/run-trees read-only, a directory that can be passed through but not listed, so a session reads its own tree (the reply names it) and writes none, as RAX's agent reads and never writes its run tree. A rollout has one session: a workspace - registers again (a retry of the call) only while its session has spent nothing, and then starts - afresh. + registers again (Hermit's retry of the call, or a request of the session's own: the service cannot + tell them apart) only while its session has spent nothing, MAX_REGISTRATIONS times in all, and + then starts afresh on the same row (the same layouts, seeds and budget). POST /lease {workspace, session} by the task's `prepare`, once the session is wired: the connection stays - open while the process that runs the session lives (the task sandbox's worker). When it closes - before /finish ended the session (the CLI failed before its session, the call was stopped, and - `collect` never ran), the session is ended (`abandoned` in the ledger). + open while the process that runs the session lives (the task sandbox's worker). When the + workspace's last open lease closes before /finish ended its session (the CLI failed before its + session, the call was stopped, and `collect` never ran), the session is ended (`abandoned` in the + ledger): the one leased, or one the workspace registered since without a lease of its own. POST /explored {workspace, session} by the session's Stop hook: whether its exploration is closed, by RAX's launcher's own rule on the session's directory (services/agent_formal/checkpoint.py exploration_closed), never by asking the frontend, which a long call can keep busy. @@ -66,6 +68,7 @@ HOME_NAME = "agent-home" # RAX's CLI home of the session, unused here (the CLI is Hermit's) STOP_SECONDS = 120 # RAX's SERVER_STOP_SECONDS +MAX_REGISTRATIONS = 3 # a workspace's registrations in all: Hermit's default attempts of a call (retries: 3) SOCKET = "robot.sock" PUBLISHED_PARTS = ("runs", "episode_reviews") # RAX's PUBLISHED_PARTS TREES = "run-trees" # <state>/run-trees/<random>: the sessions' run trees (environment.read in the configs) @@ -95,12 +98,20 @@ def gemini_usd(state: dict) -> float: return round(int((state.get("gemini_spend") or {}).get("reported") or 0) / NANODOLLARS, 6) +def gemini_called(state: dict) -> bool: + """Whether a session made a Gemini call: one its supervisor counted (its usage's calls, RAX's own test of an old + state's spend), or a cost reported or still reserved (a call in flight, or one whose bill RAX could not read).""" + usage, spend = state.get("usage"), state.get("gemini_spend") or {} + counted = isinstance(usage, dict) and any(isinstance(u, dict) and u.get("calls") for u in usage.values()) + return bool(counted or spend.get("reported") or spend.get("reserved")) + + def spent(root: Path) -> bool: """Whether a RAX session has spent anything: an episode started (or charged in its parallel pool), a bundle registered, a result, a submission, a Gemini call.""" state, pool = _json(Path(root) / "state.json"), _json(Path(root) / "exploration" / "state.json") return bool(state.get("exploration_started") or state.get("bundles") or state.get("results") - or state.get("submission") or pool.get("episodes") or gemini_usd(state)) + or state.get("submission") or pool.get("episodes") or gemini_called(state)) class Ledger: @@ -163,6 +174,7 @@ def __init__(self, args, rows: dict): raise RuntimeError(f"another RAX service uses {args.state}: one launch at a time on a RAX_OUT") from None self.ledger = Ledger(args.state / "ledger.json") self.frontends: dict[str, Frontend] = {} + self.leased: dict[str, int] = {} # each workspace's open leases (`lease`) self.registering = threading.Lock() # one registration at a time self.links = args.socket_links.resolve() self.links.mkdir(parents=True, exist_ok=True, mode=0o700) @@ -180,14 +192,19 @@ def _reap(self) -> None: in all: launch.sh waits that long for the service), and the session ended.""" left = [entry for entry in self.ledger.data.values() if not entry.get("finished")] running = [(int(e["frontend_pid"]), e["root"]) for e in left if _is_frontend(e.get("frontend_pid"), e["root"])] - for pid, _ in running: - os.kill(pid, signal.SIGTERM) + + def signal_all(sig): + for pid, root in running: + try: + if _is_frontend(pid, root): + os.kill(pid, sig) + except (ProcessLookupError, PermissionError): # it ended meanwhile (its pid not ours now) + pass + signal_all(signal.SIGTERM) deadline = time.monotonic() + STOP_SECONDS while any(_is_frontend(pid, root) for pid, root in running) and time.monotonic() < deadline: time.sleep(0.2) - for pid, root in running: - if _is_frontend(pid, root): - os.kill(pid, signal.SIGKILL) + signal_all(signal.SIGKILL) for entry in left: self._end(entry, None, abandoned=True) @@ -345,6 +362,9 @@ def register(self, body: dict) -> dict: raise ValueError(f"the rollout {rollout.name} has a RAX session already") if previous is not None and spent(Path(previous["root"])): raise ValueError("this workspace's RAX session has started; a session is never started again") + if previous is not None and len(previous.get("superseded") or []) + 1 >= MAX_REGISTRATIONS: + raise ValueError(f"this workspace has registered {MAX_REGISTRATIONS} times, as many as Hermit's " + "default attempts of a call: it registers no more") if previous is not None: with self.ledger.lock: old = self.frontends.pop(key, None) @@ -379,16 +399,17 @@ def finish(self, body: dict) -> dict: return {"ok": False, "error": "no session registered for this workspace"} return {"ok": True, **self._end(entry, frontend)} - def lease(self, body: dict) -> tuple[str, str]: - """A session's lease (the task's `prepare`, once the session is wired): its key and its session, or a - refusal. The handler holds the connection until it closes (`lease_ended`).""" + def lease(self, body: dict) -> str: + """A session's lease (the task's `prepare`, once the session is wired): its workspace's key, or a refusal. + The handler holds the connection until it closes (`lease_ended`).""" key = str(Path(str(body.get("workspace", ""))).resolve()) session = str(body.get("session") or "") with self.ledger.lock: entry = self.ledger.data.get(key) - if entry is None or entry.get("finished") or entry.get("session") != session: - raise ValueError("no open session of this workspace by that name") - return key, session + if entry is None or entry.get("finished") or entry.get("session") != session: + raise ValueError("no open session of this workspace by that name") + self.leased[key] = self.leased.get(key, 0) + 1 + return key def explored(self, body: dict) -> dict: """Whether a session's exploration is closed (its Stop hook asks), by RAX's launcher's rule on the session's @@ -410,13 +431,20 @@ def explored(self, body: dict) -> dict: from services.exploration.pool import report_refunds return {"ok": True, "closed": closed, "note": report_refunds(Path(config.root) / "exploration")} - def lease_ended(self, key: str, session: str) -> None: - """A lease's connection closed: the process that ran the session is gone. The session, if `collect` did not - end it and the workspace did not register again since, is ended now (`abandoned`).""" + def lease_ended(self, key: str) -> None: + """A lease's connection closed: the process that held it is gone. When it was the workspace's last open lease, + its session (the one it leased, or one the workspace registered since without a lease of its own: the + session's own request), if `collect` did not end it, is ended now (`abandoned`). A retry of the call takes the + new session's lease before it lets the first one go (`prepare`).""" with self.registering: # never while the workspace registers again with self.ledger.lock: + left = self.leased.get(key, 1) - 1 + if left > 0: + self.leased[key] = left + return + self.leased.pop(key, None) entry = self.ledger.data.get(key) - if entry is None or entry.get("finished") or entry.get("session") != session: + if entry is None or entry.get("finished"): return frontend = self.frontends.pop(key, None) self._end(entry, frontend, abandoned=True) @@ -458,14 +486,15 @@ def do_POST(self): body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") if self.path == "/lease": held = service.lease(body) - self._reply({"ok": True}) - self.wfile.flush() try: + self._reply({"ok": True}) + self.wfile.flush() while self.rfile.read(1): # nothing comes: it ends with its process pass except OSError: pass - service.lease_ended(*held) + finally: + service.lease_ended(held) return route = {"/register": service.register, "/explored": service.explored, "/finish": service.finish}.get(self.path) diff --git a/hermit/agent/evolver/methods/rax/actor.py b/hermit/agent/evolver/methods/rax/actor.py index f98340dc..05144212 100644 --- a/hermit/agent/evolver/methods/rax/actor.py +++ b/hermit/agent/evolver/methods/rax/actor.py @@ -29,8 +29,9 @@ collect ends the session at the service (RAX's frontend stopped, as RAX stops it when the agent ends) and lets its lease go, and returns the session's facts (the judge scores its submitted bundle with RAX's formal batch); writes what the session merged into its library (library.export) and the session's notes and - code into the log, and removes the .git of a session repository whose objects hold a key's value - (library.scrub); what it cannot read is recorded, and the session is judged as any other + code into the log, and removes the objects of every git store in the run's directory and the log + that holds a key's value (library.scrub); what it cannot read is recorded, and the session is judged + as any other RAX's own checkout comes from agent.params.rax_root (its START_PROMPT.md, bridge and agent environment must be declared readable: environment.read). The config gives the Claude Code session RAX's frontend server on the command line @@ -61,7 +62,6 @@ LIBRARY_SERVER = "skill_library" # skill_library_merge's server (RAX's frontend serves it with the robot's) CLAUDE_MCP = ".rax-mcp.json" # the session's servers (claude.args: --mcp-config .rax-mcp.json) HOOK_FILE = "hook.json" # <run>/rax/hook.json: what the Stop hook asks the service with -LIBRARY_CLONE = library.rax.LIBRARY_DIR # skill-library/: the session's clone of its library repository NOTES = ("memory", "code") # the session's notes and controller code, kept in the log DENIED_TOOLS = ("WebFetch", "WebSearch") # RAX's Claude Code launcher's SUBAGENT_TOOLS = ("Agent", "Task") # ...and these when the session's subagent cap is 0 ('Task': the old name) @@ -349,9 +349,9 @@ def answer(last_message: str, task: dict) -> dict: def _keep_notes(work: Path, log: Path) -> dict: """The session's notes and code (memory/, code/) in the log: regular files up to NOTE_FILE_BYTES each and - NOTE_BYTES in all, never through a link, and no git repository's own directory (.git, or any directory with a - HEAD and objects/): the learning material is scrubbed of key values as text, which git's compressed objects - are not.""" + NOTE_BYTES in all, never through a link, and nothing of a git store (a .git, or any directory git takes for one: + library.is_store, memory/ or code/ itself included): the learning material is scrubbed of key values as text, + which git's compressed objects are not.""" kept, total = 0, 0 for name in NOTES: top = work / name @@ -359,8 +359,10 @@ def _keep_notes(work: Path, log: Path) -> dict: continue for directory, dirs, files in os.walk(top, followlinks=False): here = Path(directory) - dirs[:] = sorted(d for d in dirs if not (here / d).is_symlink() and d not in ("__pycache__", ".git") - and not ((here / d / "HEAD").is_file() and (here / d / "objects").is_dir())) + if library.is_store(here): + dirs[:] = [] + continue + dirs[:] = sorted(d for d in dirs if not (here / d).is_symlink() and d not in ("__pycache__", ".git")) for file in sorted(files): path = here / file if path.is_symlink() or not path.is_file(): @@ -411,17 +413,21 @@ def collect(task: dict, work: Path, log: Path, params: dict) -> dict: exported["name"] = record.get("name") (log / library.RECORD).write_text(json.dumps(exported, indent=1) + "\n") facts["library"] = {k: exported.get(k) for k in ("base", "head", "bundle", "error")} - # The run's directory is kept: a repository of the session's whose objects hold a key's value loses its .git (the - # two where `prepare` makes them, as the export reads the first) - removed = {} - for name, repository in (("repository", own(work) / "library" / library.ROBOT), ("clone", work / LIBRARY_CLONE)): - held = library.scrub(repository) - if held: - removed[name] = held - if removed: - facts.setdefault("library", {})["removed_git"] = removed try: facts["notes"] = _keep_notes(work, log) except OSError as exc: facts["notes"] = {"error": f"{type(exc).__name__}: {exc}"[:500]} + # The run's directory is kept: every git store in it (the session's library repository and clone, and any the agent + # made) and in the log whose objects hold a key's value loses them, once the export and the notes have been read + removed, run = {}, work.parent + try: + for top in (run, *(() if log.resolve().is_relative_to(run) else (log.resolve(),))): + for store in library.git_stores(top): + held = library.scrub(store) + if held: + removed[os.path.relpath(store, run)] = held + except OSError as exc: + facts["git_scan_error"] = f"{type(exc).__name__}: {exc}"[:500] + if removed: + facts["removed_git"] = removed return facts diff --git a/hermit/agent/evolver/methods/rax/library.py b/hermit/agent/evolver/methods/rax/library.py index 60c25baf..45be1574 100644 --- a/hermit/agent/evolver/methods/rax/library.py +++ b/hermit/agent/evolver/methods/rax/library.py @@ -10,8 +10,9 @@ evidence checks, the same replies, and later commits of the same session see what it merged; - after it (`collect`): `export` writes what the session merged (a git bundle of the repository's main past its first commit) into the run's log, without running git in a repository the agent could write, and none of it when it holds - the value of a key the session was given (`holds_key`: Hermit's redaction cannot reach a compressed object); a - session repository whose objects hold one loses its .git (`scrub`), since the run's directory is kept; + the value of a key the session was given (`holds_key`: Hermit's redaction cannot reach a compressed object); every + git store in the run's directory and its log whose objects hold one loses them (`git_stores`, `scrub`), since the + run's directory is kept; - the Evolver (`merge.py`, in the evolver sandbox): `build` makes the same repository of the step's adapter, and RAX's `merge` takes in each session's bundle on a branch of its own, checking every changed skill again; a merge whose tree the template's check refuses (`problems`: RAX's checks over every skill, which a merge runs only over the @@ -249,20 +250,55 @@ def holds_key(repository: Path, base: str | None = None, head: str | None = None return None -def scrub(repository: Path) -> str | None: - """A session's git repository (its library repository, its clone), kept with the run's directory: when one of its - objects holds the value of a key the session was given (`holds_key`), or they cannot be read to tell, its .git is - removed, since Hermit's redaction scrubs the files a run keeps, not git's compressed objects. The objects are read +def is_store(path: Path) -> bool: + """Whether a directory is a git store, as git tells one: a HEAD and an objects/ directory (a .git, a bare + repository, a submodule's store in .git/modules), neither it nor its objects/ a link.""" + path = Path(path) + objects = path / "objects" + try: + return (not path.is_symlink() and path.is_dir() and os.path.lexists(path / "HEAD") and objects.is_dir() + and not objects.is_symlink()) + except OSError: # one that cannot be looked at cannot be read either + return False + + +def _real_directory(path: Path) -> bool: + try: + return not path.is_symlink() and path.is_dir() + except OSError: + return False + + +def git_stores(top: Path) -> list[Path]: + """Every git store under `top` (`top` included, and a store inside another), found without following a link; a + directory that cannot be listed is passed over.""" + found = [] + if not _real_directory(Path(top)): + return found + for directory, dirs, _ in os.walk(top, followlinks=False): + here = Path(directory) + if is_store(here): + found.append(here) + dirs[:] = sorted(d for d in dirs if _real_directory(here / d)) + return found + + +def scrub(store: Path) -> str | None: + """A git store kept with a run's directory (the session's library repository's, its clone's, or one the agent + made): when one of its objects holds the value of a key the session was given (`holds_key`), or they cannot be + read to tell, its objects/ is removed, since Hermit's redaction scrubs the files a run keeps as text, and git's + objects are compressed; the rest of the store (its refs and logs: text) stays, and is scrubbed. The objects are read from a copy without links (RAX's _copy_objects), as `export` reads them: no git runs in the agent's repository. Returns what was found (the variable's name, or why the objects could not be read), or None.""" - git_dir = Path(repository) / ".git" - if git_dir.is_symlink() or not git_dir.is_dir(): + from hermit.redact import key_values + store = Path(store) + if not is_store(store) or not key_values(): return None try: with tempfile.TemporaryDirectory(prefix="rax-scan-") as scratch: bare = Path(scratch) / "objects.git" bare.mkdir() - rax._copy_objects(git_dir / "objects", bare / "objects") + rax._copy_objects(store / "objects", bare / "objects") (bare / "refs").mkdir() (bare / "HEAD").write_text("ref: refs/heads/main\n") (bare / "config").write_text("[core]\n\trepositoryformatversion = 0\n\tbare = true\n") @@ -270,7 +306,9 @@ def scrub(repository: Path) -> str | None: except (rax.LibraryError, OSError, subprocess.SubprocessError) as exc: held = f"unreadable ({type(exc).__name__})" if held: - shutil.rmtree(git_dir, ignore_errors=True) + shutil.rmtree(store / "objects", ignore_errors=True) + if os.path.lexists(store / "objects"): + held += "; its objects/ could not be removed" return held diff --git a/hermit/agent/evolver/methods/rax/stop_hook.py b/hermit/agent/evolver/methods/rax/stop_hook.py index a9da65b5..7d2d725f 100644 --- a/hermit/agent/evolver/methods/rax/stop_hook.py +++ b/hermit/agent/evolver/methods/rax/stop_hook.py @@ -32,7 +32,7 @@ HOOK_FILE = "hook.json" -def explored(mine: Path, relaunch: bool, timeout: float = 30.0) -> dict: +def explored(mine: Path, relaunch: bool, timeout: float = 20.0) -> dict: """The RAX service's answer (POST /explored), straight to its loopback port (no proxy): whether the session's exploration is closed, by RAX's rule, and, when the hook would relaunch it, RAX's note for the next prompt.""" asked = json.loads((mine / HOOK_FILE).read_text()) @@ -63,22 +63,30 @@ def main(argv: list[str] | None = None) -> int: count = int(count_file.read_text().strip() or 0) if count_file.is_file() else 0 except (OSError, ValueError): count = MAX_RELAUNCHES # a count that cannot be read: no relaunch is owed - note = "" + if count >= MAX_RELAUNCHES: + return 0 + answered = False try: - reply = explored(mine, relaunch=count < MAX_RELAUNCHES) - if reply["closed"]: + if explored(mine, relaunch=False)["closed"]: return 0 - note = str(reply.get("note") or "") + answered = True except Exception as exc: # no answer: open, as RAX counts a state it cannot read print(f"rax stop hook: {type(exc).__name__}: {exc}", file=sys.stderr) - if count >= MAX_RELAUNCHES: - return 0 try: count_file.write_text(f"{count + 1}\n") except OSError as exc: # a relaunch it cannot count could be owed again and again print(f"rax stop hook: the relaunch count cannot be kept ({type(exc).__name__}: {exc}): the turn ends", file=sys.stderr) return 0 + note = "" + if answered: # RAX's note is told once: asked for once the relaunch is counted + try: + reply = explored(mine, relaunch=True) + if reply["closed"]: + return 0 + note = str(reply.get("note") or "") + except Exception as exc: # the relaunch goes on without it + print(f"rax stop hook: {type(exc).__name__}: {exc}", file=sys.stderr) print(json.dumps({"decision": "block", "reason": f"{CONTINUE_PROMPT}\n\n{note}" if note else CONTINUE_PROMPT})) return 0 diff --git a/tests/methods/rax/test_rax.py b/tests/methods/rax/test_rax.py index 6c90e2b8..f7cac658 100644 --- a/tests/methods/rax/test_rax.py +++ b/tests/methods/rax/test_rax.py @@ -21,6 +21,7 @@ import py_compile import shlex import shutil +import signal import socket import stat import subprocess @@ -466,6 +467,16 @@ def hook(where=work): (mine / "relaunches").mkdir() # a count it cannot keep: no relaunch it cannot bound assert hook() is None (mine / "relaunches").rmdir() + # RAX's note is told once: asked for only once the relaunch is counted, so a count it cannot keep loses none + (mine / H.HOOK_FILE).write_text(json.dumps(asked)) + (service.made[0] / "state.json").write_text("{}") # open again + service.refunds["notes"].append(note) + (mine / "relaunches").mkdir() + asked_before = len(service.refunds["asked"]) + assert hook() is None and len(service.refunds["asked"]) == asked_before and service.refunds["notes"] == [note] + (mine / "relaunches").rmdir() + assert hook() == {"decision": "block", "reason": f"{H.CONTINUE_PROMPT}\n\n{note}"} + assert service.refunds["notes"] == [] and (mine / "relaunches").read_text().strip() == "1" lost = subprocess.run(installed[:3], input="{}", capture_output=True, text=True, cwd=work, timeout=20) assert lost.returncode == 0 and not lost.stdout.strip() and "<run>/rax" in lost.stderr # no directory given finally: @@ -909,10 +920,11 @@ def broken(*_): assert "record cannot be read" in facts["library"]["error"] and facts["notes"]["files"] == 1 -def test_collect_removes_the_git_of_a_session_repository_that_holds_a_key(tmp_path, monkeypatch): - """The run's directory is kept, and Hermit's redaction scrubs its files, not git's compressed objects: a key's value - the session committed (here into its clone, then deleted) costs the clone its .git, wherever the record points; a - repository that holds no key keeps its own.""" +def test_collect_removes_the_objects_of_every_git_store_of_the_run_that_holds_a_key(tmp_path, monkeypatch): + """The run's directory is kept, and Hermit's redaction scrubs its files as text, not git's compressed objects: a + key's value committed into any git store of the run (the session's clone, here then deleted; a repository of the + agent's own; memory/ made a bare repository; one in the log) costs that store its objects, wherever the record + points, and nothing of a store is in the notes; a store that holds no key keeps its own, and no link is followed.""" secret = "sk-test-" + "7" * 24 monkeypatch.setenv("RAX_TEST_API_KEY", secret) adapter = seed(tmp_path) @@ -923,18 +935,39 @@ def test_collect_removes_the_git_of_a_session_repository_that_holds_a_key(tmp_pa commit(clone, "a key") (clone / "notes.txt").unlink() commit(clone, "the key removed") + + def own_repository(path: Path, text: str) -> Path: + path.mkdir(parents=True) + (path / "env.txt").write_text(text) + L.git("init", "-q", cwd=path) + L.git("add", "-A", cwd=path) + L.git("commit", "-q", "-m", "a dump of the environment", cwd=path, env=L.BASE_IDENTITY) + return path + project = own_repository(work / "code" / "proj", f"RAX_TEST_API_KEY={secret}\n") # RAX's prompts ask for none + source = own_repository(tmp_path / "source", secret) + L.git("clone", "-q", "--bare", str(source), str(work / "memory"), cwd=tmp_path) # memory/ itself a store + log = work.parent / "log" + log.mkdir() + L.git("clone", "-q", "--bare", str(source), str(log / "planted.git"), cwd=tmp_path) + (work / "code" / "linked").symlink_to(source / ".git", target_is_directory=True) + assert L.git_stores(work) == [project / ".git", work / "memory", work / rax.LIBRARY_DIR / ".git"] with socket.socket() as s: s.bind(("127.0.0.1", 0)) monkeypatch.setenv("RAX_SERVICE_URL", f"http://127.0.0.1:{s.getsockname()[1]}") for name in ("NO_PROXY", "no_proxy"): monkeypatch.setenv(name, "127.0.0.1,localhost") - log = tmp_path / "log" - log.mkdir() facts = A.collect({"id": TASK}, work, log, {}) - assert facts["library"]["removed_git"] == {"clone": "RAX_TEST_API_KEY"} and secret not in json.dumps(facts) - assert not (clone / ".git").exists() and (clone / "INDEX.md").is_file() # the files stay (Hermit scrubs them) - assert (repository / ".git").is_dir() # it holds no key - assert L.scrub(repository) is None and (repository / ".git").is_dir() + assert facts["removed_git"] == {f"work/{rax.LIBRARY_DIR}/.git": "RAX_TEST_API_KEY", + "work/code/proj/.git": "RAX_TEST_API_KEY", "work/memory": "RAX_TEST_API_KEY", + "log/planted.git": "RAX_TEST_API_KEY"} + assert secret not in json.dumps(facts) + for store in (clone / ".git", project / ".git", work / "memory", log / "planted.git"): + assert not (store / "objects").exists() and (store / "HEAD").is_file() # its refs stay: text, scrubbed + assert (clone / "INDEX.md").is_file() and (project / "env.txt").is_file() # the files stay (Hermit scrubs them) + assert (repository / ".git" / "objects").is_dir() and (source / ".git" / "objects").is_dir() # no key; a link + copied = sorted(p.relative_to(log / "session").as_posix() for p in (log / "session").rglob("*") if p.is_file()) + assert copied == ["code/proj/env.txt"] and facts["notes"]["files"] == 1 # nothing of a store in the notes + assert L.scrub(repository / ".git") is None and (repository / ".git" / "objects").is_dir() # ---------- the Evolver ---------- @@ -1216,6 +1249,22 @@ def test_the_service_registers_only_a_rollouts_own_workspace_and_one_session_a_r assert service.frontends_started[1].stops == 1 +def test_a_workspace_registers_at_most_max_registrations_times(tmp_path, service): + """A workspace whose session spent nothing registers again (Hermit's retry of the call, or the session's own + request: the service cannot tell them apart), each time stopping its last frontend, MAX_REGISTRATIONS times in + all: never a session that spent anything, and never an endless round of fresh sessions.""" + service.state = {} + work = _registration(tmp_path, f"{TASK}-0e0e0e0e", f"{TASK}-1f1f1f1f") + sessions = [service.register({"workspace": str(work), "task": TASK})["session"] + for _ in range(service.module.MAX_REGISTRATIONS)] + assert sessions == ["session-0", "session-1", "session-2"] and service.module.MAX_REGISTRATIONS == 3 + with pytest.raises(ValueError, match="registers no more"): + service.register({"workspace": str(work), "task": TASK}) + assert [f.stops for f in service.frontends_started] == [1, 1, 0] and len(service.configured) == 3 + entry = json.loads((tmp_path / "state" / "ledger.json").read_text())[str(work)] + assert entry["session"] == "session-2" and entry["superseded"] == [str(m) for m in service.made[:2]] + + def test_the_run_trees_cannot_be_listed_while_the_service_runs_and_can_once_it_stops(service): """While the service runs, its run trees' directory can be passed through, not listed (no session learns another's tree); once it stops, it can be listed again, so a run's directory can be removed.""" @@ -1263,10 +1312,57 @@ def test_a_service_started_again_ends_what_the_last_one_left_open_and_two_never_ other.wait() +def test_a_service_started_again_stops_the_frontends_left_all_at_once(tmp_path, service, monkeypatch): + """The frontends a killed service left: SIGTERM to all of them, SIGKILL to those still running once STOP_SECONDS + have passed in all (not each), and one that ends between the check and the signal is passed over.""" + monkeypatch.setattr(service.module, "STOP_SECONDS", 2) + stubborn = ("import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); print(flush=True); " + "time.sleep(120)") + processes, ledger = {}, {} + for name, code in (("stubborn-1", stubborn), ("stubborn-2", stubborn), ("gone", stubborn)): + root = tmp_path / name + root.mkdir() + (root / "configuration.json").write_text(json.dumps({"exploration_seeds": [1]})) + processes[name] = subprocess.Popen([sys.executable, "-c", code, "services.controller.frontend", "--config", + str(root / "configuration.json")], stdout=subprocess.PIPE) + processes[name].stdout.readline() # SIGTERM is ignored from here on + ledger[f"/w/{name}"] = {"task": TASK, "root": str(root), "session": name, "finished": None, + "frontend_pid": processes[name].pid} + real_kill = os.kill + + def kill(pid, sig): # it ends between the check and the signal + if pid == processes["gone"].pid and sig == signal.SIGTERM: + real_kill(pid, signal.SIGKILL) + processes["gone"].wait() + raise ProcessLookupError(pid) + real_kill(pid, sig) + try: + state = tmp_path / "state2" + state.mkdir() + (state / "ledger.json").write_text(json.dumps(ledger)) + monkeypatch.setattr(service.module.os, "kill", kill) + started = time.monotonic() + again = service.module.Service(SimpleNamespace(**{**vars(service.args), "state": state}), service.rows) + took = time.monotonic() - started + monkeypatch.setattr(service.module.os, "kill", real_kill) + assert [processes[n].wait(10) for n in ("stubborn-1", "stubborn-2", "gone")] == [-9, -9, -9] + assert 2 <= took < 3.8, took # one STOP_SECONDS for both, not one each + data = json.loads((state / "ledger.json").read_text()) + assert all(data[k]["abandoned"] and data[k]["finished"] for k in ledger) + again.stop() + again.held.close() + finally: + for process in processes.values(): + process.kill() + process.wait() + process.stdout.close() + + def test_a_session_whose_process_ends_without_collect_is_ended_when_its_lease_closes(tmp_path, service): - """The lease `prepare` takes: refused for a name that is not the open session's; a connection that closes while - its session is open (the worker gone, `collect` never run) ends the session as abandoned; one that closes after - its workspace registered again (the call's retry) or after /finish ends nothing.""" + """The lease `prepare` takes: refused for a name that is not the open session's; the workspace's last open lease + closing while its session is open (the worker gone, `collect` never run) ends the session as abandoned, also one + the workspace registered since without a lease (the session's own request); a lease that closes while another is + open (the call's retry took its own first), or after /finish, ends nothing.""" service.state = {} # nothing spent: the call's retry may register again def entry(work): @@ -1294,6 +1390,18 @@ def entry(work): assert service.frontends_started[2].stops == 1 with pytest.raises(RuntimeError, match="no open session"): A._lease(service.url, str(other), reply["session"]) # a finished session takes none + third = _registration(tmp_path, f"{TASK}-2a3b4c5d", f"{TASK}-6e7f8a9b") + started = A._post(service.url + "/register", {"workspace": str(third), "task": TASK}) + worker = A._lease(service.url, str(third), started["session"]) + taken = A._lease(service.url, str(third), started["session"]) # one the session takes itself + own = A._post(service.url + "/register", {"workspace": str(third), "task": TASK}) # the session's own request + taken.close() + time.sleep(0.5) + assert not entry(third)["finished"] # the worker's lease is open + worker.close() + _until(lambda: entry(third)["finished"]) + assert entry(third)["abandoned"] and entry(third)["session"] == own["session"] + assert [f.stops for f in service.frontends_started[3:]] == [1, 1] and service.leased == {} def test_the_services_routes_refuse_with_their_reason_and_its_health_names_its_launch(service): @@ -1319,9 +1427,13 @@ def test_a_session_has_spent_something_once_any_of_raxs_records_says_so(tmp_path (root / "state.json").write_text(json.dumps({"exploration_started": 0, "bundles": {}, "results": []})) assert S_.spent(root) is False for state in ({"exploration_started": 1}, {"bundles": {"b": {}}}, {"results": [{}]}, {"submission": {"b": 1}}, - {"gemini_spend": {"reported": 1000}}): + {"gemini_spend": {"reported": 1000}}, {"gemini_spend": {"reported": 0, "reserved": 25_000_000}}, + {"usage": {"development": {"calls": 1, "tokens": 0}}}): # a call in flight, or its bill unread (root / "state.json").write_text(json.dumps(state)) assert S_.spent(root) is True, state + (root / "state.json").write_text(json.dumps({"gemini_spend": {"reported": 0, "reserved": 0, "blocked": False}, + "usage": {p: {"calls": 0} for p in ("development", "formal")}})) + assert S_.spent(root) is False # RAX's fresh state: no call (root / "state.json").write_text("{}") (root / "exploration" / "state.json").write_text(json.dumps({"episodes": {"0": {"layout": 100}}})) assert S_.spent(root) is True