diff --git a/CHANGELOG.md b/CHANGELOG.md index ccb0c7fc..b4a3b370 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -120,7 +120,9 @@ has the checklist. - **`run --import RUN_ID`**: a new run from your checkout that reads another run's notes, history and code. - **`run --check`** makes every check a run makes before it writes anything, - then exits. + says what `run` would say at its start (other runs' unlanded commits, the + imported run's, an uncommitted config), and names the command it checked, + flags included. - **`run --why`** and **`archive --why`**: one line kept with the run. - **A summary at the end of each segment**: `runs//report.md` and `report.html`, a one-file copy of the run page (`--no-report` skips the @@ -157,9 +159,9 @@ has the checklist. ### Changed - **A failed or timed-out agent call is a rejected iteration**, and the loop - goes on; three in a row stop the run. An infrastructure failure (a rejected - key or credentials, HTTP 401/403; for Claude Code and OpenCode also HTTP 429 - or 5xx) stops it after the one call, with an error (exit 1) that says to fix + goes on; three in a row stop the run (also a rate limit or an outage, HTTP + 429 or 5xx). An infrastructure failure (a rejected key or credentials, HTTP + 401/403) stops it after the one call, with an error (exit 1) that says to fix it and `autohelix resume`. - **Notes are saved as a version per iteration**: a note the agent deletes stays deleted. @@ -172,6 +174,83 @@ has the checklist. ### Fixed +- A gate, observe or stop command that leaves a background process holding + its output (`./server & curl ...`) ends when its shell exits, with the + shell's exit code; it waited for its whole timeout and was reported as timed + out. +- A JSON line from the agent that isn't an object (a wrapper script's `0` on + stderr) is shown as output; for Claude Code and OpenCode it ended the run + with a Python error. Any error while an agent runs now kills its process + group: the agent kept running, past its timeout. +- A failed command's output in the record and the prompt is its last 15 + lines, each cut at 500 characters: one long line (a JSON dump) made the + prompt too large to start the agent, and every resume failed the same way. +- Files the agent writes outside the scope (a dataset, a checkpoint) are no + longer hashed into your repository's objects at each freeze, and the record + and the next prompt list at most 20 discarded paths, frozen ones first + (`discarded_more` counts the rest). An unreadable file outside the scope is + now discarded instead of rejecting the iteration. +- A setup that can't work stops the run at the baseline, before any agent call + is paid for, with a setup error naming the gate and its last stderr line: a + gate command that exits 126 or 127 (not executable, not found; unless its + first word is a file the agent may write and git doesn't ignore), and an `ask:` gate that exits 2 + (no answer). Each iteration used to be paid for and rejected the same way. +- Every `resume` checks that the agents' executables can be found, as the + first `run` does; a missing one cost an iteration. +- A custom prompt template that names a variable the prompt doesn't have, or + the old `.autohelix/` copy paths, or fails to render against a sample + history, is a config error, so `run --check` finds it. A misspelt variable + rendered empty (the agent got no goal), and a render error failed iteration + 1 after the baseline, in a run that couldn't take the fix. A run whose + stored template has one of these problems no longer resumes: continue from + it with `autohelix run --import ` after fixing the template. +- A damaged line in an old run's `history.jsonl` no longer stops new runs of + its config; that run's own commands name the line and what works (fix or + remove it, or `autohelix archive`), where `report` and `resume --until` + ended in a traceback. A blank line resumes, as it views. +- `delete` without `--force` refuses a run whose tip is on no branch, tag or + remote-tracking branch: a run that read landed after its target was reset + was deleted with the only ref to its commits. `land` says when it did + nothing (already there, nothing accepted, landed before) instead of + "Landed". +- Bare `land` and `report` take the most recently active run that isn't + running: they took the running run, which refuses them. +- The refusal of a changed config gives the landing first, then the `run + --import` command, a line each: a new run started first lacked the code. +- A config name given where a run id goes (`land perf`) names the config's + latest run; an unknown id lists the latest real ids instead of "e.g. k3f9". +- After a failed first baseline, the end block, `view --terminal` and the + entry screen suggest `autohelix run ` (and `autohelix delete `), + as the error does, not `resume`, which refuses the fixed setup. `view + --json` runs have `baseline`. +- An interrupted baseline is recorded as "baseline interrupted", not + "baseline failed: " with nothing after it. +- One set of numbers for a run on every screen: `run`'s baseline row has its + judges' cost, as `view` shows it; the run page's time counts the baseline, as + the run list's does (`view --json` gives the baseline's `seconds`); `view`'s + Budget names the run totals it shows (`to iteration 8 · $5.04 run total`) + and the time used of `--time` as the web pages do (`12m 05s of 1h (this + segment)`; the web pages write `12m5s`); an incomplete cost is `$0.07+` everywhere (was `$0.07 + (incomplete)` on `run` and the run page); a resumed segment's `landed` says + `(this segment)`. +- The run page words the phase as the console does (`gates`, `observe · + bench`), not "Running gates…" or "accept…". +- A stopped run's `view --terminal` waits for `autohelix resume `, not + "the next run" (a new run never shows there). +- The run page and report.html no longer show a stored config or template + that is a symlink (read as the rest of run state is). +- `resume`'s refusal of a changed config names the field and the entry + (`agent.timeout`, `gates entry 2`, `observe bench (added)`), not only + `agent` or `observe`; for files added to the experiment folder it says to + remove them, not to restore them. +- The config template's `model: opus` is commented out: a user who changed + only `cli:` kept a Claude model name for Codex or OpenCode. +- `run --help` forks from a run's code on a branch (`git switch -c + autohelix/`), not a detached checkout, which can't land. +- A timed-out agent call's error reads `timed out after 30m`, as a timed-out + command's does (was `timed out after 30 minutes`). +- A second `autohelix view` on a port in use names the page to open in the + one already serving, or `--port 0`, instead of "Address already in use". - When no cost is known for a run and all its calls give the same reason, the end says it (`cost unavailable: set agent.model` for Codex, whose output names no model). @@ -208,6 +287,12 @@ has the checklist. - A nested git repository in the project is refused with "nested git repository at X: remove its .git or clone outside the project". - Rich markup in a goal (`[/bold]`) no longer crashes `--verbose`. +- The examples run as written: Docker's steps name the AutoHelix checkout and + `run.sh` refuses a missing `--env` script; autoresearch's polite stop names + the run; AlgoTune's collector reads `base_commit`; kernelbench and + autoresearch commit without a git identity and autoresearch's setup reruns; + kernelbench's model is `opus` (its published Bedrock id is a comment), and + autoresearch's Bedrock id says the example runs on Bedrock. ### Upgrading from 0.1.1 @@ -274,9 +359,8 @@ Each old key is an error naming its replacement; there are no aliases. #### Prompt template variables -For a custom `prompt_template:`. `worktree` is a config error naming its new -name; the others are no longer variables: they render -empty, and the run warns at start naming them. +For a custom `prompt_template:`. Each old name is a config error: `worktree` +names its new name, the others are listed as variables the prompt doesn't have. | 0.1.1 | Now | |---|---| diff --git a/CLAUDE.md b/CLAUDE.md index 685648f2..0a0a7922 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -79,6 +79,13 @@ pytest -m slow # run slow tests (requires real agent) bash scripts/run_dev_test.sh # manual test with real agent (sorting, 1 iteration) ``` +Before a release, check each real backend by hand: the suite tests their flags and stream formats only against synthetic lines. For each installed CLI (`claude-code`, `codex`, `opencode`): + +1. `P=$(mktemp -d)/sorting; python examples/setup_example.py sorting --dir "$P"; cd "$P"`. +2. In `autohelix/sorting/config.yaml`, set `agent: {cli: }`, add a gate `- ask: Does sort_list still sort?` and an observe entry `- name: review` / `review: Review the diff. What is the most important next fix?`; `git commit -qam cli`. +3. `autohelix run -n 1`: the baseline and iteration 1 finish, the gate's `ask.log` and the observe entry's `review.log` are under `.autohelix/runs//iterations/001/`, the cost is priced (Codex: with `agent.model` set), and `autohelix view --once `'s Agent line names the model the CLI reported (Codex and OpenCode report none). +4. A judge can't write: `autohelix ask --cli -- "Create a file named judge.txt here, then answer yes."` leaves no `judge.txt`: the CLI's read-only flags refuse the write, or the write guard fails the call (exit 2). + ## Docs User-facing docs are plain markdown in `docs/` (see `docs/README.md` for the index). @@ -89,25 +96,25 @@ User-facing docs are plain markdown in `docs/` (see `docs/README.md` for the ind ## Architecture Notes -- Entry points: bare `autohelix` (`cli._entry`, only when stdin and stdout are TTYs, `cli._interactive`; else the help and "Run `autohelix` in a terminal to start." on stderr, exit 2) shows the project (`cli.entry_project`: `runs.find_project`'s folder when it has runs, else the nearest folder up from here with a config, else the git top level; outside a checkout it says so, `_git_problem`, and offers nothing, exit 1): a header (`run_table.entry_header`, drawn before the runs are read), the runs table (`run_table.entry_lines`, `table_lines`, one line per run), one suggested command per run (`run_table.suggestion`), the archived count and the `--help` footer, then one question (`cli.entry_options`: with non-archived runs, Ask about these runs / Set up a new experiment; configs without runs: check and finish them; nothing: `entry_question`, Enter/q; `menu.choose`/`menu.confirm`, which drop keys typed before them; q or Esc raises `menu.Quit`, exit 0; Ctrl-C exits 130). Every option execs the same agent session (`_agent_argv`, Claude Code/Codex/OpenCode, never `mock`; "Which agent?" with several) with the bundled skill and `cli.first_prompt` (`autohelix/README.md`, the coordinator's notes, when present; runs, configs, the pick, AutoHelix's CLI, Python and docs: `cli.docs_dir`, the package's `autohelix/docs` that pyproject force-includes from docs/, else the checkout's). There is no setup command. `autohelix run [NAME]` finds the config (`config.find_config`: an experiment folder's `autohelix/NAME/config.yaml`, `config.experiment_config`; without NAME the only one, several are named; `config.project_configs`; a folder without `config.yaml`, a dot-folder or a `.yaml` file directly in `autohelix/` isn't a config), creates `.autohelix/` on first use and starts the harness loop. +- Entry points: bare `autohelix` (`cli._entry`, only when stdin and stdout are TTYs, `cli._interactive`; else the help and "Run `autohelix` in a terminal to start." on stderr, exit 2) shows the project (`cli.entry_project`: `runs.find_project`'s folder when it has runs, else the nearest folder up from here with a config, else the git top level; outside a checkout it says so, `_git_problem`, and offers nothing, exit 1): a header (`run_table.entry_header`, drawn before the runs are read), the runs table (`run_table.entry_lines`, `table_lines`, one line per run), one suggested command per run (`run_table.suggestion`), the archived count and the `--help` footer, then one question: with one agent CLI found (`_found_agents`), `cli.entry_question` ("Start Claude Code with AutoHelix?", Enter/q, `menu.confirm`); with several, a menu of them (`cli.ENTRY_TITLE`, `menu.choose`); both drop keys typed before them; q or Esc raises `menu.Quit`, exit 0; Ctrl-C exits 130. It execs one agent session (`_agent_argv`, Claude Code/Codex/OpenCode, never `mock`) with the bundled skill and `cli.first_prompt` (`autohelix/README.md`, the coordinator's notes, when present; runs, configs, the pick, AutoHelix's CLI, Python and docs: `cli.docs_dir`, the package's `autohelix/docs` that pyproject force-includes from docs/, else the checkout's). There is no setup command. `autohelix run [NAME]` finds the config (`config.find_config`: an experiment folder's `autohelix/NAME/config.yaml`, `config.experiment_config`; without NAME the only one, several are named; `config.project_configs`; a folder without `config.yaml`, a dot-folder or a `.yaml` file directly in `autohelix/` isn't a config), creates `.autohelix/` on first use and starts the harness loop. - Iteration isolation: `iteration.py` runs every phase in its own fresh `workspace.Copy` (agent, checks, each review, stop; baseline and report too): a private folder holding one tree, with its own `.git` borrowing the user's objects via alternates. The harness reads copies only from outside through `Repo` and a harness index kept in a private per-process folder; it never runs git inside a copy after a call used it. The agent copy is frozen to a tree T (pinned at `refs/autohelix-tmp/`); checks run on a fresh copy of T with HEAD at A and T's files verified after every command (checks, stop and report copies are `watched`: fingerprinted for `Copy.changed()`; agent and judge copies aren't); accept commits exactly T on A (`commit-tree`, no hooks), CAS-updates `refs/autohelix/`, and records history in a deferred-SIGINT section. A no-op is accepted without a commit. A rejected attempt's T (also after a failed or timed-out agent call) is kept as `refs/autohelix-rejected//` (`keep_rejected`; removed by `delete`), and the next agent copy gets the latest rejection's `base..T` (`workspace.diff_args`, independent of the user's git config) as `rejected.patch` (over 2 MiB: none, the prompt's `rejected_diff` names the `git diff`). An attempt whose T equals its base keeps no ref. Run segments land separately on the target branch. -- Evaluation (`harness._evaluate`; user docs in `docs/config.md`): gate commands in list order (first failure rejects; `ask:` entries render to `autohelix ask [flags] -- Q`), then `observe:` entries top to bottom (`review:` entries render to `autohelix review [flags] -- P`); after each entry, the metric gates on its metrics, compared with the last accepted commit-creating record (`checks.metric_reference`). A failed observe entry is recorded and contributes no metrics; a missing gated metric fails. The baseline runs everything and rejects nothing; a missing command metric is a setup error. Metrics come only from `##autohelix[name=value]` lines on stdout, by name (`checks.parse_structured_metrics`). Unknown top-level keys and old config keys are errors (`config.RENAMED_TOP_LEVEL_KEYS`, `agents.RENAMED_AGENT_KEYS`, `agents.RENAMED_CLIS`, `config.RENAMED_ENTRY_AGENT_KEYS`); agent values are type-checked (`agents.agent_string`, `agents.cli_value`); `agent:` is `cli` (claude-code, codex, opencode; hidden `mock`, whose test knobs are `agent.mock:`), `model`, `effort` (both passed through), `timeout`, `extra_args`, `auto_memory`; a `prompt_template:` that doesn't parse is a config error (`prompt_template.template_problem`), one that fails to render raises naming it. `run --check` is `Harness(check_only=True)`: every refusal before the first write, then nothing. Preflight (`checks.preflight_check`) finds every agent the config runs (`Config.agent_commands`: the main agent, each `ask:`/`review:` judge, resolved like `judge.judge_config`) with `agents.command_path` (`$AUTOHELIX_CLAUDE_CODE_CMD` / `_CODEX_CMD` / `_OPENCODE_CMD`, else `claude`/`codex`/`opencode` on PATH; never the config), the backends' own resolver, and warns about a gate/observe/stop command naming an `autohelix/` path that exists in the working tree but not in HEAD (`checks.uncommitted_command_paths`, textual, `./autohelix/` too, so a run ref `autohelix/` stays quiet; `ask:`/`review:` entries skipped: a judge reads `experiment/`; advice `$AUTOHELIX_EXPERIMENT/...`, `$AUTOHELIX_EXPERIMENT` for the folder itself); bare `autohelix` starts `agents.executable`. A set `AUTOHELIX_CLAUDE_CMD` is a `ConfigError` from the one check in `agents.executable` (`variable_problem`'s message), wherever an executable is resolved: a backend resolves its own when created (`create_agent`; so `Harness.__init__`, the report, a judge call), preflight, the entry screen; each command reports it as a config error (`cli._start`, `report`, `ask`/`review` exit 2, the entry screen's warning). `ask`/`review` take `--cli`/`--model`/`--effort` (`cli._judge_options`; `--agent`/`--command` are hidden errors). +- Evaluation (`harness._evaluate`; user docs in `docs/config.md`): gate commands in list order (first failure rejects; `ask:` entries render to `autohelix ask [flags] -- Q`), then `observe:` entries top to bottom (`review:` entries render to `autohelix review [flags] -- P`); after each entry, the metric gates on its metrics, compared with the last accepted commit-creating record (`checks.metric_reference`). A failed observe entry is recorded and contributes no metrics; a missing gated metric fails. The baseline runs everything and rejects nothing; a missing command metric is a setup error, and so is a gate that can't work (`Harness._unworkable_gate`: a command gate exiting 126/127 unless its first word is a path the agent may write and git doesn't ignore, `_agent_may_write`; an `ask:` gate exiting 2), naming the gate and its last stderr line. Metrics come only from `##autohelix[name=value]` lines on stdout, by name (`checks.parse_structured_metrics`). Unknown top-level keys and old config keys are errors (`config.RENAMED_TOP_LEVEL_KEYS`, `agents.RENAMED_AGENT_KEYS`, `agents.RENAMED_CLIS`, `config.RENAMED_ENTRY_AGENT_KEYS`); agent values are type-checked (`agents.agent_string`, `agents.cli_value`); `agent:` is `cli` (claude-code, codex, opencode; hidden `mock`, whose test knobs are `agent.mock:`), `model`, `effort` (both passed through), `timeout`, `extra_args`, `auto_memory`; a `prompt_template:` is a config error (`prompt_template.template_problem`) when it doesn't parse, names a variable not in `VARIABLES` or the old `.autohelix/` copy paths (`uses_old_layout`), or fails to render against `SAMPLE_RECORDS` after each of their iterations (`_sample_variables`, a temporary folder; docs/phases.md's prompt is rendered from the same sample); one that fails to render in a run still raises naming it. `run --check` is `Harness(check_only=True)`: every refusal before the first write, then `run`'s start notices (`Harness._check_notices`: `runs.new_run_notices` and, landing automatically, `_uncommitted_config` over the files `snapshot_files` would store), then nothing; its OK line names the command with `--import`/`--group`/`--land`. A damaged history line raises `runs.damaged_history` (run, line, what works) from `History.load` and `repair_history` alike (which skip blank lines); readers across runs (`_resumable`, `new_run_notices`) take it as no baseline (`has_baseline(paths, damaged=False)`). Preflight (`checks.preflight_check`, before the baseline; at a later segment's start only its agent part, `checks.agent_issues`) finds every agent the config runs (`Config.agent_commands`: the main agent, each `ask:`/`review:` judge, resolved like `judge.judge_config`) with `agents.command_path` (`$AUTOHELIX_CLAUDE_CODE_CMD` / `_CODEX_CMD` / `_OPENCODE_CMD`, else `claude`/`codex`/`opencode` on PATH; never the config), the backends' own resolver, and warns about a gate/observe/stop command naming an `autohelix/` path that exists in the working tree but not in HEAD (`checks.uncommitted_command_paths`, textual, `./autohelix/` too, so a run ref `autohelix/` stays quiet; `ask:`/`review:` entries skipped: a judge reads `experiment/`; advice `$AUTOHELIX_EXPERIMENT/...`, `$AUTOHELIX_EXPERIMENT` for the folder itself); bare `autohelix` starts `agents.executable`. A set `AUTOHELIX_CLAUDE_CMD` is a `ConfigError` from the one check in `agents.executable` (`variable_problem`'s message), wherever an executable is resolved: a backend resolves its own when created (`create_agent`; so `Harness.__init__`, the report, a judge call), preflight, the entry screen; each command reports it as a config error (`cli._start`, `report`, `ask`/`review` exit 2, the entry screen's warning). `ask`/`review` take `--cli`/`--model`/`--effort` (`cli._judge_options`; `--agent`/`--command` are hidden errors). - Copy location: copies live outside the project, at `/-//iter-N-`, where base is `$AUTOHELIX_COPIES_ROOT` or `${XDG_CACHE_HOME:-~/.cache}/autohelix/copies` (`runs.copies_base()`). `runs.claim_copies()` fixes the folder for a process under the run lock (created on first use by `ensure_copies`: private 0700, owned, no symlinks below the base; a shared base must be sticky), base recorded in `runs//.internal/copies` for observers (`RunPaths.copies`), `GIT_CEILING_DIRECTORIES` set there. Segment end, standalone report and delete remove it; the project's folder stays with a `project.json` record (path, host) so `runs.sweep_copies()`, at the start of every `run`/`resume`, can remove leftovers of killed processes (runs whose lock is free) and other projects' folders whose checkout is gone (same host, over a day old). The root `conftest.py` points the base at a temporary folder for every test, examples included. - State layout (`RunPaths`; user docs: the two folders, `autohelix/` yours and `.autohelix/` the harness's, and where configs live in `docs/concepts.md`, the layout in `docs/phases.md`): `runs//` holds what people read (`run.json`, `config.yaml`, `experiment/`, `history.jsonl`, `hints.md`, `report.md`/`.html`, the `notes` link, `iterations/NNN/`, `logs/`); the harness's own files are in `runs//.internal/` (`status.json`, `segments.jsonl` (the run's event log: a start record, an iteration record per final record, an end record per segment), `stop.json` (`autohelix stop`'s request), `usage/NNN.jsonl`, `copies`, `notes//`, `attempts/`, `report.json`, ...) and `.autohelix/.internal/` (`locks/.lock`, `locks/selection.lock`, `bin/`). Iteration folders are three digits (`000` the baseline): `record.json` (derived: every record write goes through `history.write_records`, which rewrites it last; present = folder complete), `prompt.md`, `agent.log`, `notes` (link to the version saved with it), `gates//` and `stop//` (1-based position in `gates:`/`stop:`, only for commands that ran: `command.txt`, `stdout.txt`/`stderr.txt` capped 64 KB head + 1 MB tail, `ask*.log`), `observe//` (uncapped stdout, stderr, captures, `review*.log`), `rejected.patch`. A reused number (killed iteration, baseline retry) first moves the old folder to `.internal/attempts/NNN-/` (`History.supersede`). Each command runs in a call folder named after where its output goes (`iter-N-gates-2`, `iter-N-observe-`, `iter-N-stop-1` in the copies folder; `$AUTOHELIX_CALL` = `gates/2`, ...). Its output is staged there after the command ended, then replaces its stored folder; `$AUTOHELIX_LOG_DIR` is the call folder's private `logs/`, from which only regular single-link `ask*.log`/`review*.log` move into the staged output. A judge's usage record names its transcript at call time by destination, `{"call": "gates/2", "log": "ask.log"}`, never rewritten: `RunPaths.usage_log` resolves it (stored if it's there, else the live call folder); a baseline retry appends a `{"superseded": "000-1"}` marker and `usage_log.read_usage` gives the records before it that `attempt` (other tools' records keep a `log` path). Logs named by untrusted metadata open only via `safe_open.open_run_log` (`RunPaths.relative_log`; with `running`, also the running iteration's live `/iter-N-/logs/` transcripts, `RunPaths.live_transcript`), for viewer and `view` alike. - Copy layout: nothing in a copy looks like project state. Agent copies get the harness's material in `/.autohelix-iteration/` (`workspace.ITERATION_DIR`), mirroring the run folder: `prompt.md` (the rendered prompt), `notes/`, `history.jsonl`, `hints.md`, `iterations/NNN/` for the last 5 iterations plus the last accepted one (`iteration.seeded_iterations`: `record.json`, failing gates' `gates//`, `observe/`, `stop/`; no `agent.log`, `prompt.md`, `notes` link, passing gates or `rejected.patch`), `rejected.patch` (after a rejection), `commit_summary.txt` (written by the agent), `experiment/` (a copy of `runs//experiment/` when it holds a file, `experiment.has_files`; `copy_dir(read_only=True)`: files keep read/exec bits, no write bits; the prompt's `experiment` variable names it), and `runs//` for the imported run (`run --import`) and other runs of the group (`run.json`, `history.jsonl`, `notes/`); the prompt has one reading list, "Where things are" (the run's own notes and iterations; with an imported run or group members, also their `runs//` (read-only) and refs), and the hints' text (`hints_text`). Checks copies get only `candidate.diff` (the complete change, new files included); a judge's own copy (made by `autohelix ask`/`review` in `$AUTOHELIX_SCRATCH`) `candidate.diff` (`--binary`), for `review --previous`, `previous.md`, and with `$AUTOHELIX_EXPERIMENT`, `experiment/` (regular files and folders only, read-only like the agent's; `Target.experiment`, named by `describe_change`); stop copies get none of it. `$AUTOHELIX_PREVIOUS` (`observe//` of the last accepted iteration where the entry succeeded), `$AUTOHELIX_OBSERVATIONS` (the accepted iteration's `observe/`) and `$AUTOHELIX_EXPERIMENT` (the run's `experiment/`: `call_folder` adds it for every gate, observe and stop call when the run's holds a file, `has_files`; `_call_env` sets it or unsets it) are per-call copies; the report's prompt names `experiment/`. A copy's `.git` lists branches, tags, remotes and only this run's ref plus its imported run's and its group's (`Copy.create(refs=...)`); other runs' commits are reachable by hash, not discoverable. -- Scope enforcement: `Copy.snapshot()` resets out-of-scope paths to A's entries in the harness index only (nothing is written into the copy), with `--attr-source=A` when git supports it. `.autohelix/` and `.autohelix-iteration/` are excluded from `add -A` by pathspec (unless already ignored: git refuses an exclude naming an ignored folder), so their contents are never hashed into the user's object store. Submodule changes reject the iteration. +- Scope enforcement: `Copy.snapshot()` lists the change set first, hashing nothing (`update-index --refresh`, `diff-files`, `ls-files --others --exclude-standard`), and stages only the in-scope names with `update-index` (`Copy._staged`: a file or symlink not below a symlink is `--add --replace`d, any other name `--force-remove`d; unlike `add`, it stages a tracked file in an ignored folder), so an out-of-scope file never enters the user's object store; out-of-scope entries a staged name replaced (a folder turned into a file) are reset to A's entries in the harness index only (nothing is written into the copy), with `--attr-source=A` when git supports it. `.autohelix/` and `.autohelix-iteration/` are excluded from the listing by pathspec (unless already ignored: git refuses an exclude naming an ignored folder), so their contents are never hashed either. Submodule changes and nested repositories (a `dir/` in the listing) reject the iteration, in scope or not. The record lists the first 20 discarded paths, frozen ones first (`history.DISCARDED_LISTED`, `Harness._describe_attempt`; `discarded_more` counts the rest). - Notes persist across rejections: freezing (or closing) the agent copy saves `notes/` as a new version, `runs//.internal/notes//` (`7-2` for a second save of 7; each a plain copy), then swaps the `runs//notes` symlink and the iteration's `iterations/NNN/notes` link to it by rename (`iteration.save_notes()`; deletions honoured, all versions kept; a pre-version real `notes/` folder becomes `.internal/notes/old`). `notes/` is the sole agent-owned region and the only thing that round-trips; `iteration.prepare_state()` seeds agent copies with `notes/` plus read-only reference. -- Run identity: `RunPaths` is the authority for state layout. Ids are `YYYYMMDD-HHMM-[name-]xxxx`; the suffix is unique across the repo's run refs and every command accepts it (`runs.resolve_run`). Runs have no lifecycle state, only an `archived` flag. `run` always creates (`select_run(new=True)`, warnings only); `resume` takes an id, else a config name (`resume perf`), else the default config, and continues that config's most recently active non-archived run, preferring runs with a baseline (`cli._resume_target`; with nothing to run, `--land`/`--group` are stored at once, `runs.set_options`). There is no current-run pointer: `land`, `hint`, `view --terminal`, `report` without an id take `runs.default_run` (`view` without an id and without `--terminal` shows all runs) (the one running run, else the most recently active non-archived one; several running refuse), named on stderr (`cli._chosen_run`). Commands that read runs find the project from a subfolder (`runs.find_project`, `cli._project`); multi-id commands resolve every id first (`runs.resolve_runs`, `cli._each_run`). The viewer serves run data only under `/api/run//` (`RunData` needs an id). A new run is named after its experiment folder (`config.config_name`: NAME for `autohelix/NAME/config.yaml`; `runs.new_run_name`; no `name:` key, no `run --name`); the config path in `run.json` is the source file, always `autohelix/NAME/config.yaml` as named, also when `autohelix/` is a link (`config.config_relative`, which `load_config` also uses to set `Config.experiment`; naming, `config.run_command`, a bare `resume`'s selection, messages; there is no `-c`); a config that isn't an experiment's is refused (`config.not_an_experiment`: `Harness.__init__` for a new run, `select_run`, `runs.load_run_config`). All writing operations hold the per-run process lock. Whether a run is running comes from that lock: a running status (or open segment) on this host whose lock is free, or held by this process under another pid, reads as crashed (`run_status.holder_gone`, used by `read_run_status` and `wait`; `runs.is_live` probes read-only and creates no lock file). A run folder without its stored config/template (a development build's) is refused (`runs.development_run`). Legacy top-level histories are refused for writes; no migration is attempted. -- One config per run: `select_run` stores `runs//config.yaml` at creation (the file's text verbatim) and, with a `prompt_template:`, its text as `runs//prompt_template.md` (`RunPaths.template`). Its experiment folder (`Config.experiment`: autohelix/NAME/, from `config_name`; None only for a Config not loaded from one) is also stored as `runs//experiment/` (`RunPaths.experiment`; an empty folder when it holds only the config, kept for `resume` to compare and otherwise treated as none: `has_files`): `experiment.snapshot_files` decides what goes in (config, template, dotfiles, dot-folders, `__pycache__/` left out; links followed only into the project's `autohelix/`, not under a dot-name there) and refuses, as a `ConfigError` naming the files (at most `MAX_REFUSED`, then "and N more"; the walk stops at `MAX_FILES` refusals, "and more"), the folder itself when it is a link out of `autohelix/`, into a dot-name there or to `autohelix/` itself ("an experiment must be a folder inside autohelix/"), other or dangling links, a link to a folder holding the experiment folder (`up -> ..`), a folder reached twice (one set of visited real paths for the whole walk), non-regular or unreadable files (OS errors included), and, as soon as the walk passes one, over `MAX_FILES`/`MAX_FOLDERS`/`MAX_BYTES`; it runs in `Harness._new_run_ready` (so `run --check` too) and again in `select_run` before anything is written; `build_snapshot` copies it into a dot-folder in `runs/` (files keep the source's read and exec bits, `mode & 0o555`; folders writable, so `delete`'s rmtree works; a file it can't copy, or whose size differs from the walk's, is a `ConfigError` naming it), renamed into the new run folder before its config is written (a killed run's leftover, `.experiment-*`, is removed by the next `select_run`, `experiment.sweep_staging`, under the selection lock every build holds). Every reader loads that copy (`runs.load_run_config`: `source=` the file it came from, `template_text=` the stored template, which `Config.prompt_template_text` carries): segments, `view`, `report`, the viewer (which also shows the stored template), judges' `$AUTOHELIX_CONFIG`. `Harness.config_file` is the source file. `Harness._run_config` refuses an existing run before anything is spent when the file's parsed config differs (`config_changes`: the `Config` fields the harness uses, plus the template texts; other spellings of a value aren't changes), naming the settings and `run --import`, then when the live experiment folder differs from `runs//experiment/` (`_check_experiment`, `experiment.snapshot_changes`: bytes and exec bit per file, naming changed, added and removed files, or a folder `snapshot_files` now refuses); a deleted file, template or folder continues (dim note), a run without a snapshot isn't compared; a run without `config.yaml`, or without its stored template, refuses; a run `select_run` just created isn't compared. Both stored files are 0444. The config and template files are always frozen, as named and resolved, and so is all of `autohelix/`, for every config, as a folder pattern (what of it is committed is in every copy; `lib/` too) (`Config.protected`; `frozen_names()` shown: `autohelix/` always, instead of the files in it; `frozen_patterns()` matched, all of `protected`, glob-escaped); agent copies lose only the files (`Config.hidden`). `_uncommitted_config` also warns, in one line, about the folder's untracked, non-ignored files the run stored in `runs//experiment/` (`git ls-files --others --exclude-standard`; a listed link counts by the stored files under it; modified tracked files can't get there: `require_clean` refuses them first). +- Run identity: `RunPaths` is the authority for state layout. Ids are `YYYYMMDD-HHMM-[name-]xxxx`; the suffix is unique across the repo's run refs and every command accepts it (`runs.resolve_run`; given an experiment's name it names that config's latest run, an archived one marked so, else it lists the latest real ids). Runs have no lifecycle state, only an `archived` flag. `run` always creates (`select_run(new=True)`, warnings only); `resume` takes an id, else a config name (`resume perf`), else the default config, and continues that config's most recently active non-archived run, preferring runs with a baseline (`cli._resume_target`; with nothing to run, `--land`/`--group` are stored at once, `runs.set_options`). There is no current-run pointer: `hint`, `view --terminal` without an id take `runs.default_run` (`view` without an id and without `--terminal` shows all runs) (the one running run, else the most recently active non-archived one; several running refuse); `land` and `report`, which a running run refuses, take `default_run(running=False)` (the most recently active run that isn't running or archived), named on stderr (`cli._chosen_run`). Commands that read runs find the project from a subfolder (`runs.find_project`, `cli._project`); multi-id commands resolve every id first (`runs.resolve_runs`, `cli._each_run`). The viewer serves run data only under `/api/run//` (`RunData` needs an id). A new run is named after its experiment folder (`config.config_name`: NAME for `autohelix/NAME/config.yaml`; `runs.new_run_name`; no `name:` key, no `run --name`); the config path in `run.json` is the source file, always `autohelix/NAME/config.yaml` as named, also when `autohelix/` is a link (`config.config_relative`, which `load_config` also uses to set `Config.experiment`; naming, `config.run_command`, a bare `resume`'s selection, messages; there is no `-c`); a config that isn't an experiment's is refused (`config.not_an_experiment`: `Harness.__init__` for a new run, `select_run`, `runs.load_run_config`). All writing operations hold the per-run process lock. Whether a run is running comes from that lock: a running status (or open segment) on this host whose lock is free, or held by this process under another pid, reads as crashed (`run_status.holder_gone`, used by `read_run_status` and `wait`; `runs.is_live` probes read-only and creates no lock file). A run folder without its stored config/template (a development build's) is refused (`runs.development_run`). Legacy top-level histories are refused for writes; no migration is attempted. +- One config per run: `select_run` stores `runs//config.yaml` at creation (the file's text verbatim) and, with a `prompt_template:`, its text as `runs//prompt_template.md` (`RunPaths.template`). Its experiment folder (`Config.experiment`: autohelix/NAME/, from `config_name`; None only for a Config not loaded from one) is also stored as `runs//experiment/` (`RunPaths.experiment`; an empty folder when it holds only the config, kept for `resume` to compare and otherwise treated as none: `has_files`): `experiment.snapshot_files` decides what goes in (config, template, dotfiles, dot-folders, `__pycache__/` left out; links followed only into the project's `autohelix/`, not under a dot-name there) and refuses, as a `ConfigError` naming the files (at most `MAX_REFUSED`, then "and N more"; the walk stops at `MAX_FILES` refusals, "and more"), the folder itself when it is a link out of `autohelix/`, into a dot-name there or to `autohelix/` itself ("an experiment must be a folder inside autohelix/"), other or dangling links, a link to a folder holding the experiment folder (`up -> ..`), a folder reached twice (one set of visited real paths for the whole walk), non-regular or unreadable files (OS errors included), and, as soon as the walk passes one, over `MAX_FILES`/`MAX_FOLDERS`/`MAX_BYTES`; it runs in `Harness._new_run_ready` (so `run --check` too) and again in `select_run` before anything is written; `build_snapshot` copies it into a dot-folder in `runs/` (files keep the source's read and exec bits, `mode & 0o555`; folders writable, so `delete`'s rmtree works; a file it can't copy, or whose size differs from the walk's, is a `ConfigError` naming it), renamed into the new run folder before its config is written (a killed run's leftover, `.experiment-*`, is removed by the next `select_run`, `experiment.sweep_staging`, under the selection lock every build holds). Every reader loads that copy (`runs.load_run_config`: `source=` the file it came from, `template_text=` the stored template, which `Config.prompt_template_text` carries): segments, `view`, `report`, the viewer (which also shows the stored config's and template's text, read as the rest of run state is: no symlinks, one link, `RunData._stored_text`), judges' `$AUTOHELIX_CONFIG`. `Harness.config_file` is the source file. `Harness._run_config` refuses an existing run before anything is spent when the file's parsed config differs (`config_changes`: the `Config` fields the harness uses, plus the template texts; other spellings of a value aren't changes), naming the settings one level down (`config._detail`: `agent.timeout`, `gates entry 2`, `observe bench (added)`) and `run --import`, then when the live experiment folder differs from `runs//experiment/` (`_check_experiment`, `experiment.snapshot_changes`: bytes and exec bit per file, naming changed, added and removed files, or a folder `snapshot_files` now refuses); a deleted file, template or folder continues (dim note), a run without a snapshot isn't compared; a run without `config.yaml`, or without its stored template, refuses; a run `select_run` just created isn't compared. Both stored files are 0444. The config and template files are always frozen, as named and resolved, and so is all of `autohelix/`, for every config, as a folder pattern (what of it is committed is in every copy; `lib/` too) (`Config.protected`; `frozen_names()` shown: `autohelix/` always, instead of the files in it; `frozen_patterns()` matched, all of `protected`, glob-escaped); agent copies lose only the files (`Config.hidden`). `_uncommitted_config` also warns, in one line, about the folder's untracked, non-ignored files the run stored in `runs//experiment/` (`git ls-files --others --exclude-standard`; a listed link counts by the stored files under it; modified tracked files can't get there: `require_clean` refuses them first). - Read-only evaluation: gate, observe and stop commands, reviews and `ask` must not change candidate files. A gate or observe command's change rejects (checks copy verified after every command; the command's gate item or observe record is marked failed). Stop commands run after acceptance: the acceptance stays, the change is an error (`AutoHelixRunError`). Each stop command that ran is recorded in the record's `stops` (`checks.StopCheckResult.record`: outcome stop/continue/error, return code, `timed_out` as a flag, as gate items have it), shown as a note under the row (`terminal.Table._notes`) and in the viewer. `ask` and `review` judge the same target (`judge.judged`): in a run their own fresh copy of `$AUTOHELIX_CANDIDATE` in its own folder of `$AUTOHELIX_SCRATCH` (`candidate_target`; never the checks copy, where commands leave files and run candidate code), with `candidate.diff` named in the prompt (`describe_change`); by hand the current directory and its working-tree diff (`checkout_target`). One write guard (`DirectoryGuard`, git's listing of the judged directory, a walk outside a repository) around each call: a change fails the call (no retry, nothing sticky). Codex judges get `-c project_doc_max_bytes=0` (no AGENTS.md; unconfirmed against a real Codex). Ordinary review failures are recorded and continue; scripts own `ask` exit codes. - Launcher: harness commands run with PYTHONPATH remapped to the copy, so `iteration.call_folder()` writes `bin/autohelix` (`launcher.py`: the harness's interpreter with `-I`, its own package first on sys.path) and puts it first on PATH; candidate code can't replace modules inside `ask`/`review`. Each command also gets `AUTOHELIX_CANDIDATE` (T as a tree), `AUTOHELIX_BASE` (A), `AUTOHELIX_PROJECT`, `AUTOHELIX_SCRATCH`, stdin `/dev/null` (`checks._execute`), and runs in its own process group, killed whole when it ends. The main agent gets neither `AUTOHELIX_PROJECT` nor `AUTOHELIX_RUN_DIR` (`run_agent`'s `deadline_env` unsets them; it gets `AUTOHELIX_RUN_ID`, `AUTOHELIX_ITERATION`), and its copy has the config file and template removed (`IterationWorkspace.agent_copy(hidden=Config.hidden)`, never through a symlink; frozen, so `snapshot` resets them, and a still-absent one isn't reported as discarded): hygiene, not a boundary. - Exit codes (`cli._segment`, `Harness.run`'s return): `run`/`resume` exit 0 for a polite end (budget, `stop:`, `autohelix stop`), 1 for errors (refused start incl. preflight on resume and no run to resume, the agent failing 3 times or once for its infrastructure, a failed auto landing: `Harness.run` raises an `autohelix_reported` `AutoHelixRunError` after the ending), 130 when interrupted (`run` returns "interrupted" for one in the loop; one in the baseline/summary propagates; `cli._interruptible` maps Ctrl-C anywhere in `run`/`resume`, Harness init and preflight too). `ask`/`review`/`wait` keep their own codes. Documented in docs/cli.md#exit-codes. -- Recovery/accounting: under ownership, repair only a torn unterminated final history record and recover published commits from run/iteration trailers. Each attempted main-agent failure (an unsuccessful or timed-out call) records a rejected, unchecked iteration (`agent_error`), consumes its number, and the loop continues; `harness.MAX_CONSECUTIVE_AGENT_FAILURES` (3) in a row within a segment stop the run (stop reason kind `agent`). A call its backend reports as an infrastructure failure (`AgentRunResult.infrastructure`, `agents.infrastructure_reason`: Claude Code's `api_error` result with `api_error_status` 401/403/429/5xx, Codex's `turn.failed` "unexpected status 401/403", OpenCode's `error` event `statusCode`; an OpenCode `error` event fails the call at exit 0 too) is recorded the same way (plus the record's `infrastructure`) and stops the run at once (kind `infrastructure`, its detail says to fix it and resume); both kinds (`harness.AGENT_STOPS`) exit 1 and skip the summary. Judges don't use it. Failures before the call (copy, prompt) do not consume the number and stop the run with an error. Baseline retries remain iteration 0 and retain earlier call charges. Calls with unavailable usage remain unknown. Codex calls are priced (`agents/codex_cost.estimate_cost`) from the model Codex's JSON output names, else `agent.model`, else unavailable ("set agent.model"); no session files, no `extra_args` guessing. A timed-out OpenCode call has an error and an unknown cost (its finished steps' as `partial_cost_usd`). Every backend's result usage carries `agents.call_fields`: `cli`, `model` (what its output named: Claude Code's `init` event; Codex 0.171's JSON names none (checked on a real Codex, so its pricing needs `agent.model`; a `model` field is still read if a version adds one); OpenCode's events name none, None, unconfirmed) and `executable` (`backend.executable`, resolved once when created; the mock's is `$AUTOHELIX_MOCK_CMD`); so the history's agent call, judge usage records (`cli`, was `agent`) and summary usage have them. The segment start record has the main agent's `executable` (`_run` warns when it differs from the last segment's) and `autohelix_version` (`terminal.version`, as the header shows it; `wait`'s events don't carry it); the header's Agent line is `terminal.agent_text` (configured model; `view`'s run screen and the viewer's run page use `history.latest_agent_call`'s reported model, the run payload's `agent`). -- Resume/landing: one function computes the run/target relation, `runs.landing` (a `Landing`: the run's tip, the target's tip, `same`/`ahead`/`behind`/`diverged`/`landed` (the target lacks the tip and run.json's `landed.tip`, which is the tip or an ancestor of it, and `landed.target` is the branch compared, recorded by `land` and auto landing only on the run's own target and for a run with commits, `runs._record_landed`: a squash-merged PR; nothing compares the code; commits after it are `diverged`, only they count, and `Landing.since` makes their command `git cherry-pick ..autohelix/`; run.json's hashes go to git only if they match `runs.COMMIT`) or None when a side is missing, and the commit counts each way: `ahead` the unlanded ones beyond the base, `behind` the target's the tip lacks; `accepted`, the tip isn't the base), and one words it, `runs.landing_words(landing, run_id, land_mode)` (a `LandingWords`: the runs table's and web run list's cell, a sentence with what works, the end block's note, the commands that land: `autohelix land ` only for `ahead`, `git merge autohelix/` for `diverged`, the sentence's `state` without its advice and `missing`, `'s N accepted commits aren't in `; "diverged" is the one word); `reconcile`, `land`, `delete`, the new-run notices and `land_first` (`run --import`), the harness's ending (`Harness._relation`; `_land` has no pre-check of its own: `land` refuses), `view --json`'s `landing` (`Landing.payload()`) and `landing_words` (`cell`, `text`, `note`, `commands`: what the runs table, the entry screen's suggestion and `view --terminal` (end block, `next`) show, `run_table._words`) read it. `resume` only continues the same run (stored config, own tip): a target branch past the run's tip (`behind`, `landed`) refuses an auto-landing resume before anything is written (`Harness.__init__`, again under the lock in `runs.reconcile`, which no longer fast-forwards the run onto it) and is a warning in manual mode; a resume after a `stop:` condition says it continues (`cli._stopped_note`). Only initial baseline capture requires a clean checkout. After baseline, gates/observe/stop/report use run candidate copies. Auto landing runs before report, with a finally fallback preserving original errors. The pin is deleted at every segment end. Archive retains evidence and unlanded refs; delete removes state/ref while persistent lock files remain outside the deleted directory. +- Recovery/accounting: under ownership, repair only a torn unterminated final history record and recover published commits from run/iteration trailers. Each attempted main-agent failure (an unsuccessful or timed-out call) records a rejected, unchecked iteration (`agent_error`), consumes its number, and the loop continues; `harness.MAX_CONSECUTIVE_AGENT_FAILURES` (3) in a row within a segment stop the run (stop reason kind `agent`). A call its backend reports as an infrastructure failure (`AgentRunResult.infrastructure`, `agents.infrastructure_reason`: only HTTP 401/403 (429 and 5xx are ordinary failures, so three in a row end a long outage): Claude Code's `api_error` result with `api_error_status`, Codex's `turn.failed` "unexpected status 401/403", OpenCode's `error` event `statusCode`; an OpenCode `error` event fails the call at exit 0 too) is recorded the same way (plus the record's `infrastructure`) and stops the run at once (kind `infrastructure`, its detail says to fix it and resume); both kinds (`harness.AGENT_STOPS`) exit 1 and skip the summary. Judges don't use it. Failures before the call (copy, prompt) do not consume the number and stop the run with an error. Baseline retries remain iteration 0 and retain earlier call charges. Calls with unavailable usage remain unknown. Codex calls are priced (`agents/codex_cost.estimate_cost`) from the model Codex's JSON output names, else `agent.model`, else unavailable ("set agent.model"); no session files, no `extra_args` guessing. A timed-out OpenCode call has an error and an unknown cost (its finished steps' as `partial_cost_usd`). Every backend's result usage carries `agents.call_fields`: `cli`, `model` (what its output named: Claude Code's `init` event; Codex 0.171's JSON names none (checked on a real Codex, so its pricing needs `agent.model`; a `model` field is still read if a version adds one); OpenCode's events name none, None, unconfirmed) and `executable` (`backend.executable`, resolved once when created; the mock's is `$AUTOHELIX_MOCK_CMD`); so the history's agent call, judge usage records (`cli`, was `agent`) and summary usage have them. The segment start record has the main agent's `executable` (`_run` warns when it differs from the last segment's) and `autohelix_version` (`terminal.version`, as the header shows it; `wait`'s events don't carry it); the header's Agent line is `terminal.agent_text` (configured model; `view`'s run screen and the viewer's run page use `history.latest_agent_call`'s reported model, the run payload's `agent`). +- Resume/landing: one function computes the run/target relation, `runs.landing` (a `Landing`: the run's tip, the target's tip, `same`/`ahead`/`behind`/`diverged`/`landed` (the target lacks the tip and run.json's `landed.tip`, which is the tip or an ancestor of it, and `landed.target` is the branch compared, recorded by `land` and auto landing only on the run's own target and for a run with commits, `runs._record_landed`: a squash-merged PR; nothing compares the code; commits after it are `diverged`, only they count, and `Landing.since` makes their command `git cherry-pick ..autohelix/`; run.json's hashes go to git only if they match `runs.COMMIT`) or None when a side is missing, and the commit counts each way: `ahead` the unlanded ones beyond the base, `behind` the target's the tip lacks; `accepted`, the tip isn't the base), and one words it, `runs.landing_words(landing, run_id, land_mode)` (a `LandingWords`: the runs table's and web run list's cell, a sentence with what works, the end block's note, the commands that land: `autohelix land ` only for `ahead`, `git merge autohelix/` for `diverged`, the sentence's `state` without its advice and `missing`, `'s N accepted commits aren't in `; "diverged" is the one word); `reconcile`, `land`, `delete`, the new-run notices and `land_first` (`run --import`), the harness's ending (`Harness._relation`; `_land` has no pre-check of its own: `land` refuses), `view --json`'s `landing` (`Landing.payload()`) and `landing_words` (`cell`, `text`, `note`, `commands`: what the runs table, the entry screen's suggestion and `view --terminal` (end block, `next`) show, `run_table._words`) read it. `resume` only continues the same run (stored config, own tip): a target branch past the run's tip (`behind`, `landed`) refuses an auto-landing resume before anything is written (`Harness.__init__`, again under the lock in `runs.reconcile`, which no longer fast-forwards the run onto it) and is a warning in manual mode; a resume after a `stop:` condition says it continues (`cli._stopped_note`). Only initial baseline capture requires a clean checkout. After baseline, gates/observe/stop/report use run candidate copies. Auto landing runs before report, with a finally fallback preserving original errors. The pin is deleted at every segment end. `land` returns what it found when it moved nothing (already there, nothing accepted, landed before), which the CLI prints instead of "Landed". Archive retains evidence and unlanded refs; delete removes state/ref while persistent lock files remain outside the deleted directory, and without `--force` refuses unlanded commits and an accepted tip on no branch, tag or remote-tracking branch (`landed` is no proof: a reset target reads landed too). After a failed first baseline (not an interrupted one, "baseline interrupted"), the end block and `view --terminal` suggest `autohelix run ` and `autohelix delete ` (`terminal.next_commands(restart=)`, `run_table._restart`, from `view --json`'s `baseline`), and so does the entry screen's suggestion. `_refuse_changed` gives the landing first, then the `--import` command, a line each. - Groups: `run --group NAME` (stored in `run.json`; `resume --group NAME|''` changes it) makes runs of the same project share notes and code. Members are the other non-archived runs with that group (`runs.group_members()`), taken once per iteration (`IterationWorkspace.members`): copied into the copy (not linked) and listed in the prompt (`prompt_template.describe_member()`); their refs go into the copy's `.git`. No group commands: budgets, resume, land, archive stay per run. Landing mode is per run, recorded in `run.json` at creation (`--land`; else `manual` with `--group`; else `auto`; `land:`/`report:` are config errors naming `--land`/`--no-report`, like `budget:`), kept on resume, changed by `resume --land`. The "also running for this config" warning is quiet for group runs and when either run lands manually. -- Import: `run --import ID` records `import: {run}` in `run.json` (with `--why`: `why`; `archive --why`: `archive_why`, kept by `--undo`). Each iteration `IterationWorkspace.imported` (`runs.imported_run`, None when unreadable) is shown like a member (`others`: copied into `runs//`, its ref in the copy's `.git`; dropped from `members` if also in the group) and as the prompt's `imported`; at the baseline, `_observe` takes `$AUTOHELIX_PREVIOUS` from the imported run's history by entry name. Not imported: budgets, metric reference, group, notes (the new run's start empty). Harness git calls on the user's repo (`Repo.git`, `runs.git`) retry briefly on lock contention (`workspace.run_git`). +- Import: `run --import ID` records `import: {run}` in `run.json` (with `--why`: `why`; `archive --why`: `archive_why`, kept by `--undo`). Each iteration `IterationWorkspace.imported` (`runs.imported_run`, None when unreadable) is shown like a member (`others`: copied into `runs//`, its ref in the copy's `.git`; dropped from `members` if also in the group) and as the prompt's `imported`; until an entry has succeeded in this run (normally the baseline), `_observe` takes its `$AUTOHELIX_PREVIOUS` from the imported run's history by entry name. Not imported: budgets, metric reference, group, notes (the new run's start empty). Harness git calls on the user's repo (`Repo.git`, `runs.git`) retry briefly on lock contention (`workspace.run_git`). - Time limits: `agent.timeout` (a duration; replaces `agent.timeout_seconds` and `budget.iteration_time`, which are now config errors) is always a hard kill of the main agent, and also gives time-left hints where the CLI supports them: Claude Code hooks (`PostToolUse`/`UserPromptSubmit`), the same hook for Codex CLIs that support it (`_check_codex_time_left`: an older one warns and runs without), an OpenCode plugin; all via `$AUTOHELIX_TIME_LEFT_SCRIPT` (`/.autohelix/.internal/bin/time_left.sh`, copied from `src/autohelix/bin/` at run start). Claude Code's hooks are in one `--settings` file (`runs//.internal/claude_settings.json`, 0600): a user `--settings` in `extra_args` is taken out (`claudecode.split_settings`) and merged into it (`merged_settings`: the user's hook lists plus AutoHelix's; unreadable: a `ConfigError` in `Harness.__init__`, `run --check` too). Every agent command ends `-- `; the main Claude Code agent also gets `--disallowedTools ScheduleWakeup`. `ask:`/`review:` entries don't use it: the entry's `timeout:` is the command's deadline and the judge's `--timeout` (an `ask:` entry's defaults to 10m, `config.ASK_TIMEOUT`; an entry `agent.timeout` is an error). See `harness.py:_install_time_left()`. -- Budgets are per segment (one `run`/`resume` command; a `Harness` runs one segment, a second `run()` raises), on the command line (`budget:` is a config error naming the flags): `run`/`resume` `-n` / `--until` / `--cost` / `--time` make a `harness.Budget` (`Harness.run(budget)`; library callers and tests pass one too). `Budget.last_iteration(done)`: `--until`, else done + `-n`, else no cap with only cost/time, else done + `DEFAULT_ITERATIONS` (1: a bare `run` is one checked attempt). `--cost` counts what this segment charged (the baseline's from the history, then each iteration's `result.cost`), `--time` its monotonic wall clock (baseline included); both checked before and after each iteration (never interrupting one). `status.json` records the caps: `max_iterations` (None: no cap) and `max_cost_usd` = cost before + `--cost` as run totals, `max_time_seconds` as this segment's own `--time` (never a run total) with `segment_started_at`, the wall-clock time its `--time` counts from; the viewer's `progress` and `view` read them from there, never from the config (`run_table.time_cap` in `view`'s Budget field, `dashboard.js timeCap`, viewer.js's Budget chip, all formatting with `iteration_time.format_duration`'s 1h30m: only while running, "12m5s of 1h (this segment)", the web run list's row short "12m5s/1h", "(time up)" past the cap; the run's total time has no cap). `runs//.internal/segments.jsonl` (`run_status.SegmentLog`, `read_segments`, `RunPaths.segments`) is append-only: a start record written with the status at the top of `_run`, before its checks (ensure_runtime_ignored, require_clean, preflight: a refused start is a failed segment that lands nothing, `_segment_checked`), an iteration record (`SegmentLog.iteration`, `events.iteration_fields`: the `iteration` event's fields) each time a record is final (after `workspace.record` wrote it, in `run_iteration`'s finally, after stop commands; `_write_baseline`, a failed baseline too; a record no line reports, its process killed in between or `reconcile` recovering it, is logged for the last segment before the next start, `SegmentLog.catch_up`), an end record (state, stop reason, iterations added, last iteration, error) in `run()`'s finally, linked by `segment`; one O_APPEND write + fsync each, never rewritten; `read_segments` pairs start and end and marks a start without an end `open`. `autohelix wait` (`events.Watcher`) is a pure reader of that one log per run (read on from where it ended; opened via `safe_open.open_file`: regular file, no symlinks, `LOG_CAP`), nothing written; its events are the log's lines in order plus `crashed` (an open segment followed by another's start, or whose process is gone, `holder_gone`, on a reread; once confirmed not probed again until the log grows); its cursor is per run `[lines reported, last segment reported crashed]` (`Marks`; never times; a crash is pending until its segment is marked, so lines appended after it don't report it again); a run without segments is `new`. `RunLock` retries for a moment (`runs.LOCK_RETRIES`) so an `is_live` probe of a free lock doesn't refuse a resume. The status carries the segment's number (`segment`, `SegmentLog.next_number()` before `run_status.start`). `autohelix stop` (`cli._stop_run`) writes `runs//.internal/stop.json` (`run_status.write_stop_request`: `requested_at`, `why`, `now`, `segment` from the status, `host`, `pid`), only while the status says running (`read_run_status`: its lock held) with a segment number; `_run` honours only a request for its own segment (`Harness._requested_stop`) at the top of each loop pass (first right after the baseline; never during an iteration), ending like a budget (stop reason kind `request`). `--now` also sends SIGTERM to the status's pid (same host, `ps` says autohelix), after writing the request: a background run a script started ignores SIGINT, and `Harness.run` takes SIGTERM as Ctrl-C (`_terminate_interrupts`, over the default action only; `runs.critical_section` defers both); the interrupt path notes it as the stop reason (`_note_interrupt_request`; state stays interrupted). A stale request is removed at segment start (before the status says running), the request at segment end; the viewer's run row shows it as `stop_requested` (`run_status.pending_stop`). With `--cost` the only bound, an unknown charge stops the segment only while none of its charges was priced (`priced`: a backend that can't price; else it warns). The run summary (`Harness._summary`, after the loop and landing) is skipped after an `agent` or `infrastructure` stop; its failure or Ctrl-C prints a line and leaves the segment's outcome; each call's usage goes to `.internal/usage/summary.jsonl` (`RunPaths.summary_usage`), counted by `History.cost_usages` and the viewer's totals. A flagless `resume` after an interrupted/crashed status without a `stop_reason` prints what it had left (`cli._interrupted_note`); `resume --until N` at or past N exits 0 before anything is written (`cli._last_iteration`, via `planned_run`). +- Budgets are per segment (one `run`/`resume` command; a `Harness` runs one segment, a second `run()` raises), on the command line (`budget:` is a config error naming the flags): `run`/`resume` `-n` / `--until` / `--cost` / `--time` make a `harness.Budget` (`Harness.run(budget)`; library callers and tests pass one too). `Budget.last_iteration(done)`: `--until`, else done + `-n`, else no cap with only cost/time, else done + `DEFAULT_ITERATIONS` (1: a bare `run` is one checked attempt). `--cost` counts what this segment charged (the baseline's from the history, then each iteration's `result.cost`), `--time` its monotonic wall clock (baseline included); both checked before and after each iteration (never interrupting one). `status.json` records the caps: `max_iterations` (None: no cap) and `max_cost_usd` = cost before + `--cost` as run totals, `max_time_seconds` as this segment's own `--time` (never a run total) with `segment_started_at`, the wall-clock time its `--time` counts from; the viewer's `progress` and `view` read them from there, never from the config (`view`'s Budget field says the caps are run totals, "to iteration 8 · $5.04 run total"; the time used of `--time`, only while running, "(time up)" past the cap: `run_table.time_cap`, "12m 05s of 1h (this segment)", and on the web `dashboard.js timeCap` and viewer.js's Budget chip, "12m5s of 1h (this segment)", the run list's row short "12m5s/1h"; the run's total time has no cap). An incomplete cost is `$0.07+` on every screen (`terminal.money`, `format_total_cost`). `runs//.internal/segments.jsonl` (`run_status.SegmentLog`, `read_segments`, `RunPaths.segments`) is append-only: a start record written with the status at the top of `_run`, before its checks (ensure_runtime_ignored, require_clean, preflight: a refused start is a failed segment that lands nothing, `_segment_checked`), an iteration record (`SegmentLog.iteration`, `events.iteration_fields`: the `iteration` event's fields) each time a record is final (after `workspace.record` wrote it, in `run_iteration`'s finally, after stop commands; `_write_baseline`, a failed baseline too; a record no line reports, its process killed in between or `reconcile` recovering it, is logged for the last segment before the next start, `SegmentLog.catch_up`), an end record (state, stop reason, iterations added, last iteration, error) in `run()`'s finally, linked by `segment`; one O_APPEND write + fsync each, never rewritten; `read_segments` pairs start and end and marks a start without an end `open`. `autohelix wait` (`events.Watcher`) is a pure reader of that one log per run (read on from where it ended; opened via `safe_open.open_file`: regular file, no symlinks, `LOG_CAP`), nothing written; its events are the log's lines in order plus `crashed` (an open segment followed by another's start, or whose process is gone, `holder_gone`, on a reread; once confirmed not probed again until the log grows); its cursor is per run `[lines reported, last segment reported crashed]` (`Marks`; never times; a crash is pending until its segment is marked, so lines appended after it don't report it again); a run without segments is `new`. `RunLock` retries for a moment (`runs.LOCK_RETRIES`) so an `is_live` probe of a free lock doesn't refuse a resume. The status carries the segment's number (`segment`, `SegmentLog.next_number()` before `run_status.start`). `autohelix stop` (`cli._stop_run`) writes `runs//.internal/stop.json` (`run_status.write_stop_request`: `requested_at`, `why`, `now`, `segment` from the status, `host`, `pid`), only while the status says running (`read_run_status`: its lock held) with a segment number; `_run` honours only a request for its own segment (`Harness._requested_stop`) at the top of each loop pass (first right after the baseline; never during an iteration), ending like a budget (stop reason kind `request`). `--now` also sends SIGTERM to the status's pid (same host, `ps` says autohelix), after writing the request: a background run a script started ignores SIGINT, and `Harness.run` takes SIGTERM as Ctrl-C (`_terminate_interrupts`, over the default action only; `runs.critical_section` defers both); the interrupt path notes it as the stop reason (`_note_interrupt_request`; state stays interrupted). A stale request is removed at segment start (before the status says running), the request at segment end; the viewer's run row shows it as `stop_requested` (`run_status.pending_stop`). With `--cost` the only bound, an unknown charge stops the segment only while none of its charges was priced (`priced`: a backend that can't price; else it warns). The run summary (`Harness._summary`, after the loop and landing) is skipped after an `agent` or `infrastructure` stop; its failure or Ctrl-C prints a line and leaves the segment's outcome; each call's usage goes to `.internal/usage/summary.jsonl` (`RunPaths.summary_usage`), counted by `History.cost_usages` and the viewer's totals. A flagless `resume` after an interrupted/crashed status without a `stop_reason` prints what it had left (`cli._interrupted_note`); `resume --until N` at or past N exits 0 before anything is written (`cli._last_iteration`, via `planned_run`). ## Gotchas diff --git a/docker/Dockerfile b/docker/Dockerfile index 064fdcb5..1feb642a 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -29,7 +29,6 @@ RUN git config --system user.email "autohelix@container" && \ # Workspace accessible by any UID RUN mkdir -p /workspace /home/user && chmod 777 /workspace /home/user -ENV AUTOHELIX_IN_CONTAINER=1 ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin WORKDIR /workspace diff --git a/docker/run.sh b/docker/run.sh index a4cc2018..5ee78cd1 100755 --- a/docker/run.sh +++ b/docker/run.sh @@ -25,8 +25,12 @@ ARGS=( --network=host ) -# Mount and source env script -if [ -n "$ENV_SCRIPT" ] && [ -f "$ENV_SCRIPT" ]; then +# Mount and source env script (a mistyped one would run without credentials) +if [ -n "$ENV_SCRIPT" ] && [ ! -f "$ENV_SCRIPT" ]; then + echo "env script not found: $ENV_SCRIPT" >&2 + exit 1 +fi +if [ -n "$ENV_SCRIPT" ]; then ARGS+=(-v "$(cd "$(dirname "$ENV_SCRIPT")" && pwd)/$(basename "$ENV_SCRIPT"):/home/user/env.sh:ro") ARGS+=(-e AUTOHELIX_ENV_SCRIPT=/home/user/env.sh) fi diff --git a/docs/cli.md b/docs/cli.md index 300d5fce..8a16820b 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -17,12 +17,16 @@ part). Without one they act on the **running run**, else the **most recently active run that isn't [archived](#autohelix-archive)**, and say which on stderr ("Run k3f9 (the running run; name one to choose another)"). -- With several runs running they refuse: "Several runs are running: k3f9, - m2x7; name one." +- `land` and `report` skip running runs (a running run refuses them): they + take the most recently active run that isn't running or archived ("Run m2x7 + (the most recently active run that isn't running; …)"). +- With several runs running `hint` and `view --terminal` refuse: "Several runs + are running: k3f9, m2x7; name one." - With no run to act on, they say so and how to start one ("No runs in /path/to/project; start one with `autohelix run`."). - `resume` has its own rule (a config's latest run, - [below](#autohelix-resume)). + [below](#autohelix-resume)). Other commands take run ids only: given a + config name (`land perf`), they name its latest run instead. - Commands that take several ids (`archive`, `delete`, `stop`, `wait`) check every id first: an unknown one refuses the whole command, nothing done. Then they act on each, report each, and exit 1 if any failed. @@ -53,7 +57,8 @@ The screen has: `resume` one that stopped before its end, `land` waiting commits, `git merge autohelix/` for a run whose branch diverged from its target. An interrupted run or one that stopped unexpectedly gets `resume` even with - commits to land, which an auto-landing resume lands; + commits to land, which an auto-landing resume lands; a run whose first + baseline failed gets `autohelix run `; - how many runs are archived, and a pointer to `autohelix --help`; - the question. @@ -267,7 +272,9 @@ VPN alive. `Interrupted`, `Error`), each metric from the baseline to the run's tip, the totals, what landed (`landing failed: …` in yellow when auto landing couldn't, the commits then waiting for `autohelix land`), what to type next - (one command per line, with what it does; left out when it doesn't fit), the + (one command per line, with what it does; left out when it doesn't fit; + after a failed first baseline, `autohelix run ` and `autohelix delete + ` instead of `resume`, which would refuse the fixed setup), the run's `folder` (`report.md`, `history.jsonl`, `iterations/` are in it), and the files written. - **`resume`** shows the baseline and the last 5 rows before `resumed HH:MM`. @@ -288,11 +295,11 @@ pipe, a log file) or colours there is no mark and no live row. The renders at 80 | `--path`, `-p` | Project directory (default: current dir) | | `--group NAME` | Make the run part of a [group](#groups): it sees the other runs of the group (their notes, history and code), and lands manually by default | | `--land auto\|manual` | Land accepted code at the end of each segment, or retain it only on the run ref until `autohelix land`. Stored with the run. Default: `manual` with `--group`, else `auto` | -| `--import RUN_ID` | [Continue from another run](#continuing-from-another-run): its notes and history, read-only, in every iteration, and its last observe outputs at the baseline | +| `--import RUN_ID` | [Continue from another run](#continuing-from-another-run): its notes and history, read-only, in every iteration, and its last observe outputs until each entry succeeds here (normally the baseline) | | `--why TEXT` | Why this run is started: one line (at most 300 characters), stored in `run.json` and shown by `autohelix view` | | `--verbose` | Show agent command details, file paths, heartbeats | | `--no-report` | Don't write the run summary when this segment finishes (not stored: pass it to each `resume` too) | -| `--check` | Start nothing: make every check the run makes before writing anything (the config and its prompt template, the experiment folder, a clean checkout, the agent command, scope patterns, commands naming an `autohelix/` path the commit lacks, `--import`'s run), print what it finds, exit 0 when the run would start, else 1. For setup and CI | +| `--check` | Start nothing: make every check the run makes before writing anything (the config and its prompt template, the experiment folder, a clean checkout, the agent command, scope patterns, commands naming an `autohelix/` path the commit lacks, `--import`'s run), print what it finds, the warnings `run` gives at its start included (other runs' unlanded commits, an uncommitted config), exit 0 when the run would start, else 1. For setup and CI | `run` always starts a **new** run, with its own notes and history; to continue one, use [`autohelix resume`](#autohelix-resume) (scripts that want @@ -342,8 +349,9 @@ When a call fails: row: …"), with landing as at any segment end but no run summary, and the command exits 1. - An infrastructure failure stops the run after that one call: the agent CLI - reported a rejected key or credentials (HTTP 401/403), or, for Claude Code - and OpenCode, an unavailable model service (HTTP 429 or 5xx). The call is + reported a rejected key or credentials (HTTP 401/403). A rate limit or an + unavailable model service (HTTP 429 or 5xx) is an ordinary failure: a short + outage costs an iteration, and three in a row stop the run as above. The call is recorded as any failed call (its record's `infrastructure` says which), then the run stops ("the agent call failed: authentication failed (HTTP 403): …; fix it, then autohelix resume "), lands as after three failures, writes @@ -372,7 +380,7 @@ When a call fails: - **1** on an error: the config or a check refused the start (no run to resume, a dirty checkout, failed preflight checks, also on `resume`), the baseline or an iteration failed with an error, the agent failed three times in - a row or once for its infrastructure (credentials, the model service), or auto landing failed (the iterations stay accepted on the run's ref; + a row or once for its infrastructure (rejected credentials, HTTP 401/403), or auto landing failed (the iterations stay accepted on the run's ref; `autohelix land` once the cause is fixed); - **130** when interrupted: Ctrl-C, SIGTERM, or `autohelix stop --now` (the iteration is recorded and the run lands as usual). @@ -430,9 +438,10 @@ autohelix resume --until 30 --time 2h # up to iteration 30, starting none afte more · 2h", or "1 iteration (default)"). - The run's status records the iteration and cost caps as run totals and the `--time` cap as this segment's own. -- While the segment runs, `view --terminal`'s Budget field shows what is left - of that cap ("47m 55s left (--time 1h)", "time up (--time 1h)" once past - it). The run's total time has no cap (`progress.seconds` in +- `view`'s Budget field shows the status's caps, as run totals ("to iteration 8 + · $5.04 run total"), and while the segment runs the time it used of its + `--time` ("12m 05s of 1h (this segment)", "(time up)" once past it), as the + web pages do. The run's total time has no cap (`progress.seconds` in [JSON output](#json-output)). - Every segment that starts is also an event for [`autohelix wait`](#autohelix-wait). @@ -495,8 +504,9 @@ What it adds: ref, `autohelix/`; the prompt's "Where things are" list names it as imported ("this run continues from k3f9"). They are copied at the start of each iteration, as for a [group](#groups); a deleted imported run is just left out; -- at the baseline, each observe entry gets as `$AUTOHELIX_PREVIOUS` that run's - last successful output of the entry with the same name +- until it succeeds in this run (normally at the baseline), each observe entry + gets as `$AUTOHELIX_PREVIOUS` that run's last successful output of the entry + with the same name ([Previous output](config.md#previous-output)), so a tracker continues from it. `run.json` records `"import": {"run": ""}`. The imported run may be @@ -584,7 +594,8 @@ picking an older one. With no run to resume it exits 1 (see anything, `resume` compares it with the config file: - When the file's parsed config differs (a setting, or the prompt template's - text), it refuses, names the settings, and names both ways out: `autohelix + text), it refuses, names the settings (`agent.timeout`, `gates entry 2`, + `observe bench (added)`), and names both ways out: `autohelix run --import ` applies the new config in a new run, or restore the file to continue this one. - What the run would do counts, not how the file says it: comments, @@ -596,7 +607,7 @@ anything, `resume` compares it with the config file: - The experiment folder is compared with the run's copy (`runs//experiment/`), file by file: a changed file (its bytes or exec bit), an added one or a removed one refuses, naming them, with the same two - ways out (restore the files). Edits to files the folder links to count. A + ways out (restore the files; remove the added ones). Edits to files the folder links to count. A deleted folder isn't a change, and a run without a stored folder resumes as before. - A run started before runs stored their config can't be resumed: continue it @@ -711,7 +722,7 @@ autohelix land [RUN_ID] [-p PATH] [--into BRANCH] ``` Fast-forward the run's starting branch to its accepted tip, preserving unrelated -checkout edits. Without `RUN_ID`, the [running or latest run](#which-run-a-command-acts-on). +checkout edits. Without `RUN_ID`, the [latest run that isn't running](#which-run-a-command-acts-on). - It only fast-forwards: when the target diverged (a commit on it after the run's base, during a segment or since), it refuses, says so, and gives what @@ -720,6 +731,10 @@ checkout edits. Without `RUN_ID`, the [running or latest run](#which-run-a-comma trying to land it. - Auto landing at a segment's end refuses the same way; AutoHelix never rewinds user commits. +- When there is nothing to land it says so instead of "Landed": the run is + already in the branch, it accepted nothing, or it landed there before and + the branch has other commits in their place (to land it again: `git merge + autohelix/`). - A run created from a detached checkout requires `--into BRANCH`. - Landing also refuses branches that are being rebased. @@ -734,12 +749,15 @@ git push origin main:perf-pr # push it as a branch and open a PR from git fetch origin && git reset --hard origin/main # your main as the remote has it ``` -The runs table, `view`, the entry screen and `delete` then read k3f9 as -landed (no `--force` needed), while its tip isn't on main: the target lacks the -tip, but run.json says `land` landed that tip on this same branch. +The runs table, `view` and the entry screen then read k3f9 as landed, while +its tip isn't on main: the target lacks the tip, but run.json says `land` +landed that tip on this same branch. - Nothing compares the code, so if the PR is abandoned and main reset, the run - still reads landed (its commits stay on `autohelix/`). + still reads landed, and `autohelix/` is the only ref to its commits. + So `delete` asks for `--force` for any run whose tip is on no branch, tag or + remote-tracking branch, landed or not; once the PR's branch is gone, use + `--force` or `archive`. - Only a landing on the run's own target is recorded: a landing on another branch (`land --into other`) leaves the record alone, and a squash merge of the run's branch done without `land` (`git merge --squash autohelix/`) @@ -788,8 +806,10 @@ Deletes runs: (`refs/autohelix-rejected//`); - any leftover copies. -It refuses a running run, and a run with accepted commits that its target -branch lacks (they would be lost) unless `--force`. Code on your branch and +It refuses a running run, and, unless `--force`, a run with accepted commits +that its target branch lacks or whose tip is on no branch, tag or +remote-tracking branch (they would be lost; a squash-merged PR's run once its +branch is gone, too). Code on your branch and external artifacts stay intact. To keep a run but hide it, use `archive`. ## `autohelix view` @@ -818,7 +838,7 @@ ssh -L 8765:127.0.0.1:8765 user@host # then open http://localhost:8765 The run list (`/`) has one row per run, with these columns: - its short id and name (with its group, and the config file under it when the run isn't named after it); -- state, with time and cost so far, and what is left of `--time`, under it; +- state, with time and cost so far, and the time used of `--time` (`12m5s/1h`), under it; - iterations; - one metric from the latest accepted iteration, picked from a menu in the column header; its change against the run's own baseline is in the tooltip; - landing; @@ -830,7 +850,7 @@ Hover a cell for details such as the stop reason or budgets; click a row for tha A run's page (`/run//`) shows its `.autohelix/` state: - The header: the goal's title (its first line; click it for the rest) and run status (which iteration and phase is running, or whether the run finished, was interrupted, or crashed, and when; hover for why it ended). -- The left side: the best metric value with total time and cost, the metric over time, and one row per iteration with the agent's one-line summary (and, for a rejection, the gate that failed), then a row for the run summary once one is written (see [`autohelix report`](#autohelix-report)). +- The left side: the best metric value with the total time (the baseline's included, as the run list's) and cost, the metric over time, and one row per iteration with the agent's one-line summary (and, for a rejection, the gate that failed), then a row for the run summary once one is written (see [`autohelix report`](#autohelix-report)). - The right side, one panel: the selected iteration, or, after the last iteration, the run summary (shown when the run has stopped; `#summary`). While a run is live the running iteration is selected. To pick another, click a row or chart point, press `j`/`k`, or use the panel's arrows; `#iter-N` in the address picks one. An iteration's panel has these sections (paths are below `.autohelix/runs//`): @@ -880,7 +900,7 @@ With `RUN_ID`: - `--once` prints the top part of `--terminal`'s screen once and exits (`tests/snapshots/view-*.txt` shows it). In its table a rejected iteration shows the gate that failed (a metric gate as `speed 6.5% worse than iter 3 (5% allowed)`), with failed observe entries, failed stop commands and discarded paths on the lines under it. - `--json` prints the run once and exits, for scripts and agents managing runs: the run's row from [`view --json`](#json-output) under `run`, plus `iterations`, one entry per iteration with: - - `iteration`, `accepted`, `metrics`, `cost`, `cost_incomplete`, `seconds`; + - `iteration`, `accepted`, `metrics`, `cost`, `cost_incomplete`, `seconds` (the baseline's from its start to end); - `summary`: the agent's one-line summary; for records without one, the commit subject, or why it was rejected; - `reason`: why it was rejected, `null` otherwise; - `gates`, in config order: `text`, `kind` (`command` or `metric`), `passed` (`true`, `false`, or `null` when not reached); for commands that ran, `return_code`, `duration_s` (`timed_out` when one did) and, failed, the `output` tail; for checked metric gates, `value`, `reference` and, failed, `reason`; @@ -906,7 +926,7 @@ With `RUN_ID`: - `segment_started_at`, when that segment started (its `--time` counts from there), and `segment`, its number (1, 2, … in the run); - `entry`: the name of the observe entry running, else `null`; - `stop_requested`: while the running segment has been asked to end by [`autohelix stop`](#autohelix-stop), `requested_at`, `why` and `now`; else `null`; - - `accepted`: the number of accepted iterations; + - `accepted`: the number of accepted iterations, and `baseline`: whether its baseline was accepted; - `metrics`: the latest accepted measurement, `iteration` and `values` (`name`, `value`, `baseline`, `direction`), or `null`; - `progress`: - `iterations` attempted, `cost_usd` and `cost_incomplete` (the whole run's), `seconds` (the recorded iterations' wall clock, the baseline's included); @@ -1234,7 +1254,7 @@ Write (or rewrite) the run summary. autohelix report [RUN_ID] [-p PATH] ``` -Without `RUN_ID`, the [running or latest run](#which-run-a-command-acts-on). +Without `RUN_ID`, the [latest run that isn't running](#which-run-a-command-acts-on). One agent call reads the run's history, notes, logs and commits and writes a short summary to `.autohelix/runs//report.md`: what was achieved, which diff --git a/docs/concepts.md b/docs/concepts.md index 2a472121..14484883 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -262,8 +262,9 @@ The variables a template gets are a stable, documented contract: | `hints_text` | The hints' text (the lines `autohelix hint` added, oldest first), else empty; over 8,000 characters, the last whole lines that fit, after a line saying earlier hints are in `.autohelix-iteration/hints.md` | | `rejected_patch` | `.autohelix-iteration/rejected.patch` if the copy has one, else empty | | `rejected_diff` | When the latest rejected change is over 2 MiB (no patch file), the `git diff ` command that shows it, else empty | -| `discarded` | The paths whose changes the latest iteration lost to the scope | +| `discarded` | The paths whose changes the latest iteration lost to the scope (the first 20, frozen ones first) | | `discarded_frozen` | Those of them that are frozen (the others aren't editable) | +| `discarded_more` | How many more paths it lost, not listed (0 for 20 or fewer) | | `last` | The latest iteration (the baseline before iteration 1), or none: `{iteration, accepted, reason, summary, failure_output, gates: [{text, kind, status, path}], observe: [{name, ok, error, missing, path}]}`; `status` is `passed`, `failed` or `pending`, `missing` the declared metrics an entry ran without reporting, and `path` the item's folder in the copy if it has one there, else empty (a failed gate's `.autohelix-iteration/iterations/KKK/gates//`, an observe entry's `.autohelix-iteration/iterations/KKK/observe//`; passing gates' output isn't in the copy) | | `last_accepted` | The latest accepted iteration (the baseline counts), or none: `{iteration, path}`, `path` being its folder in the copy (`.autohelix-iteration/iterations/KKK/`: its record and observations describe the code in the copy), or empty | | `recent_iterations` | How many of the latest iterations the copy has folders of (5; the last accepted one is there too) | @@ -273,11 +274,11 @@ The variables a template gets are a stable, documented contract: | `experiment` | `.autohelix-iteration/experiment/`, the copy of the run's stored experiment folder (`runs//experiment/`), or empty for a folder holding only its config | A custom template is a copy: it won't pick up future changes to the built-in -one. Remove `prompt_template:` to return to it. A run warns when a custom -template uses variables not in this table (such as the old `constraints` or -`history_summary`; they render empty), and when it still names `.autohelix/` -paths in the agent's copy (they are now `.autohelix-iteration/`). -A template naming `worktree`, `copy`'s old name, is a config error. +one. Remove `prompt_template:` to return to it. A custom template that uses +variables not in this table (such as the old `constraints` or +`history_summary`) is a config error, and so is one naming `worktree` +(`copy`'s old name) or `.autohelix/` paths in the agent's copy (they are now +`.autohelix-iteration/`). Agent-written text in the variables (summaries, discarded paths, errors, failure output) has its control characters removed; summaries are cut to 200 characters. @@ -519,7 +520,7 @@ evaluator calls count when they record usage through `$AUTOHELIX_USAGE_FILE`. Codex agent duration is measured locally even when usage is unavailable. Missing, invalid, or interrupted usage remains **unavailable**, not zero, and -totals with unavailable parts are labeled **incomplete**. `--cost` counts the +a total with unavailable parts gets the same `+` (`$0.25+`: what is known). `--cost` counts the saved amounts (Codex estimates included) and is checked between iterations, so it is an approximate stopping threshold, not a guaranteed spending cap; what it does when a cost is unavailable is in [CLI → Budgets](cli.md#budgets). diff --git a/docs/config.md b/docs/config.md index 49575715..4f31f577 100644 --- a/docs/config.md +++ b/docs/config.md @@ -367,10 +367,16 @@ a benchmark gate already rejected. **The baseline** (iteration 0, on the run's starting code) runs every gate command and every observe entry, `ask:` gates and reviews included; failures -are logged but reject nothing, and metric gates aren't checked. A gate, entry -or judge that modifies the code it checks stops the run with a setup error. A -metric from a `command:` entry that is missing at the baseline stops the run -too (there would be no reference). A metric from a `review:` entry stops it +are logged but reject nothing (the agent may be meant to make a gate pass), and +metric gates aren't checked. A setup that can't work stops the run at the +baseline with a setup error naming it: a gate or entry that modifies the code +it checks; a command gate that exits 126 or 127 (not executable, not found), +unless its first word is a file the agent may write and git doesn't ignore (it may create it; only +the first word counts, so name such a script `./tests/new.sh`, not +`bash tests/new.sh`); an +`ask:` gate that exits 2 (no answer: its judge changed files, or its calls +failed). A metric from a `command:` entry that is missing at the baseline stops +the run too (there would be no reference). A metric from a `review:` entry stops it only if a gate uses it; otherwise it is a warning (an LLM answer missing once may be flakiness, not setup). @@ -493,8 +499,10 @@ config error. Changes outside the scope are discarded when the agent's copy is frozen, before any gate runs, so gates check exactly the tree that would be accepted. Nothing -is written back into the agent's copy. Discarded paths are recorded with the -iteration (`discarded` in history, the frozen ones also in `discarded_frozen`), +is written back into the agent's copy, and an out-of-scope file is never stored +in your repository's objects. Discarded paths are recorded with the +iteration (`discarded` in history, the first 20, frozen ones first; `discarded_more` counts the +rest; the frozen ones also in `discarded_frozen`), shown in the console, `view` and the viewer, and the next agent is told ("Your changes to tests/x.py were discarded: outside the editable scope", or "...: frozen" for frozen paths). A rejected attempt whose changes were all discarded @@ -564,9 +572,9 @@ model when the CLI's default does. | Models | [OpenCode models](https://opencode.ai/docs/models/) | The executable is never in the config: set the variable (a wrapper script, a -Bedrock or proxy launcher) where you run `autohelix`. `run` checks before -starting that every agent the config runs (the main agent, each `ask:` and -`review:` entry's judge) can be found; `ask`, `review` and bare `autohelix` use +Bedrock or proxy launcher) where you run `autohelix`. `run` and every `resume` +check before starting that every agent the config runs (the main agent, each +`ask:` and `review:` entry's judge) can be found; `ask`, `review` and bare `autohelix` use the same variables. A `resume` whose agent executable differs from the one the run's last segment started warns ("The agent now starts …"). @@ -590,10 +598,11 @@ hints), OpenCode through a plugin. Every agent can run `prompt_template:` is optional: a [Jinja2](https://jinja.palletsprojects.com/) file that replaces the built-in agent prompt, as a path relative to the config -file (so it lives beside it). A template that doesn't parse is a config -error naming the file and line, and one that fails to render (say `{{ -last.gates.x.y }}`) stops the run with an error naming the file, before its -agent call. A run stores the template's text with its config when it starts, so +file (so it lives beside it). These are config errors naming the file, so +`run --check` finds them: a template that doesn't parse (with its line), one +naming a variable the prompt doesn't have, or the old `.autohelix/` paths in the +agent's copy, and one that fails to render (say `{{ last.gates.x.y }}`) against +a sample history: a baseline, an accepted iteration and a rejected one. A run stores the template's text with its config when it starts, so editing the template changes later runs, not this one. Most configs need only `goal:`. The variables a template gets are a documented contract; see diff --git a/docs/docker.md b/docs/docker.md index 2118f40e..c94a5f91 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -5,7 +5,7 @@ Run AutoHelix inside a Docker container for filesystem isolation. The agent can' ## Quick start ```bash -# 1. Build the image (one-time, takes a few minutes) +# 1. Build the image, from an AutoHelix source checkout (one-time, takes a few minutes) bash docker/build.sh # 2. Create an env script with your credentials @@ -15,14 +15,14 @@ EOF # 3. Run from your project directory cd my-project -docker/run.sh --env ~/autohelix-env.sh run -n 10 # or: run perf -n 10 for autohelix/perf/config.yaml +/path/to/AutoHelix/docker/run.sh --env ~/autohelix-env.sh run -n 10 # or: run perf -n 10 for autohelix/perf/config.yaml ``` All autohelix commands work: `run`, `resume`, `report`, `view --terminal`. Tip: set up an alias to avoid repeating the env path: ```bash -alias autohelix-docker='path/to/docker/run.sh --env ~/autohelix-env.sh' +alias autohelix-docker='/path/to/AutoHelix/docker/run.sh --env ~/autohelix-env.sh' autohelix-docker run -n 10 ``` diff --git a/docs/phases.md b/docs/phases.md index 6c18df2c..2e67bc0d 100644 --- a/docs/phases.md +++ b/docs/phases.md @@ -191,7 +191,7 @@ latest iteration: how to report it). The copy holds its code. - **After a rejection:** the rejected attempt's gate results (passed, failed, or not reached; a failing gate with the folder holding its whole output), the - failure output, the observations it produced before being rejected, and + failure output (the last 15 lines, each cut at 500 characters), the observations it produced before being rejected, and `.autohelix-iteration/rejected.patch` (for a change over 2 MiB, the `git diff` command that shows it instead). The copy is still the last accepted code, and the prompt names the folder of the last accepted iteration too. diff --git a/examples/algotune/collect.py b/examples/algotune/collect.py index 3fee127c..4645068f 100644 --- a/examples/algotune/collect.py +++ b/examples/algotune/collect.py @@ -74,10 +74,10 @@ def autohelix_runs(folder): "summary": r.get("summary"), }) run = json.load(open(os.path.join(run_dir, "run.json"))) - base = run.get("base") + base = run.get("base_commit") # where the run started (rescore: a no-op accept's code) for it in iterations: - if it["commit"]: - files = git(project, "diff", "--name-only", base or it["commit"] + "~", it["commit"]) + if it["commit"]: # this iteration's files, not everything since the base + files = git(project, "diff", "--name-only", it["commit"] + "~", it["commit"]) it["files"] = files.split("\n") if files else [] summary_cost = 0.0 for f in glob.glob(os.path.join(run_dir, ".internal/usage/summary.jsonl")): diff --git a/examples/autoresearch/arms/autohelix/launch.sh b/examples/autoresearch/arms/autohelix/launch.sh index 00736a37..cbcdc0f4 100755 --- a/examples/autoresearch/arms/autohelix/launch.sh +++ b/examples/autoresearch/arms/autohelix/launch.sh @@ -6,7 +6,9 @@ # # RUN ARGS default to `-n 60 --time 24h`. The run's state is in projects/ar-NAME/.autohelix/ # (collect.py and rescore.py read it there), its console output in arms/runs/NAME/console.log. -# Stop it politely with `docker exec -u agent -w PROJECT ar-NAME autohelix stop`. +# Stop it politely (after its current iteration) with +# `docker exec -u agent -w PROJECT ar-NAME sh -c 'autohelix stop "$(ls .autohelix/runs | tail -1)"'` +# (`stop` needs the run's id; the header names it too). set -euo pipefail ARMS=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) name=$1 gpus=$2 diff --git a/examples/autoresearch/arms/container.sh b/examples/autoresearch/arms/container.sh index 0df63028..c9f60b6c 100644 --- a/examples/autoresearch/arms/container.sh +++ b/examples/autoresearch/arms/container.sh @@ -41,7 +41,7 @@ state=$ARMS/runs/$name . "$LOCAL/projects/autoresearch/ar/paths.sh" # AR_VENV, AR_PYTHON_HOME, AR_HF_HOME, AR_DATA, AR_TOKENIZER claude=$(readlink -f "$LOCAL/claude-home/.local/bin/claude") autohelix=$LOCAL/autohelix-venv -model=us.anthropic.claude-opus-5-5 # as template/autohelix/autoresearch/config.yaml's agent.model +model=us.anthropic.claude-opus-5-5 # every arm's (ANTHROPIC_MODEL; the AutoHelix arm's config names none) die() { echo "container: $*" >&2; exit 2; } [ -d "$project/.git" ] || die "no project $project: run arms/reset_projects.sh ar-$name" diff --git a/examples/autoresearch/arms/container/entrypoint.sh b/examples/autoresearch/arms/container/entrypoint.sh index ed8a058f..4866c842 100644 --- a/examples/autoresearch/arms/container/entrypoint.sh +++ b/examples/autoresearch/arms/container/entrypoint.sh @@ -15,7 +15,8 @@ # console.log (autohelix), or session.jsonl (the stream), session.err, session-end.json # (exit code: 124 for the AR_WALL cap) and transcript.jsonl (Claude Code's own record). # The session gets the flags AutoHelix's backend uses (stream-json with partial messages, -# --dangerously-skip-permissions, model and effort of template/autohelix/autoresearch/config.yaml) plus +# --dangerously-skip-permissions, the effort of template/autohelix/autoresearch/config.yaml, the +# model from ANTHROPIC_MODEL, which the AutoHelix arm's Claude Code reads too) plus # --max-budget-usd AR_MAX_BUDGET_USD, under `timeout AR_WALL`. # 4. Kills whatever the agent's user left running. Then the container ends. set -uo pipefail diff --git a/examples/autoresearch/setup.py b/examples/autoresearch/setup.py index 48196152..f42bede2 100644 --- a/examples/autoresearch/setup.py +++ b/examples/autoresearch/setup.py @@ -102,6 +102,10 @@ def prepare_data(local): def lay_out(project, local): + if (project / "ar" / "paths.sh").exists() and subprocess.run( + ["git", "-C", project, "rev-parse", "-q", "--verify", "HEAD"], capture_output=True).returncode == 0: + print(f"project: {project} exists") # laid out and committed by an earlier run of this script + return if project.exists() and any(project.iterdir()): sys.exit(f"setup: {project} exists and isn't empty") shutil.copytree(HERE / "template", project, dirs_exist_ok=True, @@ -121,7 +125,8 @@ def lay_out(project, local): (project / ".gitignore").write_text("__pycache__/\n") run("git", "init", "-q", project) run("git", "-C", project, "add", "-A") - run("git", "-C", project, "commit", "-q", "-m", "autoresearch at upstream 228791f, patched") + run("git", "-C", project, "-c", "user.name=AutoHelix", "-c", "user.email=autohelix@localhost", + "-c", "commit.gpgsign=false", "commit", "-q", "-m", "autoresearch at upstream 228791f, patched") def heldout_shard(folder): diff --git a/examples/autoresearch/template/autohelix/autoresearch/config.yaml b/examples/autoresearch/template/autohelix/autoresearch/config.yaml index 73a46577..456aa03a 100644 --- a/examples/autoresearch/template/autohelix/autoresearch/config.yaml +++ b/examples/autoresearch/template/autohelix/autoresearch/config.yaml @@ -39,7 +39,8 @@ goal: | agent: cli: claude-code - model: us.anthropic.claude-opus-5-5 # Bedrock id; pin a model for a result + # No model: Claude Code's own. The arms pin one model for every arm (arms/container.sh's + # ANTHROPIC_MODEL, a Bedrock id). effort: high timeout: 30m diff --git a/examples/kernelbench/setup.py b/examples/kernelbench/setup.py index 0df09250..024cf82e 100644 --- a/examples/kernelbench/setup.py +++ b/examples/kernelbench/setup.py @@ -47,10 +47,13 @@ def git_init(directory: Path) -> None: + # Its own identity: a fresh GPU box or container often has none, and the commit + # would fail after the project was written. subprocess.run(["git", "init", "-q"], cwd=directory, check=True) subprocess.run(["git", "add", "-A"], cwd=directory, check=True) subprocess.run( - ["git", "commit", "-q", "-m", "Initial commit"], + ["git", "-c", "user.name=AutoHelix", "-c", "user.email=autohelix@localhost", "-c", "commit.gpgsign=false", + "commit", "-q", "-m", "Initial commit"], cwd=directory, check=True, ) diff --git a/examples/kernelbench/setup.yaml b/examples/kernelbench/setup.yaml index affd8f69..506be41b 100644 --- a/examples/kernelbench/setup.yaml +++ b/examples/kernelbench/setup.yaml @@ -8,4 +8,6 @@ defaults: evaluation_timeout: 1800 correctness_trials: 5 iterations: 5 - agent_model: us.anthropic.claude-opus-4-8 + # The published runs used a Bedrock id, us.anthropic.claude-opus-4-8: set it here + # only with Claude Code set up for Bedrock. + agent_model: opus diff --git a/examples/posttrain/README.md b/examples/posttrain/README.md index 02520c34..2f5377ed 100644 --- a/examples/posttrain/README.md +++ b/examples/posttrain/README.md @@ -44,6 +44,11 @@ posttrain/ committed with the iteration (`.gitignore` ignores the usual training by-products). Either way it isn't where the eval looks. If `$ARTIFACTS` is left at its in-repo default, `check_final_model.sh` fails with an error saying so. +- **One model folder, never rolled back:** a rejected iteration rolls back code only. + Its model stays at `$ARTIFACTS/final_model`, where the next agent continues from it + and the next eval scores it unless that agent retrains. The metric gate rejects the + iteration, not the model. For a model per iteration, see + [ML experiments](../../docs/ml-experiments.md#one-folder-per-iteration). - **The eval's chat template is the base model's,** read from the Hugging Face cache each time (`evaluate.py --chat-template-model`), so the prompt format stays fixed whatever the agent's model ships. It isn't kept in this folder: a copy holds only diff --git a/examples/posttrain/autohelix/posttrain/config.yaml b/examples/posttrain/autohelix/posttrain/config.yaml index 8539d06d..fd2910f2 100644 --- a/examples/posttrain/autohelix/posttrain/config.yaml +++ b/examples/posttrain/autohelix/posttrain/config.yaml @@ -23,8 +23,9 @@ goal: | under `$ARTIFACTS/checkpoints` — absolute paths OUTSIDE this working directory (see `config.sh` for the value of `$ARTIFACTS`). The eval reads exclusively from `$ARTIFACTS/final_model`. - - You may continue training from your best previous checkpoint (see - `$ARTIFACTS/final_model`); iterations are meant to compound. + - You may continue training from the last model saved at `$ARTIFACTS/final_model`, + which may be a rejected iteration's; keep your own best checkpoint under + `$ARTIFACTS/checkpoints`. Iterations are meant to compound. Rules: 1. Operate autonomously — there is no user to ask. diff --git a/scripts/console_screens.py b/scripts/console_screens.py index e0da358c..1ee77b62 100644 --- a/scripts/console_screens.py +++ b/scripts/console_screens.py @@ -219,8 +219,9 @@ def run_in_pty(argv, cwd, env, width, *, keys=(), frame_when=None, timeout=180): return snapshot(screen), live, code -MENU = "(q: quit)" # the last line a menu draws ("Which agent?") +MENU = "(q: quit)" # the last line a menu draws (several agents: "Start an agent with AutoHelix:") QUESTION = "Enter/q" # the entry screen's one question +ENTRY_TITLE = "Start an agent with AutoHelix:" # its menu with several agents (`cli.ENTRY_TITLE`) def showing(*texts: str): @@ -364,13 +365,12 @@ def mid_iteration_3(text): # The same, Enter: the first option starts the (fake) agent with its first prompt. final, _, code = run_in_pty([*cli], project, env, width, keys=[(QUESTION, b"\r")], timeout=30) record(f"entry-ask-{width}", final, width, f"autohelix · runs, Enter · {width} cols", code) - # Two agents: the labels say "an agent", then "Which agent?"; q there quits. + # Two agents: one menu of them (`cli.ENTRY_TITLE`); q there quits. two = environment(root, width, ("claude", "codex")) - _, live, code = run_in_pty([*cli], project, two, width, - keys=[(MENU, b"\x1b[B"), (0.5, b"\r"), ("Which agent?", b"q")], - frame_when=showing("Which agent?", MENU), timeout=30) + _, live, code = run_in_pty([*cli], project, two, width, keys=[(MENU, b"q")], + frame_when=showing(ENTRY_TITLE, MENU), timeout=30) record(f"entry-agents-{width}", live or [], width, - f"autohelix · two agents, ↓ Enter (then q) · {width} cols", code) + f"autohelix · two agents (then q) · {width} cols", code) configs = make_project(root, "half-done", True) # autohelix/sorting/config.yaml, no runs yet _, live, code = run_in_pty([*cli], configs, env, width, keys=[(QUESTION, b"q")], diff --git a/src/autohelix/__init__.py b/src/autohelix/__init__.py index abf2f291..94c40dd1 100644 --- a/src/autohelix/__init__.py +++ b/src/autohelix/__init__.py @@ -6,6 +6,7 @@ from autohelix.config import Config, ConfigIssue, load_config from autohelix.harness import Harness from autohelix.history import History +from autohelix.terminal import version as _version -__version__ = "0.2.0" +__version__ = _version() # the installed package's (pyproject.toml), never written twice __all__ = ["Config", "ConfigIssue", "load_config", "Harness", "History"] diff --git a/src/autohelix/agents/__init__.py b/src/autohelix/agents/__init__.py index bef5fcaf..46ae657e 100644 --- a/src/autohelix/agents/__init__.py +++ b/src/autohelix/agents/__init__.py @@ -139,7 +139,7 @@ class AgentRunResult: usage: dict[str, Any] = field(default_factory=dict) final_text: str | None = None # the agent's last message structured_output: Any = None # schema-constrained answer, where the backend supports it - # A failed call's infrastructure failure (credentials, the model service), as a short + # A failed call's infrastructure failure (rejected credentials, 401/403), as a short # reason (`infrastructure_reason`), from the CLI's specific signals only; None for # anything else. The harness ends the segment on one. infrastructure: str | None = None @@ -150,14 +150,13 @@ class AgentRunResult: def infrastructure_reason(status: Any) -> str | None: """An HTTP status a CLI reported for a failed model call, as an infrastructure - failure: 401/403 `authentication failed (HTTP 403)`, 429 and 5xx `model service - error (HTTP 503)`. None for anything else (an ordinary failure).""" + failure: only 401/403, `authentication failed (HTTP 403)`, which no retry fixes. + None for anything else, 429 and 5xx included: an ordinary failure, so a short + outage costs an iteration and three in a row still end the run.""" if not isinstance(status, int) or isinstance(status, bool): return None if status in (401, 403): return f"authentication failed (HTTP {status})" - if status == 429 or 500 <= status <= 599: - return f"model service error (HTTP {status})" return None diff --git a/src/autohelix/agents/claudecode.py b/src/autohelix/agents/claudecode.py index 2f6c5428..b217f6bd 100644 --- a/src/autohelix/agents/claudecode.py +++ b/src/autohelix/agents/claudecode.py @@ -11,7 +11,7 @@ AgentConfig, AgentEvent, AgentEventKind, AgentRunResult, EventCallback, call_fields, command_path, infrastructure_reason, ) -from autohelix.agents.runner import format_timeout_seconds, run_process +from autohelix.agents.runner import run_process, timeout_error from autohelix.sandbox import build_copy_env @@ -165,6 +165,9 @@ def _handle_line(self, line: str, event_callback: EventCallback, *, replay: bool except json.JSONDecodeError: self._emit(event_callback, AgentEventKind.RAW, line) return + if not isinstance(payload, dict): # `0`, `[1]` on stderr (a wrapper's): output, not an event + self._emit(event_callback, AgentEventKind.RAW, line) + return event_type = payload.get("type") @@ -288,7 +291,7 @@ def _handle_line(self, line: str, event_callback: EventCallback, *, replay: bool self._result_error = str( payload.get("result") or f"Claude Code returned {subtype}" ) - # Credentials or the model service (401/403, 429/5xx), as the CLI reports + # Rejected credentials (401/403; `infrastructure_reason`), as the CLI reports # them; an earlier `completed` result doesn't change it: the call failed. # The last failed result decides. self._infrastructure = None @@ -389,7 +392,7 @@ def run( event_callback( AgentEvent( kind=AgentEventKind.WARNING, - text=f"Agent {format_timeout_seconds(self.config.timeout)}", + text=f"Agent {timeout_error(self.config.timeout)}", ) ) @@ -400,7 +403,7 @@ def run( error = self._result_error if result.timed_out: - error = format_timeout_seconds(self.config.timeout) + error = timeout_error(self.config.timeout) elif result.exit_code != 0 and error is None: error = f"Claude Code exited with status {result.exit_code}" diff --git a/src/autohelix/agents/codex.py b/src/autohelix/agents/codex.py index ba43e6e3..0f50f5aa 100644 --- a/src/autohelix/agents/codex.py +++ b/src/autohelix/agents/codex.py @@ -15,7 +15,7 @@ infrastructure_reason, ) from autohelix.agents.codex_cost import TOKEN_FIELDS, estimate_cost -from autohelix.agents.runner import format_timeout_seconds, run_process +from autohelix.agents.runner import run_process, timeout_error from autohelix.sandbox import build_copy_env @@ -270,13 +270,13 @@ def run( event_callback( AgentEvent( kind=AgentEventKind.WARNING, - text=f"Agent {format_timeout_seconds(self.config.timeout)}", + text=f"Agent {timeout_error(self.config.timeout)}", ) ) error = self._turn_error if result.timed_out: - error = format_timeout_seconds(self.config.timeout) + error = timeout_error(self.config.timeout) elif result.exit_code != 0 and error is None: error = f"Codex exited with status {result.exit_code}" diff --git a/src/autohelix/agents/opencode.py b/src/autohelix/agents/opencode.py index 17ea288a..4fd46662 100644 --- a/src/autohelix/agents/opencode.py +++ b/src/autohelix/agents/opencode.py @@ -10,7 +10,7 @@ AgentConfig, AgentEvent, AgentEventKind, AgentRunResult, EventCallback, call_fields, command_path, infrastructure_reason, ) -from autohelix.agents.runner import format_timeout_seconds, run_process +from autohelix.agents.runner import run_process, timeout_error from autohelix.sandbox import build_copy_env @@ -61,6 +61,9 @@ def _handle_line(self, line: str, event_callback: EventCallback) -> None: except json.JSONDecodeError: self._emit(event_callback, AgentEventKind.RAW, line) return + if not isinstance(payload, dict): # `0`, `[1]` on stderr (a wrapper's): output, not an event + self._emit(event_callback, AgentEventKind.RAW, line) + return event_type = payload.get("type") part = payload.get("part", {}) @@ -95,8 +98,7 @@ def _handle_line(self, line: str, event_callback: EventCallback) -> None: data = error.get("data") if isinstance(error.get("data"), dict) else {} message = data.get("message") or error.get("message") or error.get("name") or "OpenCode reported an error" self._error = str(message) - # 401/403 seen for real (an invalid key); 429/5xx not yet: an error event is - # assumed to come after OpenCode's own retries (`isRetryable` aside). + # 401/403 seen for real (an invalid key): the only statuses that stop a run. self._infrastructure = infrastructure_reason(data.get("statusCode")) self._emit(event_callback, AgentEventKind.ERROR, self._error) return @@ -159,7 +161,7 @@ def run( error = None if result.timed_out: - error = format_timeout_seconds(self.config.timeout) + error = timeout_error(self.config.timeout) event_callback(AgentEvent(kind=AgentEventKind.WARNING, text=f"Agent {error}")) # Its finished steps' costs only: the call's cost is unknown (kept apart). if "cost_usd" in self._usage: diff --git a/src/autohelix/agents/runner.py b/src/autohelix/agents/runner.py index 31b6a1e5..37d0c147 100644 --- a/src/autohelix/agents/runner.py +++ b/src/autohelix/agents/runner.py @@ -15,6 +15,8 @@ from pathlib import Path from typing import Callable +from autohelix.iteration_time import format_limit + @dataclass class ProcessRunResult: @@ -49,30 +51,19 @@ def child_signals(): signal.signal(signum, signal.SIG_IGN) -def format_timeout_seconds(timeout_seconds: int | None) -> str: - """Render a timeout value as natural language.""" - if timeout_seconds is None: - return "timed out" - - remaining = int(timeout_seconds) - hours, remainder = divmod(remaining, 3600) - minutes, seconds = divmod(remainder, 60) - parts: list[str] = [] - if hours: - parts.append(f"{hours} hour" if hours == 1 else f"{hours} hours") - if minutes: - parts.append(f"{minutes} minute" if minutes == 1 else f"{minutes} minutes") - if seconds or not parts: - parts.append(f"{seconds} second" if seconds == 1 else f"{seconds} seconds") - return f"timed out after {' '.join(parts)}" +def timeout_error(timeout_seconds: int | None) -> str: + """A timed-out call's error, worded as a timed-out command's: `timed out after 30m`.""" + return "timed out" if timeout_seconds is None else f"timed out after {format_limit(int(timeout_seconds))}" def _kill_process_group(process: subprocess.Popen, grace: float = 3) -> None: - """Kill a process and its entire process group (SIGTERM, then SIGKILL after `grace` s).""" + """Kill a process and its entire process group (SIGTERM, then SIGKILL after `grace` s). + The group is the process's own (`start_new_session`): its id is the process's pid, + also when the process exits right after the `poll` (where `getpgid` would raise).""" if process.poll() is not None: return - pgid = os.getpgid(process.pid) + pgid = process.pid try: os.killpg(pgid, signal.SIGTERM) @@ -204,7 +195,9 @@ def run_process( # outlive a normal exit either. end_group(process) return ProcessRunResult(exit_code=exit_code) - except KeyboardInterrupt: + except BaseException: + # Ctrl-C, or anything raised while the agent runs (a line callback, a full disk + # writing the log): the agent must not go on working, unbounded, without the loop. if process is not None: _kill_process_group(process) end_group(process) diff --git a/src/autohelix/checks.py b/src/autohelix/checks.py index 1c2ca034..88c5bd62 100644 --- a/src/autohelix/checks.py +++ b/src/autohelix/checks.py @@ -17,8 +17,6 @@ from dataclasses import dataclass from pathlib import Path -logger = logging.getLogger(__name__) - from autohelix.agents.runner import _kill_process_group, child_signals, end_group from autohelix.agents import command_path from autohelix.config import (CONFIG_DIR, CONFIG_FILE, DEFAULT_CHECK_TIMEOUT, CommandSpec, Config, ConfigError, MetricGate, @@ -27,7 +25,7 @@ from autohelix.sandbox import build_copy_env from autohelix.workspace import git_env, path_in_scope, run_git -# Progress callback type: (phase, command, elapsed_seconds | None) +logger = logging.getLogger(__name__) @dataclass @@ -61,24 +59,8 @@ def preflight_check(config: Config, project_path: Path) -> list[PreflightIssue]: for ci in config_issues: issues.append(PreflightIssue(level=ci.level, message=ci.message)) - # 2. Every agent the config runs (main agent, `ask:` and `review:` judges) can start: - # its executable resolved as the backend resolves it (mock is built in; a variable - # that is gone raises ConfigError there, reported as the config errors are). - from autohelix.agents import CLI_NAMES, command_variable - - missing: dict[str, list[str]] = {} - for who, cli in config.agent_commands(): - if cli in CLI_NAMES and not shutil.which(path := command_path(cli)): - missing.setdefault(f"{cli}\0{path}", []).append(who) - for key, whos in missing.items(): - cli, path = key.split("\0") - users = "" if whos == ["agent"] else " (used by " + ", ".join( - "the agent" if who == "agent" else f"`{who}`" for who in whos) + ")" - issues.append(PreflightIssue( - level="error", - message=(f"Agent command '{path}' not found in PATH{users}; install {CLI_NAMES[cli]}, or set " - f"{command_variable(cli)}"), - )) + # 2. Every agent the config runs can start. + issues.extend(agent_issues(config)) # 3. Scope patterns that match no committed file, with the matcher the harness uses # (no scope at all: `scope_warning`, at run start). Editable ones may name files the @@ -102,6 +84,30 @@ def preflight_check(config: Config, project_path: Path) -> list[PreflightIssue]: return issues +def agent_issues(config: Config) -> list[PreflightIssue]: + """Preflight's errors for agents the config runs (main agent, `ask:` and `review:` + judges) that can't start: its executable resolved as the backend resolves it (mock is + built in; a variable that is gone raises ConfigError there, reported as the config + errors are). Checked at every segment start: a resume on another shell or machine.""" + from autohelix.agents import CLI_NAMES, command_variable + + issues: list[PreflightIssue] = [] + missing: dict[str, list[str]] = {} + for who, cli in config.agent_commands(): + if cli in CLI_NAMES and not shutil.which(path := command_path(cli)): + missing.setdefault(f"{cli}\0{path}", []).append(who) + for key, whos in missing.items(): + cli, path = key.split("\0") + users = "" if whos == ["agent"] else " (used by " + ", ".join( + "the agent" if who == "agent" else f"`{who}`" for who in whos) + ")" + issues.append(PreflightIssue( + level="error", + message=(f"Agent command '{path}' not found in PATH{users}; install {CLI_NAMES[cli]}, or set " + f"{command_variable(cli)}"), + )) + return issues + + # A path under autohelix/ in a command's text, `./` allowed in front: not part of a longer # path (`src/autohelix/`, `$AUTOHELIX_PROJECT/autohelix/`, `.autohelix/`), up to a space, # quote or shell operator. The group is the path without the `./`. @@ -264,9 +270,15 @@ def _execute(command: str, cwd: Path, timeout: int, env: dict[str, str]) -> _Exe ) while True: try: - stdout, stderr = proc.communicate(timeout=2.0) + stdout, stderr = proc.communicate(timeout=0.5) break except subprocess.TimeoutExpired: + if proc.poll() is not None: + # The shell has exited, but a background child still holds its output: + # the command has ended, so its group goes, and so does the wait. + end_group(proc) + stdout, stderr = _drain(proc) + return _Execution(proc.returncode, stdout, stderr, duration_s=time.monotonic() - start) elapsed = time.monotonic() - start if elapsed > timeout: # Kill the whole process group, not just the /bin/sh wrapper, diff --git a/src/autohelix/cli.py b/src/autohelix/cli.py index a09ab39c..58d68b95 100644 --- a/src/autohelix/cli.py +++ b/src/autohelix/cli.py @@ -3,6 +3,7 @@ """Command-line interface.""" +import errno import functools import json import os @@ -101,16 +102,17 @@ def _warn(message: str, err: bool = False) -> None: terminal.warn(Console(stderr=err), message) -def _chosen_run(project: Path, value: str | None) -> RunPaths: +def _chosen_run(project: Path, value: str | None, running: bool = True) -> RunPaths: """The run a command acts on: `value` (an id or its last part), else `runs.default_run`'s - (the running run, else the most recently active one that isn't archived), named.""" + (the running run, else the most recently active one that isn't archived; without + `running`, one that isn't running), named.""" if value is not None: return RunPaths(project, _run_id(project, value)) try: - paths, _, why = default_run(project) + paths, _, why = default_run(project, running) except RuntimeError as error: raise click.ClickException(str(error)) from error - click.echo(click.style(f"Run {short_id(paths.run_id)} (the {why} run; name one to choose another)", dim=True), + click.echo(click.style(f"Run {short_id(paths.run_id)} (the {why}; name one to choose another)", dim=True), err=True) return paths @@ -442,13 +444,11 @@ def _git_project(path: Path) -> Path: def _ancestor_configs(project: Path) -> str: """For a project without a config: the nearest folder above it, up to the top of - its repository, that has one (`run` from src/ by mistake).""" - top = subprocess.run(["git", "rev-parse", "--show-toplevel"], cwd=project, capture_output=True, text=True) - if top.returncode: - return "" - top_path = Path(top.stdout.strip()).resolve() - for folder in project.parents: - if not folder.is_relative_to(top_path): + its checkout (`_checkout_top`), that has one (`run` from src/ by mistake). Still + used: 06-3's subfolder lookup that would replace it is for later.""" + top = _checkout_top(project) + for folder in project.parents if top is not None else (): + if not folder.is_relative_to(top): break if configs := project_configs(folder): return f" {folder} has {', '.join(configs)}; run from there or pass -p {folder}." @@ -614,9 +614,9 @@ def _last_iteration(project: Path, config: Path | None, run_id: str | None) -> i written; -1 when there is none to read (`_start` then refuses as usual).""" try: planned = planned_run(project, config, run_id=run_id, create=False) - except (RuntimeError, ValueError): + return History(project, planned.run_id).get_last_iteration() if planned else -1 + except (RuntimeError, ValueError): # `_start` refuses as usual (a damaged history: as `resume` says it) return -1 - return History(project, planned.run_id).get_last_iteration() if planned else -1 def _segment(harness: Harness, budget: Budget, report: bool) -> None: @@ -644,7 +644,8 @@ def _segment(harness: Harness, budget: Budget, report: bool) -> None: "(landing defaults to manual).") @click.option("--import", "import_run", metavar="RUN_ID", help="Continue from another run: its notes and history (read-only) in every iteration, its last " - "observe outputs at the baseline. Code still comes from your checkout.") + "observe outputs until each entry succeeds here (normally the baseline). Code still comes from " + "your checkout.") @click.option("--why", help="Why this run is started (one line, shown by `autohelix view`).") @click.option("--check", is_flag=True, help="Only make the checks a run makes before it writes anything (config, prompt template, " @@ -676,10 +677,11 @@ def run(config_name: str | None, path: Path, verbose: bool, no_report: bool, lan With --import RUN_ID (or its last part), the new run continues from that one: its agents see its run.json, history and notes (read-only, in - .autohelix-iteration/runs//) and its code's ref, and the baseline's - observe entries get its last outputs as $AUTOHELIX_PREVIOUS. Your notes, - budgets, metric reference and group are this run's own. To fork from the - run's code, `git checkout autohelix/` first. + .autohelix-iteration/runs//) and its code's ref, and each observe entry + gets its last output as $AUTOHELIX_PREVIOUS until the entry succeeds here + (normally the baseline). Your notes, budgets, metric reference and group are + this run's own. To fork from the run's code, start a branch at it first + (`git switch -c autohelix/`). With --check, nothing is started or written: the command makes every check the run would make before writing anything, prints what it finds, and exits @@ -695,7 +697,10 @@ def run(config_name: str | None, path: Path, verbose: bool, no_report: bool, lan group=group or None, import_run=imported, why=why, check_only=check) if check: shown = config_relative(project, config) - click.echo(f"OK: {shown} is ready; `{run_command(shown)}` would start a new run.") + flags = "".join(f" {flag} {shlex.quote(value)}" for flag, value in + (("--import", imported and short_id(imported)), ("--group", group), ("--land", land_mode)) + if value) + click.echo(f"OK: {shown} is ready; `{run_command(shown)}{flags}` would start a new run.") return _segment(harness, budget, not no_report) @@ -780,13 +785,13 @@ def resume(target: str | None, path: Path, verbose: bool, no_report: bool, land_ @click.option("--into", help="Target branch, required for runs created detached.") def land(run_id: str | None, path: Path, into: str | None): """Fast-forward a target branch to a run's accepted code (RUN_ID or its last part, else - the running run, else the most recently active one).""" - paths = _chosen_run(_project(path), run_id) + the most recently active run that isn't running or archived).""" + paths = _chosen_run(_project(path), run_id, running=False) try: with RunLock(paths.lock): data = paths.read_identity() - land_run(paths, data, run_tip(paths, data), into) - click.echo(f"Landed {short_id(paths.run_id)}.") + unchanged = land_run(paths, data, run_tip(paths, data), into) + click.echo(unchanged or f"Landed {short_id(paths.run_id)}.") except RuntimeError as e: raise click.ClickException(str(e)) from e @@ -1228,6 +1233,10 @@ def _serve(project: Path, port: int | None, open_browser: bool, page: str) -> No try: server = make_server(project, port) except OSError as exc: + if exc.errno == errno.EADDRINUSE: # one server serves every run of its project + raise click.ClickException( + f"Port {port} is in use (another `autohelix view`?). If it serves this project, open " + f"http://127.0.0.1:{port}{page} there; else pass --port 0 (any free port).") from exc raise click.ClickException(f"Cannot listen on port {port}: {exc}") from exc url = f"http://127.0.0.1:{server.server_port}{page}" click.echo(f"Viewing {project.resolve().name} at {url} (Ctrl-C to stop)") @@ -1246,7 +1255,8 @@ def _serve(project: Path, port: int | None, open_browser: bool, page: str) -> No @click.argument("run_id", required=False) @_path_option() def report(run_id: str | None, path: Path): - """Write (or rewrite) a run's summary (RUN_ID or its last part, else the running or latest run). + """Write (or rewrite) a run's summary (RUN_ID or its last part, else the most recently + active run that isn't running or archived). One agent call reads the run's history, notes, reviews, logs and commits, and writes the selected run's report.md. `run` and `resume` do this automatically when a run @@ -1259,9 +1269,13 @@ def report(run_id: str | None, path: Path): console = Console() project_path = _project(path) - paths = _chosen_run(project_path, run_id) + paths = _chosen_run(project_path, run_id, running=False) run_id = paths.run_id - if History(project_path, run_id).get_last_iteration() == 0: + try: + last = History(project_path, run_id).get_last_iteration() + except RuntimeError as e: # a damaged history + raise click.ClickException(str(e)) from e + if last == 0: _warn(f"Run {short_id(run_id)} has no iterations yet. Nothing to report.") raise SystemExit(1) from rich.text import Text diff --git a/src/autohelix/config.py b/src/autohelix/config.py index 4889c321..ff7b1afa 100644 --- a/src/autohelix/config.py +++ b/src/autohelix/config.py @@ -5,6 +5,7 @@ from dataclasses import dataclass, field from pathlib import Path, PurePath, PurePosixPath +import dataclasses import glob as globmod import math import os @@ -852,9 +853,32 @@ def config_changes(stored: Config, current: Config) -> list[str]: """The settings in which two parsed configs differ, as the config names them: what the harness uses, so formatting, comments and other spellings of the same value (`600` and `10m`, `- pytest` and `- command: pytest`, a default written out) don't - count. `prompt_template` also differs when the templates' texts do (`template_text`; - ConfigError when one can't be read).""" - changed = [name for attr, name in _COMPARED if getattr(stored, attr) != getattr(current, attr)] + count. Named one level down (`_detail`): `agent.timeout`, `gates entry 2`, `observe + bench (added)`. `prompt_template` also differs when the templates' texts do + (`template_text`; ConfigError when one can't be read).""" + changed = [part for attr, name in _COMPARED if getattr(stored, attr) != getattr(current, attr) + for part in _detail(name, getattr(stored, attr), getattr(current, attr))] if "prompt_template" not in changed and template_text(stored) != template_text(current): changed.append("prompt_template") return changed + + +def _detail(name: str, old, new) -> list[str]: + """Where one differing setting differs: the agent's fields (`agent.timeout`), list + entries by position (`gates entry 2`, `stop entry 1 (added)`), observe entries by + name (`observe bench`, `(added)`, `(removed)`; `observe (order)`); else `name`.""" + if name == "agent": + fields = [f.name for f in dataclasses.fields(old) if getattr(old, f.name) != getattr(new, f.name)] + return [f"agent.{field}" for field in fields] or [name] + if name == "observe": + before, after = {e.name: e for e in old}, {e.name: e for e in new} + parts = [f"observe {entry}" + ("" if entry in before and entry in after else + " (added)" if entry in after else " (removed)") + for entry in [*before, *(e for e in after if e not in before)] + if before.get(entry) != after.get(entry)] + return parts or ["observe (order)"] + if name in ("gates", "stop"): + return [f"{name} entry {k}" + (" (added)" if k > len(old) else " (removed)" if k > len(new) else "") + for k in range(1, max(len(old), len(new)) + 1) + if old[k - 1:k] != new[k - 1:k]] or [name] + return [name] diff --git a/src/autohelix/events.py b/src/autohelix/events.py index 76e4ddeb..04116a9e 100644 --- a/src/autohelix/events.py +++ b/src/autohelix/events.py @@ -135,8 +135,6 @@ def encode_cursor(marks: dict[str, Marks]) -> str: def decode_cursor(cursor: str) -> dict[str, Marks]: """The marks a cursor holds; ValueError if it isn't one.""" version, _, body = cursor.strip().partition(".") - if version == "1" and body: - raise ValueError("a cursor of an older AutoHelix: start again with `autohelix wait` (no --after)") if version != CURSOR_VERSION or not body: raise ValueError(_NOT_A_CURSOR) try: diff --git a/src/autohelix/experiment.py b/src/autohelix/experiment.py index f9ee460a..446417ac 100644 --- a/src/autohelix/experiment.py +++ b/src/autohelix/experiment.py @@ -235,15 +235,16 @@ def sweep_staging(beside: Path) -> None: shutil.rmtree(path, ignore_errors=True) -def snapshot_changes(config: Config, project: Path, stored: Path) -> str | None: - """How the live experiment folder differs from a run's snapshot (`stored`), as - words: the files changed (bytes or exec bit), added and removed, or why the folder - can no longer be stored (a file that can't be read too); None when they match. - Compared file by file: the snapshot is the manifest.""" +def snapshot_changes(config: Config, project: Path, stored: Path) -> tuple[str, set[str]] | None: + """How the live experiment folder differs from a run's snapshot (`stored`): words + naming the files changed (bytes or exec bit), added and removed, or why the folder + can no longer be stored (a file that can't be read too), and which of `changed`, + `added`, `removed` there are (none for a folder that can't be stored); None when + they match. Compared file by file: the snapshot is the manifest.""" try: live = {file.name: file for file in snapshot_files(config, project)} except ConfigError as e: - return f"it can no longer be stored: {e}" + return f"it can no longer be stored: {e}", set() kept = {path.relative_to(stored).as_posix(): path for path in stored.rglob("*") if path.is_file() and not path.is_symlink()} changed = [] @@ -254,8 +255,10 @@ def snapshot_changes(config: Config, project: Path, stored: Path) -> str | None: or file.size != copy.stat().st_size or file.source.read_bytes() != copy.read_bytes()): changed.append(name) except OSError as e: # gone or unreadable since the walk - return f"it can no longer be stored: {e.filename or name} can't be read ({e.strerror or e})" - parts = [f"{label}: {', '.join(names)}" for label, names in ( + return f"it can no longer be stored: {e.filename or name} can't be read ({e.strerror or e})", set() + found = {label: names for label, names in ( ("changed", changed), ("added", sorted(live.keys() - kept.keys())), - ("removed", sorted(kept.keys() - live.keys()))) if names] - return "; ".join(parts) or None + ("removed", sorted(kept.keys() - live.keys()))) if names} + if not found: + return None + return "; ".join(f"{label}: {', '.join(names)}" for label, names in found.items()), set(found) diff --git a/src/autohelix/formatting.py b/src/autohelix/formatting.py index 5e91e6cb..22717b37 100644 --- a/src/autohelix/formatting.py +++ b/src/autohelix/formatting.py @@ -65,7 +65,7 @@ def format_cap(cost: float) -> str: def format_total_cost(usages: Iterable[dict]) -> str: - """Describe a total as incomplete when some agent calls have no known cost; an + """A total, `$0.25+` when some agent calls have no known cost (the known part); an unavailable one says why when its calls give one reason (`set agent.model ...`).""" usages = list(usages) total = summarize_costs(usages) @@ -78,4 +78,4 @@ def format_total_cost(usages: Iterable[dict]) -> str: reason = clean(reason, 80).rstrip(".") if reason else "" return f"cost unavailable: {reason}" if reason else "cost unavailable" text = format_cost(total.cost_usd) - return f"{text} (incomplete)" if total.incomplete else text + return f"{text}+" if total.incomplete else text # `+`: the known part, as `terminal.money` diff --git a/src/autohelix/harness.py b/src/autohelix/harness.py index 7a0518e2..44d9a40b 100644 --- a/src/autohelix/harness.py +++ b/src/autohelix/harness.py @@ -9,6 +9,7 @@ import itertools import math import os +import shlex import shutil import signal import subprocess @@ -25,22 +26,22 @@ from rich.text import Text from autohelix.agents import AgentConfig, AgentEvent, AgentEventKind, AgentRunResult, create_agent -from autohelix.config import (Config, ConfigError, MetricGate, config_changes, config_relative, find_config, +from autohelix.config import (CONFIG_DIR, Config, ConfigError, MetricGate, config_changes, config_relative, find_config, load_config, not_an_experiment, run_command) from autohelix.costs import summarize_costs from autohelix import terminal from autohelix.display import LiveDisplay, clean from autohelix.terminal import LiveRow, Row, budget_text -from autohelix.history import History, IterationResult +from autohelix.history import DISCARDED_LISTED, History, IterationResult from autohelix.runs import (RunPaths, RunState, select_run, reconcile, land, git, - claim_copies, critical_section, new_run_name, + claim_copies, critical_section, new_run_name, new_run_notices, iteration_folder, load_run_config, planned_run, remove_copies, require_clean, short_id, landing, Landing, LandingWords, landing_words, WHY_LIMIT, imported_run, is_live, group_landing_note, has_baseline, land_first, target_ahead_refusal, write_json) from autohelix.iteration import IterationWorkspace from autohelix.launcher import command_path -from autohelix.checks import (metric_gate_failure, metric_reference, preflight_check, run_gate_commands, +from autohelix.checks import (agent_issues, metric_gate_failure, metric_reference, preflight_check, run_gate_commands, run_observe_entry, run_stop_checks, scope_warning, StopCheckResult) from autohelix.events import iteration_fields from autohelix.experiment import shown, snapshot_changes, snapshot_files @@ -48,8 +49,7 @@ from autohelix.usage_log import ENV as USAGE_ENV, append_usage, read_usage, superseded_marker from autohelix.formatting import clean_block, format_cap, format_cost, format_duration, format_total_cost from autohelix.iteration_time import format_limit -from autohelix.prompt_template import (build_prompt_variables, load_template, render_template, unknown_variables, - uses_old_layout) +from autohelix.prompt_template import build_prompt_variables, load_template, render_template from autohelix.run_log import RunLog from autohelix.workspace import (path_in_scope, SCRUBBED_GIT_ENV, ATTR_SOURCE_LIMITATION, ITERATION_DIR, OPENCODE_PLUGIN, CandidateRejected, GitExcludeError, Repo, Scope, ensure_git_exclude_entry, @@ -164,8 +164,16 @@ def _call_env(folders: dict) -> dict[str, str]: "AUTOHELIX_EXPERIMENT": str(folders["experiment"]) if "experiment" in folders else None} -def _tail(output: str, lines: int = 15) -> str: - return "\n".join(output.strip().splitlines()[-lines:]) +TAIL_LINES = 15 +TAIL_LINE_CHARS = 500 # so a failure's tail, in the record and the next prompts, stays under 8 KB + + +def _tail(output: str, lines: int = TAIL_LINES) -> str: + """A failed command's last lines for the record and the prompt, each cut at + `TAIL_LINE_CHARS` ("…" where cut): one long line (a JSON dump) can't make the + prompt too large to start the agent. The whole output stays in its stored folder.""" + return "\n".join(line if len(line) <= TAIL_LINE_CHARS else line[:TAIL_LINE_CHARS] + "…" + for line in output.strip().splitlines()[-lines:]) class Harness: @@ -187,8 +195,9 @@ def __init__(self, project_path: Path, verbose: bool = False, heartbeat_seconds: folder (`config.config_name`; `name` replaces that, for library callers and tests). A new run may import another (`import_run`, a full id: `run --import`): every - agent copy shows that run's state read-only, and the baseline's observe entries - get its last outputs as `$AUTOHELIX_PREVIOUS`. `why` is the new run's note + agent copy shows that run's state read-only, and each observe entry gets its + last output as `$AUTOHELIX_PREVIOUS` until the entry succeeds in this run + (normally the baseline). `why` is the new run's note (`run --why`). A resume refuses, before writing anything, when its target branch moved past its tip and it lands automatically (`runs.landing`: `behind`). @@ -259,9 +268,11 @@ def __init__(self, project_path: Path, verbose: bool = False, heartbeat_seconds: raise RuntimeError(f"Run {short_id(planned.run_id)} is running.") raise RuntimeError(target_ahead_refusal(planned, data, found)) self._agent_settings(self.config) # an unreadable user --settings: refused before any write - if check_only: # nothing written; the scope advice a run prints at its start too + if check_only: # nothing written; what a run prints at its start too if warning := scope_warning(self.config): self._warn(warning) + self._say(self._check_notices(config_file, land_mode or ("manual" if group else "auto"), group, + import_run)) return # The first writes: the local excludes, before .autohelix/ exists. ensure_runtime_ignored(self.project_path) @@ -305,12 +316,11 @@ def __init__(self, project_path: Path, verbose: bool = False, heartbeat_seconds: notices.append(("warn", note)) self.land_mode = land_mode or self.run_info.get("land") or "auto" if self.paths.run_id not in existing and self.land_mode == "auto": - notices.extend(("warn", text) for text in self._uncommitted_config()) - for level, text in notices: - if level == "warn": - self._warn(text) - else: - terminal.show(self.console, text, style="dim") + snapshot = self.paths.experiment + stored = [path.relative_to(snapshot).as_posix() for path in snapshot.rglob("*") if path.is_file()] + notices.extend(("warn", text) for text in self._uncommitted_config(self.run_info.get("target_branch"), + stored)) + self._say(notices) try: self.history = History(self.project_path, self.paths.run_id) tip, warning = reconcile(self.paths, self.run_info, self.history, self.land_mode) @@ -345,22 +355,43 @@ def __init__(self, project_path: Path, verbose: bool = False, heartbeat_seconds: self.close() raise - def _uncommitted_config(self) -> list[str]: + def _say(self, notices: list[tuple[str, str]]) -> None: + """Print `(level, text)` notices: warnings, else dim.""" + for level, text in notices: + if level == "warn": + self._warn(text) + else: + terminal.show(self.console, text, style="dim") + + def _check_notices(self, config_file: Path, land_mode: str, group: str | None, + imported: str | None) -> list[tuple[str, str]]: + """`run --check`'s notices: what `run` would say at its start about the config's + other runs (`new_run_notices`) and, landing automatically, its uncommitted files.""" + base = git(self.project_path, "rev-parse", "HEAD").stdout.strip() + target = git(self.project_path, "symbolic-ref", "--quiet", "HEAD", + check=False).stdout.strip().removeprefix("refs/heads/") or None + notices = new_run_notices(self.project_path, config_relative(self.project_path, config_file), target, + group, imported, base, land_mode) + if land_mode == "auto": + stored = [file.name for file in snapshot_files(self.config, self.project_path)] + notices.extend(("warn", text) for text in self._uncommitted_config(target, stored)) + return notices + + def _uncommitted_config(self, branch: str | None, stored: list[str]) -> list[str]: """A new auto-landing run's warning when its config file, prompt template or a file - the snapshot stores of its experiment folder is untracked or modified (not ignored): committing it - after the run lands puts the branch past the run's tip, and `resume` then refuses.""" - branch = self.run_info.get("target_branch") + the snapshot stores of its experiment folder (`stored`, names in it) is untracked or + modified (not ignored): committing it after the run lands on `branch` puts the + branch past the run's tip, and `resume` then refuses.""" files = [f for f in (self.config_file, self.config.prompt_template) if f is not None] if not branch or not files: return [] - consequence = f"a commit on {branch} after this run lands makes `resume` refuse." + consequence = (f"a commit on {branch} after this run lands makes `resume` refuse. Or keep " + f"{CONFIG_DIR}/ private (docs/concepts.md#where-configs-live).") warnings = [] if (folder := self.config.experiment).is_dir(): # What the run stored (a link, as git lists it, by the files under it) that is # untracked and not ignored (tracked files are clean: `require_clean`). where = config_relative(self.project_path, folder) - snapshot = self.paths.experiment - stored = [path.relative_to(snapshot).as_posix() for path in snapshot.rglob("*") if path.is_file()] listed = git(self.project_path, "--no-optional-locks", "ls-files", "-z", "--others", "--exclude-standard", "--", where, check=False).stdout.split("\0") changed = {name[len(where) + 1:] for name in listed if name.startswith(f"{where}/")} @@ -414,7 +445,7 @@ def _run_config(self, paths: RunPaths, check: bool = True): changed = f"it no longer reads: {e}" if changed: self._refuse_changed(paths, data, f"{data['config_path']} changed since run {short} started ({changed}); ", - "the run keeps the config it started with", "config", "file") + "the run keeps the config it started with", "config", "restore the file") self._check_experiment(paths, data, config) return config @@ -428,24 +459,29 @@ def _check_experiment(self, paths: RunPaths, data: dict, config) -> None: if not config.experiment.is_dir(): terminal.show(self.console, f"{folder} is gone; run {short} continues with the files it " "stored when it started.", style="dim") - elif changed := snapshot_changes(config, self.project_path, paths.experiment): + elif found := snapshot_changes(config, self.project_path, paths.experiment): + # Added files (an evaluator's test output) are removed, not restored. + changed, kinds = found + remedy = ("remove the added files" if kinds == {"added"} else + "restore the files and remove the added ones" if "added" in kinds else "restore the files") self._refuse_changed(paths, data, f"{folder} changed since run {short} started ({changed}); ", - "the run keeps the experiment folder it started with", "folder", "files") + "the run keeps the experiment folder it started with", "folder", remedy) @staticmethod - def _refuse_changed(paths: RunPaths, data: dict, said: str, keeps: str, what: str, restore: str): + def _refuse_changed(paths: RunPaths, data: dict, said: str, keeps: str, what: str, remedy: str): """`_run_config`'s refusal of a changed config or experiment folder (`said`, how): - with a baseline, `run --import`, else a new run.""" + with a baseline, `run --import`, else a new run; `remedy` continues this one.""" short = short_id(paths.run_id) if not has_baseline(paths): # a failed first attempt: nothing to continue or import raise RuntimeError(f"{said}run {short} has no accepted baseline: start a new run, " f"`{run_command(data['config_path'])}` (`autohelix delete {short}` removes " "this attempt).") + command = f"`{run_command(data['config_path'])} --import {short}`" + # The landing first, when there is one: a new run started before it lacks the code. first = land_first(paths, data, data.get("target_branch")) - raise RuntimeError( - f"{said}{keeps}. To apply the new {what}, start a new run " - f"that continues from this one: `{run_command(data['config_path'])} --import {short}`" - f"{'. ' + first if first else '.'} To continue this run, restore the {restore}.") + apply = (f"{first}\nThen {command} applies the new {what}." if first else + f"To apply the new {what}, start a new run that continues from this one: {command}.") + raise RuntimeError(f"{said}{keeps}.\n{apply}\nTo continue this run, {remedy}.") def _metric_label(self, name: str) -> str: """Format metric name with direction arrow.""" @@ -1003,8 +1039,13 @@ def _describe_attempt(self, result: IterationResult, workspace: IterationWorkspa result.summary = workspace.summary result.base = workspace.base result.tree = workspace.tree if workspace.iteration else None - result.discarded = self._discarded(workspace) - result.discarded_frozen = [path for path in result.discarded if path_in_scope(path, self.config.frozen_patterns())] + discarded = self._discarded(workspace) + patterns = self.config.frozen_patterns() + frozen = {path for path in discarded if path_in_scope(path, patterns)} + listed = ([path for path in discarded if path in frozen] + + [path for path in discarded if path not in frozen])[:DISCARDED_LISTED] # frozen first + result.discarded, result.discarded_more = listed, len(discarded) - len(listed) + result.discarded_frozen = [path for path in listed if path in frozen] def _gate_text(self, command: str) -> str: """A gate command's display text (`ask: ` for ask entries).""" @@ -1374,6 +1415,39 @@ def _write_baseline(self, baseline: IterationResult) -> None: self.history.append(baseline) self.segment_log.iteration(ended_at=baseline.ended_at, **iteration_fields(baseline)) + def _unworkable_gate(self, evaluation: _Evaluation) -> str | None: + """At the baseline, a gate that can't work, which would reject every paid + iteration the same way: a command gate exiting 126 or 127 (the shell's "not + executable", "not found"), unless its first word is a path the agent may write + (it may be meant to create it), and an `ask:` gate exiting 2 (no valid answer). + Other failing gates are the agent's to make pass.""" + for spec, result in zip(self.config.gate_commands(), evaluation.constraints): + said = next((clean(line, 300) for line in reversed(result.stderr.splitlines()) if line.strip()), "") + if spec.label is not None: # an `ask:` entry + if result.return_code == 2: + return f"gate `{spec.text}` got no answer" + (f" ({said})" if said else "") + elif result.return_code in (126, 127) and not self._agent_may_write(spec.command): + what = "command not found" if result.return_code == 127 else "not executable" + return f"gate `{spec.text}` could not run (exit {result.return_code}: {what})" + ( + f": {said}" if said else "") + return None + + def _agent_may_write(self, command: str) -> bool: + """Whether a command's first word is a project path the scope lets the agent write + and git doesn't ignore (an ignored file, `.venv/bin/pytest`, never reaches a copy).""" + try: + first = shlex.split(command)[0] + except (ValueError, IndexError): + return False + path = os.path.normpath(first) + if "/" not in first or os.path.isabs(path) or path == ".." or path.startswith("../"): + return False + editable = self.config.editable + return ((not editable or path_in_scope(path, editable)) + and not path_in_scope(path, self.config.frozen_patterns()) + and git(self.project_path, "--no-optional-locks", "check-ignore", "-q", "--", path, + check=False).returncode != 0) + def _capture_baseline(self) -> dict[str, str] | None: """Evaluate A in a checks copy and check stop commands. @@ -1401,6 +1475,10 @@ def _capture_baseline(self) -> dict[str, str] | None: self.log.info(f"baseline FAILED — {reason}") raise AutoHelixRunError(reason) from e + if problem := self._unworkable_gate(evaluation): + self.log.info(f"baseline FAILED — {problem}") + raise RuntimeError(f"Baseline setup error: {problem}") + # A missing number is a setup error, except a review's that no gate uses: an # LLM's answer missing once may be flakiness. A failed entry produces none. metrics = evaluation.metrics @@ -1430,8 +1508,6 @@ def why(names) -> str: self.log.info(f"baseline FAILED — missing metrics: {names}") raise RuntimeError(f"Baseline setup error: {why(missing - advisory)}: every declared metric " "needs a value at the baseline") - self._print_row(IterationResult(iteration=0, accepted=True, metrics=metrics, - gates=evaluation.gates, observe=evaluation.observe)) if metrics: self.log.info("baseline: " + ", ".join(f"{name}: {value:g}" for name, value in metrics.items())) @@ -1450,10 +1526,11 @@ def why(names) -> str: ) self._complete_record(baseline, started_at, time.monotonic(), evaluation) self._write_baseline(baseline) + self._print_row(baseline) # the stored record, its judges' cost included, as `view` shows it return baseline.stop except BaseException as error: - baseline = IterationResult(iteration=0, accepted=False, reason=f"baseline failed: {error}", - base=workspace.base) + reason = "baseline interrupted" if isinstance(error, KeyboardInterrupt) else f"baseline failed: {error}" + baseline = IterationResult(iteration=0, accepted=False, reason=reason, base=workspace.base) self._complete_record(baseline, started_at, time.monotonic(), evaluation) if any(r.iteration == 0 and r.accepted for r in self.history.load()): raise @@ -1606,10 +1683,10 @@ def _new_run_ready(self) -> None: raise RuntimeError("Preflight checks failed. Fix the issues above before running.") self._preflight_done = True - def _preflight(self) -> bool: - """Print preflight warnings and errors; False if there are errors (the caller - then raises, saying the checks failed).""" - issues = preflight_check(self.config, self.project_path) + def _preflight(self, issues=None) -> bool: + """Print preflight warnings and errors (`issues`, default: all of preflight's); False + if there are errors (the caller then raises, saying the checks failed).""" + issues = preflight_check(self.config, self.project_path) if issues is None else issues for w in (i for i in issues if i.level == "warning"): self._warn(w.message) errors = [i for i in issues if i.level == "error"] @@ -1638,7 +1715,7 @@ def _land(self) -> None: before = self._target_tip() land(self.paths, self.run_info, self.run_state.expected_tip) self._landed_count = self._commits_between(before, self.run_state.expected_tip) - self._landing = terminal.landed(self._landed_count, target) + self._landing = terminal.landed(self._landed_count, target, segment=(self._segment or 1) > 1) else: found, words = self._relation() self._landing = terminal.unlanded(found.ahead, f"autohelix/{self.paths.run_id}", words.note, @@ -1727,17 +1804,15 @@ def _run(self, budget: Budget) -> bool: "prompt is used. To keep a custom prompt, move it next to your config, set " "`prompt_template: ` there, and update its .autohelix/ paths to " f"{ITERATION_DIR}/. Otherwise delete it.") - if self.config.prompt_template and (unknown := unknown_variables(load_template(self.config))): - self._warn(f"{self.config.prompt_template.name} uses variables the prompt doesn't have " - f"(they render empty): {', '.join(unknown)}. See docs/concepts.md#prompt for the names.") - if self.config.prompt_template and uses_old_layout(load_template(self.config)): - self._warn(f"{self.config.prompt_template.name} names .autohelix/ paths " - f"in the agent's copy; they are now {ITERATION_DIR}/ (notes written to the old " - "place are lost).") # Run preflight checks before the baseline (silent on success); a first - # start already ran them before allocating the run. - if needs_baseline and not self._preflight_done and not self._preflight(): + # start already ran them before allocating the run. Later segments check only + # that every agent can start (a resume in another shell or on another machine). + if needs_baseline: + ready = self._preflight_done or self._preflight() + else: + ready = self._preflight(agent_issues(self.config)) + if not ready: raise AutoHelixRunError("Preflight checks failed. Fix the issues above before running.") self._segment_checked = True @@ -1827,7 +1902,7 @@ def warn_unknown_cost() -> None: if result.stop: stop_reason = self._condition_stop(result.stop, iteration) break - if result.infrastructure: # credentials or the model service: the next call fails too + if result.infrastructure: # rejected credentials (401/403): the next call fails too stop_reason = {"kind": "infrastructure", "iteration": iteration, "infrastructure": result.infrastructure, "error": result.agent_error, "detail": f"the agent call failed: {result.infrastructure}: " @@ -1914,7 +1989,11 @@ def _print_ending(self, error: BaseException | None) -> None: short = short_id(self.paths.run_id) # What lands the commits that wait (a manual run, an auto landing that failed): # `autohelix land` when the target can fast-forward, else `git merge`. - commands = terminal.next_commands(short, also=self._relation()[1].commands) + # A failed first baseline: `resume` would refuse the fixed setup (an interrupted one resumes). + last = (self.history.load() or [None])[-1] + failed = last is not None and last.iteration == 0 and not last.accepted and last.reason != "baseline interrupted" + restart = run_command(self.run_info["config_path"]) if failed else None + commands = terminal.next_commands(short, also=self._relation()[1].commands, restart=restart) lines = table.ending(outcome, spent=format_total_cost(self.history.cost_usages), landing=self._landing, commands=commands, files=self._files, folder=terminal.shown_path(self.paths.run_dir) + "/", diff --git a/src/autohelix/history.py b/src/autohelix/history.py index 513c1a2f..08b060ad 100644 --- a/src/autohelix/history.py +++ b/src/autohelix/history.py @@ -15,11 +15,16 @@ from autohelix.config import capture_problem from autohelix.formatting import SUMMARY_LIMIT, clean, clean_block from autohelix.costs import CostSummary, summarize_costs -from autohelix.runs import RunPaths, SCHEMA, iteration_folder, remove_planted +from autohelix.runs import RunPaths, SCHEMA, damaged_history, iteration_folder, remove_planted logger = logging.getLogger(__name__) +# The discarded paths a record lists (the rest are counted): an agent writing thousands of +# files outside the scope mustn't grow the history, the record and the next prompt by each. +DISCARDED_LISTED = 20 + + @dataclass class IterationResult: """Result of a single iteration.""" @@ -57,10 +62,11 @@ class IterationResult: tree: str | None = None discarded: list[str] = field(default_factory=list) discarded_frozen: list[str] = field(default_factory=list) # those of `discarded` that are frozen + discarded_more: int = 0 # discarded paths past the first `DISCARDED_LISTED`, not listed # Why the main agent's call failed or timed out (the attempt was rejected unchecked). agent_error: str | None = None - # The failure was the infrastructure's (`AgentRunResult.infrastructure`: credentials, - # the model service), which ended the segment. + # The failure was the infrastructure's (`AgentRunResult.infrastructure`: rejected + # credentials, HTTP 401/403), which ended the segment. infrastructure: str | None = None rejected_ref: str | None = None @@ -461,7 +467,7 @@ def load(self) -> list[IterationResult]: results.append(IterationResult(**data)) except (json.JSONDecodeError, TypeError, ValueError) as e: if lineno != len(lines) or terminated: - raise RuntimeError(f"Corrupt history record {lineno}: {self.history_path}") from e + raise damaged_history(self.paths, lineno) from e logger.warning("Incomplete final history record in %s: %s", self.history_path, e) self._cache = results self._cache_key = key diff --git a/src/autohelix/judge.py b/src/autohelix/judge.py index 6b73d5cb..6a9869af 100644 --- a/src/autohelix/judge.py +++ b/src/autohelix/judge.py @@ -128,14 +128,9 @@ def judge_config(base: AgentConfig, *, cli: str | None = None, model: str | None ) -def load_base_config(cwd: Path) -> AgentConfig: - """`agent:` from $AUTOHELIX_CONFIG, else the config a bare `run` here would use - (`find_config`), else defaults (`base_config`).""" - return base_config(cwd)[0] - - def base_config(cwd: Path) -> tuple[AgentConfig, str]: - """`load_base_config`'s settings, with where they came from, for a by-hand `ask` or + """`agent:` from $AUTOHELIX_CONFIG, else the config a bare `run` here would use + (`find_config`), else defaults; with where they came from, for a by-hand `ask` or `review` to say ("autohelix/a/config.yaml", "defaults: several configs", ...). A set but unreadable $AUTOHELIX_CONFIG, or a malformed `agent:`, is an error diff --git a/src/autohelix/live.py b/src/autohelix/live.py index 7bf6d6a5..8d7fe765 100644 --- a/src/autohelix/live.py +++ b/src/autohelix/live.py @@ -35,13 +35,14 @@ "crashed": "Stopped unexpectedly"} -def status_line(status: dict | None, now: float | None = None) -> str: +def status_line(status: dict | None, now: float | None = None, run_id: str | None = None) -> str: """One line, worded like the viewer's status (the stop reason and phase come from - the run's files: no control characters).""" - return clean(_status_line(status, now)) + the run's files: no control characters). A stopped run waits for its own resume + (`run_id`'s): the view follows one run, and a new `run` never shows in it.""" + return clean(_status_line(status, now, run_id)) -def _status_line(status: dict | None, now: float | None = None) -> str: +def _status_line(status: dict | None, now: float | None = None, run_id: str | None = None) -> str: now = now or time.time() if not status: return "No run recorded yet. Waiting for `autohelix run`…" @@ -51,7 +52,8 @@ def _status_line(status: dict | None, now: float | None = None) -> str: # Interrupted with a reason: `autohelix stop --now`, or Ctrl-C while the ending landed. reason = status.get("stop_reason") if status.get("state") in ("finished", "interrupted") else None why = f" · {reason['detail']}" if isinstance(reason, dict) and reason.get("detail") else "" - return f"{word}{' at ' + when if when else ''}{why}. Waiting for the next run…" + resume = f"autohelix resume {short_id(run_id)}" if run_id else "autohelix resume" + return f"{word}{' at ' + when if when else ''}{why}. Waiting for `{resume}`…" since = format_duration(now - status.get("phase_started_at", now)) if status.get("phase") == "report": return f"Running · writing the summary · {since}" @@ -164,7 +166,7 @@ def render(self, status: dict | None, height: int | None = None) -> list: status.get("stopped_at") or status.get("updated_at") or time.time()) show = self.display and (height is None or height >= MIN_LOG_LINES) parts = [self.display.render(elapsed=int(end - self.started), height=height)] if show else [] - return parts + [Text(status_line(status), style="dim"), *self.steer_lines() * running] + return parts + [Text(status_line(status, run_id=self.run_id), style="dim"), *self.steer_lines() * running] def steer_lines(self) -> list[Text]: """What steers the run from another terminal, and what Ctrl-C does here.""" diff --git a/src/autohelix/prompt_template.py b/src/autohelix/prompt_template.py index 37558d93..cecdf8d0 100644 --- a/src/autohelix/prompt_template.py +++ b/src/autohelix/prompt_template.py @@ -127,6 +127,7 @@ def build_prompt_variables( "rejected_diff": rejected_diff, "discarded": [clean(path) for path in latest.discarded] if latest else [], "discarded_frozen": [clean(path) for path in latest.discarded_frozen] if latest else [], + "discarded_more": latest.discarded_more if latest else 0, "last": _describe_last(latest, state) if latest else None, "last_accepted": _describe_accepted(history, iteration, state), "recent_iterations": SEEDED_ITERATIONS, @@ -263,10 +264,10 @@ def _describe_accepted(history, iteration: int, state: Path) -> dict[str, Any] | # The documented variables (`build_prompt_variables`); a custom template naming others -# gets a warning at run start (`unknown_variables`). +# is a config error (`template_problem`). VARIABLES = frozenset({ "goal", "title", "iteration", "copy", "history", "gates", "observe", "stop", "editable", "frozen", - "notes_path", "hints", "hints_text", "rejected_patch", "rejected_diff", "discarded", "discarded_frozen", "last", "last_accepted", + "notes_path", "hints", "hints_text", "rejected_patch", "rejected_diff", "discarded", "discarded_frozen", "discarded_more", "last", "last_accepted", "recent_iterations", "time_limit", "group", "group_runs", "imported", "experiment", }) @@ -274,36 +275,94 @@ def _describe_accepted(history, iteration: int, state: Path) -> dict[str, Any] | # Variables that were renamed: a template naming the old one is a config error. RENAMED_VARIABLES = {"worktree": "copy"} +# A sample history (a baseline, an accepted iteration, a rejected one) that a custom +# template is rendered against at validation (`template_problem`); docs/phases.md's +# prompt is rendered from it too. +SAMPLE_OBSERVED = [{"name": "bench", "ok": True, "error": None, "metrics": {"speed": 10.0}}, + {"name": "clarity", "ok": True, "error": None, "metrics": {}}] +SAMPLE_RECORDS = [ + {"iteration": 0, "accepted": True, "metrics": {"speed": 10.0}, "reason": "baseline", + "gates": [{"text": "pytest -q", "kind": "command", "passed": True}, + {"text": "speed regress 5%", "kind": "metric", "passed": None}], + "observe": SAMPLE_OBSERVED}, + {"iteration": 1, "accepted": True, "metrics": {"speed": 14.2}, "summary": "Insertion sort for short runs", + "gates": [{"text": "pytest -q", "kind": "command", "passed": True}, + {"text": "speed regress 5%", "kind": "metric", "passed": True}], + "observe": [{**SAMPLE_OBSERVED[0], "metrics": {"speed": 14.2}}, SAMPLE_OBSERVED[1]]}, + {"iteration": 2, "accepted": False, "reason": "gate failed: pytest -q", + "failure_output": "FAILED test_sort.py::test_negative_numbers - assert [-1, -3] == [-3, -1]", + "summary": "Radix sort", "discarded": ["test_sort.py"], "tree": "abc", + "rejected_ref": "refs/autohelix-rejected/20261118-1205-sort-x7k2/2", + "gates": [{"text": "pytest -q", "kind": "command", "passed": False}, + {"text": "speed regress 5%", "kind": "metric", "passed": None}]}, +] + def template_problem(config) -> str | None: - """Why the config's `prompt_template:` can't be used (a config error naming the file - and line: it doesn't parse, or can't be read), else None. Config validation calls it, - so a broken template fails `run`, not the agent.""" + """Why the config's `prompt_template:` can't be used (a config error naming the file: + it doesn't parse, can't be read, names a variable the prompt doesn't have or a path + of the old copy layout, or fails to render against `SAMPLE_RECORDS` after each of + their iterations), else None. Config validation calls it, so a broken template fails + `run --check` and `run`, not the agent.""" name = config.prompt_template.name if config.prompt_template else "prompt template" try: - parsed = _create_env().parse(load_template(config)) + text = load_template(config) + env = _create_env() + parsed = env.parse(text) except TemplateSyntaxError as e: return f"prompt_template {name}, line {e.lineno}: {e.message}" except (RuntimeError, UnicodeDecodeError) as e: return f"prompt_template {name}: {e}" from jinja2 import meta - renamed = sorted(old for old in RENAMED_VARIABLES if old in meta.find_undeclared_variables(parsed)) + names = meta.find_undeclared_variables(parsed) + renamed = sorted(old for old in RENAMED_VARIABLES if old in names) if renamed: return f"prompt_template {name}: " + "; ".join( f"`{old}` is now `{RENAMED_VARIABLES[old]}` ({{{{ {RENAMED_VARIABLES[old]} }}}})" for old in renamed) + if unknown := sorted(names - VARIABLES - set(env.globals)): + return (f"prompt_template {name} uses variables the prompt doesn't have: {', '.join(unknown)}. " + "See docs/concepts.md#prompt for the names.") + if uses_old_layout(text): + from autohelix.workspace import ITERATION_DIR + + return (f"prompt_template {name} names .autohelix/ paths in the agent's copy; they are now " + f"{ITERATION_DIR}/.") + try: + for variables in _sample_variables(config): + render_template(text, variables, name) + except RuntimeError as e: + return str(e) return None -def unknown_variables(template: str) -> list[str]: - """Names a template uses that are not prompt variables (nor Jinja globals), sorted: - e.g. `constraints` or `history_summary` from before config v2. The template parses - (config validation, `template_problem`).""" - from jinja2 import meta +def _sample_variables(config): + """The variables for iterations 1 to 3 of `SAMPLE_RECORDS`, built in a temporary + folder: the top-level `gates` and `observe` are `config`'s, the records' (`last`, + `history`) the sample's. Nothing if the config can't build them (its other problems + are reported on their own).""" + import tempfile + + from autohelix.history import History, IterationResult + from autohelix.workspace import ITERATION_DIR - env = _create_env() - names = meta.find_undeclared_variables(env.parse(template)) - return sorted(names - VARIABLES - set(env.globals)) + with tempfile.TemporaryDirectory(prefix="autohelix-template-") as folder: + try: + project = Path(folder) / "project" + (project / ".autohelix").mkdir(parents=True) + history = History(project) + history.paths.hints.write_text("- [2026-11-18 13:02] A sample hint\n") + state = Path(folder) / "copy" / ITERATION_DIR + (state / "notes").mkdir(parents=True) + (state / "rejected.patch").write_text("diff --git a/sort.py b/sort.py\n") + built = [] + for record in SAMPLE_RECORDS: + history.append(IterationResult(**record)) + built.append(build_prompt_variables(config, history, record["iteration"] + 1, state.parent, + head="sample")) + except Exception: # noqa: BLE001 + return [] + return built def _describe_gate(gate) -> str: diff --git a/src/autohelix/run_table.py b/src/autohelix/run_table.py index eff4aba7..3c9e11ea 100644 --- a/src/autohelix/run_table.py +++ b/src/autohelix/run_table.py @@ -24,6 +24,7 @@ from autohelix import terminal from autohelix.formatting import clean, format_cap, format_duration from autohelix.iteration_time import format_limit +from autohelix.config import config_name, run_command from autohelix.runs import LandingWords, short_id from autohelix.terminal import Row, Table @@ -79,17 +80,17 @@ def _phase(run: dict, now: float | None = None) -> str: def time_cap(run: dict, now: float) -> str: - """What is left of the running segment's --time: `47m 55s left (--time 1h)`, past - it `time up (--time 1h)` (the limit as the flag spells it). "" when the run isn't - running or the segment has no --time (a stopped run's stop reason says when time - ended it). Never a run total.""" + """The running segment's time against its --time, as the web pages say it: `12m 05s + of 1h (this segment)` (the web: `12m5s of 1h`), past it `... (time up)`. "" when the run isn't running or the + segment has no --time (a stopped run's stop reason says when time ended it). Never + a run total.""" status = run.get("status") or {} cap, started = status.get("max_time_seconds"), status.get("segment_started_at") if (not _live(run) or not isinstance(cap, (int, float)) or isinstance(cap, bool) or cap <= 0 or not isinstance(started, (int, float))): return "" - left = int(cap) - max(0, int(now - started)) - return f"{format_duration(left)} left (--time {format_limit(cap)})" if left > 0 else f"time up (--time {format_limit(cap)})" + used = max(0, int(now - started)) + return f"{format_duration(used)} of {format_limit(cap)} (this segment)" + " (time up)" * (used >= cap) def _iterations(run: dict) -> str: @@ -230,8 +231,9 @@ def view_parts(data: dict, saved: Saved, width: int = 100, now: float | None = N version=terminal.version()) if config is not None: progress = run["progress"] - budget = [f"{progress['max_iterations']} iterations"] if progress.get("max_iterations") else [] - budget += [format_cap(progress["max_cost_usd"])] if progress.get("max_cost_usd") is not None else [] + # The status's caps are run totals (`run`'s header says this segment's "2 more"): said so. + budget = [f"to iteration {progress['max_iterations']}"] if progress.get("max_iterations") else [] + budget += [f"{format_cap(progress['max_cost_usd'])} run total"] if progress.get("max_cost_usd") is not None else [] budget += [left] if (left := time_cap(run, now)) else [] called = run.get("agent") or {} # the latest main-agent call's (`latest_agent_call`) agent = terminal.agent_text(config.agent.cli, called.get("model") or config.agent.model, @@ -261,7 +263,7 @@ def view_parts(data: dict, saved: Saved, width: int = 100, now: float | None = N tail = [Text(), terminal.rule(width), *table.outcome_lines(_outcome(run))] else: accepted = sum(1 for r in table.rows if r.accepted and r.iteration > 0 and r.commit) - commands = terminal.next_commands(short, view=False, also=_words(run).commands) + commands = terminal.next_commands(short, view=False, also=_words(run).commands, restart=_restart(run)) tail = table.ending(_outcome(run), spent=terminal.money(run["progress"]["cost_usd"], run["progress"]["cost_incomplete"]), landing=_landed(run, accepted), commands=commands, files=list(saved.files), @@ -398,6 +400,8 @@ def suggestion(run: dict) -> tuple[str, str] | None: command = f"autohelix resume {short}" elif lands: command, where = lands[0], _words(run).cell + elif state == "failed" and (restart := _restart(run)): + command = restart elif state in ("failed", "idle", None) and resumable: command = f"autohelix resume {short}" else: @@ -405,6 +409,16 @@ def suggestion(run: dict) -> tuple[str, str] | None: return f"{_word(run)} · {where}", command +def _restart(run: dict) -> str | None: + """For a run that ended without an accepted baseline (a setup error: `resume` would + refuse the fixed config), the command that starts a new run of its config.""" + if run.get("baseline") is not False or (run.get("status") or {}).get("state") != "failed": + return None + if not isinstance(file := run.get("config_file"), str) or config_name(file) is None: + return None + return run_command(file) + + def entry_header(folder: str, width: int = 100, git: tuple | None = None, version: str | None = None ) -> list[Text]: """The entry screen's header, drawn before the runs are read: `AutoHelix v0.x · diff --git a/src/autohelix/runs.py b/src/autohelix/runs.py index 7d1c3c67..bdcbb67b 100644 --- a/src/autohelix/runs.py +++ b/src/autohelix/runs.py @@ -21,7 +21,7 @@ from typing import NamedTuple from pathlib import Path -from autohelix.config import (ENTRY_NAME, config_name, config_relative, load_config, not_an_experiment, project_configs, +from autohelix.config import (ENTRY_NAME, config_name, config_relative, experiment_config, load_config, not_an_experiment, project_configs, run_command, template_text) from autohelix.experiment import build_snapshot, snapshot_files, sweep_staging @@ -724,10 +724,27 @@ def check_why(text: str) -> str: return why -def has_baseline(paths: RunPaths) -> bool: +def has_baseline(paths: RunPaths, damaged: bool | None = None) -> bool: + """Whether the run's baseline was accepted. A damaged history raises + (`damaged_history`), or, with `damaged` set, gives that: a reader looking across + runs leaves the damage to that run's own commands.""" from autohelix.history import History - return any(r.iteration == 0 and r.accepted for r in History(paths.project, paths.run_id).load()) + try: + return any(r.iteration == 0 and r.accepted for r in History(paths.project, paths.run_id).load()) + except RuntimeError: + if damaged is None: + raise + return damaged + + +def damaged_history(paths: RunPaths, line: int) -> RuntimeError: + """The one error for a history line that can't be read (`History.load`, `repair_history`).""" + if paths.run_id is None: + return RuntimeError(f"{paths.history} line {line} is damaged: fix or remove the line.") + short = short_id(paths.run_id) + return RuntimeError(f"Run {short}'s history.jsonl line {line} is damaged: fix or remove the line, " + f"or `autohelix archive {short}`.") @dataclass(frozen=True) @@ -903,7 +920,7 @@ def words(cell, sentence, note=manual, commands=(), state=None, missing=""): if not accepted: return words("—", "No commits accepted yet.") if relation == "landed": - return words("landed", f"Run {short} landed on {target} (`autohelix land`), which has other " + return words("landed", f"Run {short} landed on {target}, which has other " f"commits in their place since (a squash-merged or rebased PR).") past = (f", which has {plural(behind, 'commit')} past its tip (committed after it)" if relation == "behind" else "") @@ -944,9 +961,23 @@ def resolve_run(project: Path, value: str) -> str: return matches[0] if matches: raise RuntimeError(f"{value!r} matches several runs ({', '.join(matches)}); use the full id.") + project = Path(project).resolve() + if "/" not in value and (project / experiment_config(value)).is_file(): # a config name, as `resume` takes + found = project_runs(project, experiment_config(value)) + latest = next(((p, False) for p, d in found if not is_archived(d)), None) or next( + ((p, True) for p, _ in found), None) + if latest: + short, archived = short_id(latest[0].run_id), " (archived)" if latest[1] else "" + raise RuntimeError(f"{value} is an experiment, not a run: its latest run is {short}{archived}; " + f"use {short}.") + raise RuntimeError(f"{value} is an experiment, not a run, and has no runs; " + f"`autohelix run {value}` starts one.") folder = f" ({value} is a folder: use -p {value})" if Path(value).is_dir() else "" - raise RuntimeError(f"No run {value!r} in {Path(project).resolve()}{folder}. Use a run id or its last " - "part, e.g. k3f9 (names aren't ids); `autohelix view --once` lists runs.") + where = os.path.relpath(project, Path.cwd()) + known = [short_id(p.run_id) for p, _ in project_runs(project)[:3]] + ids = f"the latest: {', '.join(known)}" if known else "e.g. k3f9" + raise RuntimeError(f"No run {value!r} in {min(where, str(project), key=len)}{folder}. Use a run id or its " + f"last part ({ids}); `autohelix view --once` lists runs.") def resolve_runs(project: Path, values) -> list[str]: @@ -978,21 +1009,31 @@ def no_run(project: Path) -> str: return f"No runs in {project}; {how_to_start(project)}" -def default_run(project: Path) -> tuple[RunPaths, dict, str]: - """The run a command given no run id acts on (`land`, `hint`, `view --terminal`, `report`): the - one running run, else the most recently active run that isn't archived. Returns it - with why it was chosen ("running", "most recently active") for the caller to say. - RuntimeError when several runs are running (name one), NoRun when there is none.""" +def default_run(project: Path, running: bool = True) -> tuple[RunPaths, dict, str]: + """The run a command given no run id acts on (`hint`, `view --terminal`): the one + running run, else the most recently active run that isn't archived. Without + `running` (`land`, `report`, which a running run refuses), the most recently active + run that isn't running or archived. Returns it with why it was chosen ("running", + "most recently active", "most recently active … that isn't running") for the caller + to say. RuntimeError when several runs are running (name one), NoRun when there is none.""" runs = project_runs(project) live = [(p, d) for p, d in runs if is_live(p)] + if not running: + for paths, data in runs: + if not is_archived(data) and (paths, data) not in live: + return paths, data, "most recently active run that isn't running" + if live: + raise RuntimeError(f"Every run is running or archived (running: " + f"{', '.join(short_id(p.run_id) for p, _ in live)}); name one.") + raise NoRun(no_run(project)) if len(live) > 1: raise RuntimeError(f"Several runs are running: {', '.join(short_id(p.run_id) for p, _ in live)}; " "name one.") if live: - return (*live[0], "running") + return (*live[0], "running run") for paths, data in runs: if not is_archived(data): - return paths, data, "most recently active" + return paths, data, "most recently active run" raise NoRun(no_run(project)) @@ -1033,7 +1074,7 @@ def _resuming(paths: RunPaths, data: dict) -> str: return f"Resuming {short_id(paths.run_id)}: {last} iteration{'s' * (last != 1)}{ago}.{back}" -def _new_run_notices(project: Path, config_path: str, target: str | None, +def new_run_notices(project: Path, config_path: str, target: str | None, group: str | None = None, imported: str | None = None, base: str | None = None, land_mode: str | None = None) -> list[tuple[str, str]]: """What `run` says about this config's other runs: it never refuses. Runs of a @@ -1066,7 +1107,7 @@ def _new_run_notices(project: Path, config_path: str, target: str | None, short = short_id(paths.run_id) found = landing(paths, data) count = found.ahead - if not has_baseline(paths): # a failed first attempt: nothing to continue + if not has_baseline(paths, damaged=False): # a failed first attempt: nothing to continue if not notices: notices.append(("info", f"Previous run for this config: {short}, without an accepted baseline " f"(`autohelix delete {short}` removes it).")) @@ -1181,13 +1222,8 @@ def _resumable(project: Path, config_path: str) -> list[RunPaths]: (an empty run, `run` typed by mistake and interrupted, must not shadow the real one, but is resumed when it is all there is), then by activity.""" candidates = [p for p, d in project_runs(project, config_path) if not is_archived(d)] - def baseline(paths: RunPaths) -> bool: - try: - return has_baseline(paths) - except RuntimeError: # a corrupt history: that run's own resume says so, not every other's - return False - - candidates.sort(key=baseline, reverse=True) # stable: by activity within each + # A damaged history: that run's own resume says so, not every other's. + candidates.sort(key=lambda paths: has_baseline(paths, damaged=False), reverse=True) # stable: by activity within each return candidates @@ -1268,7 +1304,7 @@ def select_run(project: Path, config: Path, *, name: str | None = None, new: boo files = snapshot_files(loaded, project) # refused here, before anything is written base = git(project, "rev-parse", "HEAD").stdout.strip() target = git(project, "symbolic-ref", "--quiet", "HEAD", check=False).stdout.strip().removeprefix("refs/heads/") or None - notices = _new_run_notices(project, config_path, target, group, imported, base, land_mode) + notices = new_run_notices(project, config_path, target, group, imported, base, land_mode) # Suffixes are unique across the repository (refs of old-format ids included). taken = {short_id(ref) for ref in git(project, "for-each-ref", "--format=%(refname:lstrip=2)", "refs/autohelix/").stdout.split()} @@ -1335,17 +1371,19 @@ def repair_history(paths: RunPaths) -> None: lines = raw.splitlines(keepends=True) records = [] for index, line in enumerate(lines): + if not line.strip(): # skipped, as `History.load` does + continue try: record = json.loads(line) except (ValueError, UnicodeDecodeError): if index != len(lines) - 1 or line.endswith(b"\n"): - raise RuntimeError(f"Corrupt history record {index + 1}: {path}") from None + raise damaged_history(paths, index + 1) from None torn = re.match(rb'\s*\{\s*"iteration"\s*:\s*(\d+)\s*[,}]', line) write_records(paths, records, mode="replace", iterations=stale_records(paths, records) | ({int(torn[1])} if torn else set())) return if not valid_record(record): - raise RuntimeError(f"Invalid history record {index + 1}: {path}") + raise damaged_history(paths, index + 1) records.append(record) stale = stale_records(paths, records) if raw and not raw.endswith(b"\n"): # complete, but unterminated @@ -1411,8 +1449,9 @@ def reconcile(paths: RunPaths, data: dict, history, land_mode: str) -> tuple[str return tip, warning -def land(paths: RunPaths, data: dict, expected_tip: str, into: str | None = None) -> None: - """Fast-forward the target to the harness's validated tip, never a moving ref.""" +def land(paths: RunPaths, data: dict, expected_tip: str, into: str | None = None) -> str | None: + """Fast-forward the target to the harness's validated tip, never a moving ref. None + when it moved the branch, else what it found instead (nothing was done).""" target = into or data.get("target_branch") if not target: raise RuntimeError("This run started detached; land requires --into .") @@ -1424,9 +1463,14 @@ def land(paths: RunPaths, data: dict, expected_tip: str, into: str | None = None # Already there (a `behind` target that has the tip), or nothing accepted to land. there = found.relation != "behind" or _has(paths.project, found.target_tip, expected_tip) if there or not found.accepted: - if there and found.relation != "landed": - _record_landed(paths, data, found) - return + short = short_id(paths.run_id) + if not found.accepted: + return f"Run {short} has nothing accepted to land." + if found.relation == "landed": + return (f"Run {short} landed on {target} before, which has other commits in their place since; " + f"to land it again: `git merge autohelix/{paths.run_id}`.") + _record_landed(paths, data, found) + return f"Run {short} is already in {target}." hint = f"Run {paths.run_id} remains available: git merge autohelix/{paths.run_id}" if found.relation != "ahead": # diverged (also commits accepted after a squash-merged landing) why = (landing_words(found, paths.run_id, data.get("land") or "auto").sentence @@ -1452,6 +1496,7 @@ def land(paths: RunPaths, data: dict, expected_tip: str, into: str | None = None if result.returncode: raise RuntimeError(f"Cannot land {target}: branch is busy or changed. {hint}") _record_landed(paths, data, found) + return None def _record_landed(paths: RunPaths, data: dict, found: Landing) -> None: @@ -1513,7 +1558,9 @@ def set_options(paths: RunPaths, *, land_mode: str | None = None, group: str | N def delete(paths: RunPaths, *, force: bool = False, warn=None) -> None: """Remove a run's state, ref, pin, rejected trees and copies. Refuses while it runs, and, unless - forced, while it has unlanded commits (they'd become unreachable).""" + forced, while it has unlanded commits or its accepted tip is on no branch, tag or + remote-tracking branch (they'd become unreachable: `landed` is no proof, a reset + target reads landed too).""" short = short_id(paths.run_id) with RunLock(paths.lock): try: @@ -1528,6 +1575,14 @@ def delete(paths: RunPaths, *, force: bool = False, warn=None) -> None: raise RuntimeError(f"Not deleting run {short}, which has {plural(found.ahead, 'unlanded commit')}: " f"{sentence} " f"`autohelix delete --force {short}` discards {'it' if found.ahead == 1 else 'them'}.") + if found and found.accepted and found.tip and not force and not git( + paths.project, "for-each-ref", "--count=1", "--contains", found.tip, "--format=%(refname)", + "refs/heads", "refs/tags", "refs/remotes", check=False).stdout.strip(): + why = (f" It reads landed: `land` put it on {found.target}, which lacks it now (a squash-merged PR, " + f"or a reset?)." if found.relation == "landed" else "") + raise RuntimeError(f"Not deleting run {short}: its tip isn't on any branch, tag or remote-tracking " + f"branch, so its commits would be lost.{why} `autohelix delete --force {short}` " + f"discards them; `autohelix archive {short}` keeps them.") remove_copies(paths.copies, warn or (lambda message: None)) git(paths.project, "update-ref", "-d", paths.pin, check=False) kept = git(paths.project, "for-each-ref", "--format=%(refname)", paths.rejected_refs, check=False) diff --git a/src/autohelix/skills/autohelix/references/reading-runs.md b/src/autohelix/skills/autohelix/references/reading-runs.md index e9918df3..63d5e8d1 100644 --- a/src/autohelix/skills/autohelix/references/reading-runs.md +++ b/src/autohelix/skills/autohelix/references/reading-runs.md @@ -36,8 +36,8 @@ agent's one-line summary), `metrics`, `commit` (accepted), `gates` (each `output` tail; metric gates `value` and `reference`), `observe` (each `name`, `ok`, `error`, `metrics`), `stops`, `discarded` (out-of-scope paths dropped), `agent_error` (the agent call failed or timed out: rejected unchecked), -`infrastructure` (that failure was the credentials' or the model service's: -the run stopped there), +`infrastructure` (that failure was rejected credentials, HTTP 401/403: the +run stopped there), `base`, `tree`, `rejected_ref`, `started_at`/`ended_at`, `calls`. For numbers across iterations: `jq -c '[.iteration, .accepted, .metrics, .reason]' .autohelix/runs//history.jsonl`. diff --git a/src/autohelix/templates/config_template.yaml b/src/autohelix/templates/config_template.yaml index bae59222..e3813fe2 100644 --- a/src/autohelix/templates/config_template.yaml +++ b/src/autohelix/templates/config_template.yaml @@ -44,7 +44,7 @@ scope: agent: cli: claude-code # claude-code, codex or opencode - model: opus # passed through unchanged; unset = the CLI's default + # model: opus # the CLI's own model name, passed through; unset = its default # effort: high # timeout: 30m # per iteration: the agent sees the time left, then is stopped diff --git a/src/autohelix/templates/default_prompt.md b/src/autohelix/templates/default_prompt.md index 0e867b80..c7d35620 100644 --- a/src/autohelix/templates/default_prompt.md +++ b/src/autohelix/templates/default_prompt.md @@ -46,6 +46,9 @@ Your changes to {{ not_editable | join(', ') }} were discarded: outside the edit {% if discarded_frozen %} Your changes to {{ discarded_frozen | join(', ') }} were discarded: frozen. {% endif %} +{% if discarded_more %} +Your changes to {{ discarded_more }} more paths outside the scope were discarded too. +{% endif %} {% if gates %} Gates (must pass — failure means your changes are discarded): diff --git a/src/autohelix/terminal.py b/src/autohelix/terminal.py index c567d463..44109b1a 100644 --- a/src/autohelix/terminal.py +++ b/src/autohelix/terminal.py @@ -329,6 +329,7 @@ class Row: stops: list = field(default_factory=list) discarded: list = field(default_factory=list) discarded_frozen: list = field(default_factory=list) + discarded_more: int = 0 # past the record's listed ones @classmethod def of(cls, record) -> "Row": @@ -339,7 +340,8 @@ def of(cls, record) -> "Row": seconds=wall_ms / 1000 if wall_ms else None, cost=cost.cost_usd, cost_incomplete=cost.incomplete, commit=record.commit, reason=record.reason, agent_error=record.agent_error, summary=record.summary, gates=record.gates, observe=record.observe, stops=record.stops, - discarded=record.discarded, discarded_frozen=record.discarded_frozen) + discarded=record.discarded, discarded_frozen=record.discarded_frozen, + discarded_more=record.discarded_more) LABEL = 6 # "✓ 12 " @@ -522,7 +524,8 @@ def _notes(self, row: Row) -> list[tuple[str, str | None]]: if row.discarded: frozen = set(row.discarded_frozen) shown = ", ".join(clean(p) + " (frozen)" * (p in frozen) for p in row.discarded[:3]) - more = f", … {len(row.discarded) - 3} more" if len(row.discarded) > 3 else "" + hidden = len(row.discarded) - 3 + row.discarded_more + more = f", … {hidden} more" if hidden > 0 else "" notes.append((f"discarded, outside the scope: {shown}{more}", "dim")) return notes @@ -710,10 +713,13 @@ def commits(n: int) -> str: return f"{n} commit{'s' * (n != 1)}" -def landed(count: int, target: str) -> tuple[str, str, str | None]: +def landed(count: int, target: str, segment: bool = False) -> tuple[str, str, str | None]: """The end block's landing line (label, text, style): `landed 3 commits on main`, - `landed nothing (no accepted changes)`.""" - return ("landed", f"{commits(count)} on {target}", None) if count else ("landed", "nothing (no accepted changes)", "dim") + `landed nothing (no accepted changes)`. `segment`: `count` is one segment's of a + resumed run (`run`'s end block), said so, where `view` counts the run's.""" + if not count: + return "landed", "nothing (no accepted changes" + " this segment" * segment + ")", "dim" + return "landed", f"{commits(count)} on {target}" + " (this segment)" * segment, None def unlanded(count: int, branch: str, note: str = "", style: str | None = None) -> tuple[str, str, str | None]: @@ -726,12 +732,14 @@ def not_landed(error) -> tuple[str, str, str | None]: return "landing", f"failed: {clean(error)}", "yellow" -def next_commands(short: str, view: bool = True, also=()) -> list[str]: +def next_commands(short: str, view: bool = True, also=(), restart: str | None = None) -> list[str]: """What to type after a run: look at it (`view`: not from the view itself), continue it, then `also`: what lands commits that wait (`runs.LandingWords.commands`: `autohelix land ` when the target can fast-forward, `git merge autohelix/` - when it diverged).""" - return ([f"autohelix view {short}"] if view else []) + [f"autohelix resume {short}", *also] + when it diverged). A run whose baseline failed (`restart`: the command that starts + its config's runs) isn't continued: a new run once the setup is fixed, or delete it.""" + go_on = [restart, f"autohelix delete {short}"] if restart else [f"autohelix resume {short}"] + return ([f"autohelix view {short}"] if view else []) + [*go_on, *also] def command_hint(command: str, target: str = "") -> str: @@ -743,6 +751,10 @@ def command_hint(command: str, target: str = "") -> str: return "the run's page in your browser" if command.startswith("autohelix resume "): return "one more iteration (-n N for more)" + if command.startswith("autohelix run "): + return "a new run, once the setup is fixed" + if command.startswith("autohelix delete "): + return "remove this attempt" if command.startswith("autohelix land "): return f"put its commits on {branch}" if command.startswith("git merge "): diff --git a/src/autohelix/viewer.py b/src/autohelix/viewer.py index a283405c..970bab3a 100644 --- a/src/autohelix/viewer.py +++ b/src/autohelix/viewer.py @@ -42,7 +42,7 @@ from autohelix import run_table from autohelix.agents import AgentEventKind from autohelix.safe_open import bad_parts as _bad_parts, contained as _contained, open_dir as _open_dir, open_file as _open_file, open_run_log -from autohelix.config import ConfigError, MetricGate, config_relative, load_config, template_text +from autohelix.config import MetricGate, config_relative, load_config from autohelix.costs import summarize_costs from autohelix.history import History, latest_agent_call, record_seconds from autohelix.runs import (COMMIT, RunPaths, git, is_archived, is_transcript, landing, landing_words, @@ -61,7 +61,7 @@ ".gif": "image/gif", ".webp": "image/webp"} LOOPBACK = {"127.0.0.1", "localhost", "[::1]"} # Phases after the agent copy is frozen, when the pin holds this iteration's tree. -FROZEN_PHASES = {"preparing checks", "checks", "observe", "review", "accept", "stop check"} +FROZEN_PHASES = {"preparing checks", "checks", "observe", "accept", "stop check"} ASSETS = { "/": ("dashboard.html", "text/html; charset=utf-8"), "/common.js": ("common.js", "text/javascript; charset=utf-8"), @@ -110,6 +110,11 @@ def _field(record, name: str): return getattr(record, name, None) if record is not None else None +def _count(value) -> int: + """A count from a history record: a non-negative int, else 0.""" + return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 0 + + def _object(value) -> str | None: """A git object name from a history record, or None: never an option or a rev expression.""" return value if isinstance(value, str) and COMMIT.fullmatch(value) else None @@ -139,19 +144,6 @@ def _read_text_at(root: Path, parts, single_link: bool = False) -> str | None: return None if fd is None else _tail(fd) -def _read_user_file(path: Path) -> str | None: - """`_tail` of a file the user owns (the config: a symlink to it is fine), never - blocking on a FIFO.""" - try: - fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | getattr(os, "O_CLOEXEC", 0)) - except OSError: - return None - if not stat.S_ISREG(os.fstat(fd).st_mode): - os.close(fd) - return None - return _tail(fd) - - def _listing(root: Path, parts) -> list[tuple[str, os.stat_result]]: """The entries of the folder `root/parts...` (opened as `_open_dir` does), with their own lstat.""" @@ -263,9 +255,15 @@ def _config(self): config = load_run_config(self.paths) except Exception: config = None - cached = self._configs[path] = (key, config, _read_user_file(path)) + cached = self._configs[path] = (key, config, self._stored_text(path)) return cached[1], path + def _stored_text(self, path: Path) -> str | None: + """A file the run stored (its config, its template), read as the rest of run state + is: from the run folder down, no symlinks, a single link (the page and report.html + show it).""" + return _read_text_at(self.root, self.paths.parts(path), single_link=True) + def _config_summary(self, config, path: Path | None, called: dict | None = None) -> dict | None: """The run page's config: its file and text, and the header's fields; `agent` with the model the latest main-agent call reported (`called`), else the configured one.""" @@ -278,13 +276,10 @@ def _config_summary(self, config, path: Path | None, called: dict | None = None) file = self.paths.read_identity()["config_path"] except (RuntimeError, KeyError): pass - summary = {"file": file, "text": cached[2] if cached else _read_user_file(path)} + summary = {"file": file, "text": cached[2] if cached else self._stored_text(path)} if config is not None and config.prompt_template is not None: # stored beside a run's config - try: - text = template_text(config) - except ConfigError: - text = None - summary["template"] = {"file": config_relative(self.project, config.prompt_template), "text": text} + summary["template"] = {"file": config_relative(self.project, config.prompt_template), + "text": self._stored_text(self.paths.template)} if config: summary.update( agent=agent_text(config.agent.cli, (called or {}).get("model") or config.agent.model, @@ -312,11 +307,12 @@ def iterations(self, records) -> list[dict]: or reason or subjects.get(r.commit), "reason": reason, "cost": r.cost.cost_usd, "cost_incomplete": r.cost.incomplete, - "seconds": (r.usage.get("wall_clock_ms") or 0) / 1000 or None, + "seconds": record_seconds(r) or None, # the baseline's from its start and end "gates": r.gates, "observe": r.observe, "stops": [item for item in _field(r, "stops") or [] if isinstance(item, dict)], "discarded": [p for p in _field(r, "discarded") or [] if isinstance(p, str)], "discarded_frozen": [p for p in _field(r, "discarded_frozen") or [] if isinstance(p, str)], + "discarded_more": _count(_field(r, "discarded_more")), }) return rows @@ -458,6 +454,7 @@ def iteration(self, n: int, logs: bool = True, diff: bool = True, outputs: bool "summary": summary if isinstance(summary, str) and summary.strip() else None, "discarded": [p for p in _field(record, "discarded") or [] if isinstance(p, str)], "discarded_frozen": [p for p in _field(record, "discarded_frozen") or [] if isinstance(p, str)], + "discarded_more": _count(_field(record, "discarded_more")), # What `/iteration//diff` compares: the commit the attempt started from and its frozen tree. "attempt": {"base": base, "tree": tree, "commit": record.commit if record else None, "rejected_ref": rejected_ref if isinstance(rejected_ref, str) else None} @@ -1001,6 +998,7 @@ def _run(self, run_id: str, refs: dict[str, str]) -> dict: # `autohelix stop` asked the running segment to end ({requested_at, why, now}), else None. "stop_requested": pending_stop(paths, status), "accepted": accepted, + "baseline": any(r.iteration == 0 and r.accepted for r in records), # its baseline was accepted "metrics": self._metrics(records, config.get("directions") or {}), # The caps of the latest segment (`run`/`resume` flags), from its status; None # where it had none. Iterations and cost as run totals (spent before it plus its diff --git a/src/autohelix/viewer_resources/viewer.js b/src/autohelix/viewer_resources/viewer.js index 5aa0dadd..33521322 100644 --- a/src/autohelix/viewer_resources/viewer.js +++ b/src/autohelix/viewer_resources/viewer.js @@ -150,8 +150,9 @@ function bestSoFar() { return out; } -// Best metric, then run totals (as in the terminal's run summary): time over the -// iterations (finished, and the running one so far); cost also includes the baseline's calls. +// Best metric, then run totals (as in the terminal's run summary): time over every +// recorded row, the baseline's included (as the run list's), and the running iteration so +// far; cost also includes the baseline's calls. function renderStats() { const its = state.iterations.filter((r) => r.iteration > 0); const cost = state.cost; @@ -165,14 +166,15 @@ function renderStats() { const started = state.status?.iteration_started_at; const running = live > 0 && !row(live) && isNumber(started) ? Math.max(0, Date.now() / 1000 - started) : null; if (its.length || running !== null) { - const timed = its.filter((r) => isNumber(r.seconds)); + const timed = state.iterations.filter((r) => isNumber(r.seconds)); stats.push(['Time', timed.length || running !== null - ? fmtDuration(timed.reduce((sum, r) => sum + r.seconds, running ?? 0)) + (timed.length < its.length ? ' (incomplete)' : '') + ? fmtDuration(timed.reduce((sum, r) => sum + r.seconds, running ?? 0)) + + (timed.length < state.iterations.length ? ' (incomplete)' : '') : '—']); } if (its.length || isNumber(cost?.cost_usd) || cost?.incomplete) { stats.push(['Cost', isNumber(cost?.cost_usd) - ? fmtMoney(cost.cost_usd) + (cost.incomplete ? ' (incomplete)' : '') + ? fmtMoney(cost.cost_usd) + (cost.incomplete ? '+' : '') : 'unavailable']); } $('stats').replaceChildren(...stats.map(([k, v, extra]) => el('div', { className: 'stat' }, @@ -299,7 +301,7 @@ function renderRows() { el('td', { className: 'value' }, metric ? fmtNumber(v) : '', metric && r.iteration > 0 ? deltaEl(v, base) : null), summaryCell(r), el('td', { className: 'num', textContent: fmtDuration(r.seconds) }), - el('td', { className: 'num', textContent: (fmtMoney(r.cost) || '—') + (isNumber(r.cost) && r.cost_incomplete ? ' (incomplete)' : ''), + el('td', { className: 'num', textContent: (fmtMoney(r.cost) || '—') + (isNumber(r.cost) && r.cost_incomplete ? '+' : ''), title: r.cost_incomplete ? 'Some call costs are unavailable' : '' }), ]); }); @@ -307,7 +309,7 @@ function renderRows() { rows.push(rowEl(running, [ el('td', { textContent: String(running) }), el('td', {}, el('span', { className: 'pill running', textContent: 'running' })), - el('td'), el('td', { className: 'summary muted', textContent: phaseText(state.status.phase) }), el('td'), el('td'), + el('td'), el('td', { className: 'summary muted', textContent: state.status.phase_word || '' }), el('td'), el('td'), ])); } if (report) { @@ -337,7 +339,7 @@ function summaryCell(r) { const flags = [ baselineGates.length && `gate failed at the baseline: ${baselineGates.join(', ')}`, failed.length && `${failed.join(', ')} failed`, - r.discarded?.length && `${plural(r.discarded.length, 'out-of-scope change')} discarded`, + r.discarded?.length && `${plural(r.discarded.length + (r.discarded_more || 0), 'out-of-scope change')} discarded`, ].filter(Boolean).join(' · '); return el('td', { className: 'summary' }, why ? el('div', { className: 'why', textContent: why }) : null, @@ -372,13 +374,6 @@ function shortReason(reason) { return reason.length > 40 ? reason.slice(0, 40) + '…' : reason; } -const PHASES = { - starting: 'Starting…', baseline: 'Measuring the baseline…', agent: 'Agent is working…', - checks: 'Running gates…', observe: 'Running observe entries…', - merge: 'Merging the accepted change…', 'between iterations': 'Wrapping up…', -}; -const phaseText = (phase) => PHASES[phase] || `${phase}…`; - function rowEl(iteration, cells) { const tr = el('tr', { tabIndex: 0 }, ...cells); tr.dataset.iteration = String(iteration); @@ -522,7 +517,7 @@ function renderPanel() { const why = outcome === 'rejected' ? rejection(r) : ''; $('panel-title').replaceChildren(el('span', { textContent: label(n) }), ...[ n > 0 && outcome && el('span', { className: `pill ${outcome}`, textContent: outcome }), - live && el('span', { className: 'muted', textContent: phaseText(state.status.phase) }), + live && el('span', { className: 'muted', textContent: state.status.phase_word || '' }), why && el('span', { className: 'muted', textContent: why }), ].filter(Boolean)); const d = panel.detail; @@ -567,10 +562,11 @@ function discardedSection(d, where) { if (!discarded.length) return null; const frozen = new Set(d.discarded_frozen || []); const s = section('discarded', 'Discarded changes', true, `${where}/record.json`); - fill(s, plural(discarded.length, 'path'), JSON.stringify([discarded, [...frozen]]), () => [ + const more = d.discarded_more || 0; + fill(s, plural(discarded.length + more, 'path'), JSON.stringify([discarded, [...frozen], more]), () => [ el('p', { textContent: 'Changes outside the scope (not editable, or frozen) were discarded:' }), el('ul', { className: 'paths' }, ...discarded.map((p) => el('li', {}, el('code', { textContent: p }), - frozen.has(p) ? ' (frozen)' : '')))]); + frozen.has(p) ? ' (frozen)' : '')), more ? el('li', { textContent: `and ${more} more` }) : null)]); return s; } diff --git a/src/autohelix/workspace.py b/src/autohelix/workspace.py index d3a9412f..a9f3f537 100644 --- a/src/autohelix/workspace.py +++ b/src/autohelix/workspace.py @@ -152,8 +152,8 @@ def out(self, *args: str, **kwargs) -> str: return os.fsdecode(self.git(*args, **kwargs).stdout).strip() def unfrozen_excludes(self, work_tree: Path, index: Path, **kwargs) -> list[str]: - """Pathspecs keeping `.autohelix/` and `.autohelix-iteration/` out of an `add -A` - in a copy, so their files are never hashed. `add` refuses an exclude naming an + """Pathspecs keeping `.autohelix/` and `.autohelix-iteration/` out of a listing or + an `add` in a copy, so their files are never hashed. `add` refuses an exclude naming an ignored folder; an ignored folder isn't added anyway, so it needs none.""" unfrozen = [f"{self.prefix}{name}" for name in _UNFROZEN] ignored = set(_records(self.git("check-ignore", "-z", "--stdin", work_tree=work_tree, index=index, @@ -333,6 +333,12 @@ def _records(output: bytes) -> list[str]: return [os.fsdecode(record) for record in output.split(b"\0") if record] +def _parents(name: str): + """`a/b/c`'s folders: `a`, `a/b`.""" + parts = name.split("/") + return ("/".join(parts[:depth]) for depth in range(1, len(parts))) + + def _remove_tree(path: Path) -> None: """Remove a tree, including read-only or unreadable folders, without following symlinks.""" try: @@ -447,7 +453,12 @@ def _init_private_git(self) -> None: def snapshot(self, scope: Scope) -> tuple[str, list[str]]: """The candidate tree: the copy's files with out-of-scope changes reset to - `files` in the harness index only. Returns (tree, discarded names).""" + `files` in the harness index only. Returns (tree, discarded names). + + The change set is listed first, hashing nothing; only in-scope names are staged, + so an out-of-scope file (a dataset, a checkpoint) never enters the user's object + store. Out-of-scope entries a staged name replaced (a folder turned into a file) + are reset afterwards.""" _check_copy(self.path) repo = self.repo for name in self.gitlinks: # git ignores writes inside an uninitialized submodule @@ -457,22 +468,67 @@ def snapshot(self, scope: Scope) -> tuple[str, list[str]]: attributes = [f"--attr-source={self.files}"] if repo.attr_source else [] self._check_index() unfrozen = [f"{repo.prefix}{name}" for name in _UNFROZEN] + + def kept(name: str) -> bool: + return scope.allows(name) and not any(name == d or name.startswith(d + "/") for d in unfrozen) + + excludes = repo.unfrozen_excludes(self.path, self.index) + try: + # Stat data only (no object is written), so a touched file isn't listed as changed. + repo.git(*attributes, "update-index", "-q", "--refresh", work_tree=self.path, index=self.index, + check=False) + listed = set(_records(repo.git(*attributes, "diff-files", "-z", "--name-only", "--", ".", *excludes, + work_tree=self.path, index=self.index).stdout)) + new = _records(repo.git("ls-files", "-z", "--others", "--exclude-standard", "--", ".", *excludes, + work_tree=self.path, index=self.index).stdout) + except RuntimeError as e: + raise CandidateRejected(f"could not snapshot the candidate: {e}") from e + for name in new: + if name.endswith("/"): # a repository the agent made or cloned, with or without commits + raise CandidateRejected(nested_repository(name.rstrip("/"))) + if gitlink := next((name for name in self.gitlinks if name in listed), None): + raise CandidateRejected(f"submodule changes are not supported: {gitlink}") + listed.update(new) + added = {name for name in listed if kept(name)} + outside = listed.difference(added) + # The kept names go straight into the harness index (`update-index`: unlike `add`, it + # stages a tracked file in an ignored folder): a file or symbolic link is hashed and + # staged; any other name (deleted, now a folder, below a folder now a symbolic link) + # loses its entry. A folder's new files are listed names of their own. + staged = sorted(name for name in added if self._staged(name)) try: - repo.git(*attributes, "add", "-A", "--", ".", *repo.unfrozen_excludes(self.path, self.index), - work_tree=self.path, index=self.index) - except RuntimeError as e: # e.g. an unreadable file or an embedded repo without commits - if nested := re.search(r"'([^'\n]+?)/?' does not have a commit checked out", str(e)): - raise CandidateRejected(nested_repository(nested.group(1))) from e + if removed := sorted(added.difference(staged)): + repo.git("update-index", "-z", "--force-remove", "--stdin", index=self.index, + input=b"".join(os.fsencode(name) + b"\0" for name in removed)) + if staged: + repo.git(*attributes, "update-index", "-z", "--add", "--replace", "--stdin", + work_tree=self.path, index=self.index, + input=b"".join(os.fsencode(name) + b"\0" for name in staged)) + except RuntimeError as e: # e.g. an unreadable file raise CandidateRejected(f"could not snapshot the candidate: {e}") from e changes = self._changes() # Reset to `files` in the index only; git drops new entries that conflict with a restored path. - reset = [f"{old_mode} {old_oid}\t{name}" for name, (old_mode, old_oid) in changes.items() - if not scope.allows(name) or any(name == d or name.startswith(d + "/") for d in unfrozen)] + reset = [f"{old_mode} {old_oid}\t{name}" for name, (old_mode, old_oid) in changes.items() if not kept(name)] if reset: repo.git("update-index", "-z", "--index-info", index=self.index, input=b"".join(os.fsencode(line) + b"\0" for line in reset)) tree = repo.out("write-tree", index=self.index) - return tree, sorted(changes.keys() - (self._changes() if reset else changes).keys()) + return tree, sorted(outside | (changes.keys() - (self._changes() if reset else changes).keys())) + + def _staged(self, name: str) -> bool: + """Whether `name` is a file or symbolic link in the copy, not below a symbolic link. + A FIFO, socket or device there can't be committed: CandidateRejected.""" + if any(os.path.islink(self.path / parent) for parent in _parents(name)): + return False + try: + mode = os.lstat(self.path / name).st_mode + except OSError: # deleted, or below what is now a file + return False + if stat.S_ISREG(mode) or stat.S_ISLNK(mode): + return True + if stat.S_ISDIR(mode): + return False + raise CandidateRejected(f"could not snapshot the candidate: {name} is not a regular file or symbolic link") def _changes(self) -> dict[str, tuple[str, str]]: """Index entries that differ from `files`: name -> (mode, oid) in `files`.""" diff --git a/tests/snapshots/resume-120.txt b/tests/snapshots/resume-120.txt index 73c89ed4..0b6c76da 100644 --- a/tests/snapshots/resume-120.txt +++ b/tests/snapshots/resume-120.txt @@ -23,7 +23,7 @@ speed 46.9 → 61,004.2 1301× iter 8 mem_mb 120 → 94 -22% iter 8 run 8 iterations · 4 accepted · 40m 21s · $2.92 - landed 1 commit on main + landed 1 commit on main (this segment) next autohelix view krp3 the run's page in your browser autohelix resume krp3 one more iteration (-n N for more) folder .autohelix/runs/20261115-1402-sorting-krp3/ diff --git a/tests/snapshots/resume-80.txt b/tests/snapshots/resume-80.txt index f7345e4d..cd0e7c51 100644 --- a/tests/snapshots/resume-80.txt +++ b/tests/snapshots/resume-80.txt @@ -24,7 +24,7 @@ speed 46.9 → 61,004.2 1301× iter 8 mem_mb 120 → 94 -22% iter 8 run 8 iterations · 4 accepted · 40m 21s · $2.92 - landed 1 commit on main + landed 1 commit on main (this segment) next autohelix view krp3 the run's page in your browser autohelix resume krp3 one more iteration (-n N for more) folder .autohelix/runs/20261115-1402-sorting-krp3/ diff --git a/tests/snapshots/view-120.txt b/tests/snapshots/view-120.txt index 887e4e2c..ee861c36 100644 --- a/tests/snapshots/view-120.txt +++ b/tests/snapshots/view-120.txt @@ -4,7 +4,7 @@ ⣴⠙⢦ ⡴⠊⣧ Gates pytest -q test_sort.py · speed regress 5% ⠙⠦⠬⠤⢤⡀⢀⡤⠄⡇⠴⠋ Observe bench (speed ↑, mem_mb ↓) ⠘⢦⣤⠵⠫⣤⡴⠃ Scope editable: sort.py - Budget 7 iterations · $10.00 · 30m each + Budget to iteration 7 · $10.00 run total · 30m each ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── time cost speed ↑ mem_mb ↓ · base 46.9 120 diff --git a/tests/snapshots/view-80.txt b/tests/snapshots/view-80.txt index 8638c599..d0f52f98 100644 --- a/tests/snapshots/view-80.txt +++ b/tests/snapshots/view-80.txt @@ -4,7 +4,7 @@ ⣴⠙⢦ ⡴⠊⣧ Gates pytest -q test_sort.py · speed regress 5% ⠙⠦⠬⠤⢤⡀⢀⡤⠄⡇⠴⠋ Observe bench (speed ↑, mem_mb ↓) ⠘⢦⣤⠵⠫⣤⡴⠃ Scope editable: sort.py - Budget 7 iterations · $10.00 · 30m each + Budget to iteration 7 · $10.00 run total · 30m each ──────────────────────────────────────────────────────────────────────────── time cost speed ↑ mem_mb ↓ · base 46.9 120 diff --git a/tests/snapshots/view-live-120.txt b/tests/snapshots/view-live-120.txt index 388b2856..957b1998 100644 --- a/tests/snapshots/view-live-120.txt +++ b/tests/snapshots/view-live-120.txt @@ -4,7 +4,7 @@ ⣴⠙⢦ ⡴⠊⣧ Gates pytest -q test_sort.py · speed regress 5% ⠙⠦⠬⠤⢤⡀⢀⡤⠄⡇⠴⠋ Observe bench (speed ↑, mem_mb ↓) ⠘⢦⣤⠵⠫⣤⡴⠃ Scope editable: sort.py - Budget 7 iterations · $10.00 · 30m each + Budget to iteration 7 · $10.00 run total · 30m each ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── time cost speed ↑ mem_mb ↓ · base 46.9 120 diff --git a/tests/snapshots/view-live-80.txt b/tests/snapshots/view-live-80.txt index ce5674f2..812596f9 100644 --- a/tests/snapshots/view-live-80.txt +++ b/tests/snapshots/view-live-80.txt @@ -4,7 +4,7 @@ ⣴⠙⢦ ⡴⠊⣧ Gates pytest -q test_sort.py · speed regress 5% ⠙⠦⠬⠤⢤⡀⢀⡤⠄⡇⠴⠋ Observe bench (speed ↑, mem_mb ↓) ⠘⢦⣤⠵⠫⣤⡴⠃ Scope editable: sort.py - Budget 7 iterations · $10.00 · 30m each + Budget to iteration 7 · $10.00 run total · 30m each ──────────────────────────────────────────────────────────────────────────── time cost speed ↑ mem_mb ↓ · base 46.9 120 diff --git a/tests/snapshots/view-unreadable-80.txt b/tests/snapshots/view-unreadable-80.txt index dd23d534..b74f3b83 100644 --- a/tests/snapshots/view-unreadable-80.txt +++ b/tests/snapshots/view-unreadable-80.txt @@ -4,7 +4,7 @@ ⣴⠙⢦ ⡴⠊⣧ Gates pytest -q test_sort.py · speed regress 5% ⠙⠦⠬⠤⢤⡀⢀⡤⠄⡇⠴⠋ Observe bench (speed ↑, mem_mb ↓) ⠘⢦⣤⠵⠫⣤⡴⠃ Scope editable: sort.py - Budget 7 iterations · $10.00 · 30m each + Budget to iteration 7 · $10.00 run total · 30m each ──────────────────────────────────────────────────────────────────────────── ! The run's history can't be read: no iterations to show. diff --git a/tests/test_agents.py b/tests/test_agents.py index 9884e98e..03c1b33b 100644 --- a/tests/test_agents.py +++ b/tests/test_agents.py @@ -728,10 +728,10 @@ def fake_run_process(**kwargs): def test_a_timeout_is_an_error_with_unknown_cost(self, monkeypatch, tmp_path): result, events = self._run(monkeypatch, tmp_path, exit_code=124, timed_out=True) - assert not result.success and result.error == "timed out after 4 seconds" + assert not result.success and result.error == "timed out after 4s" assert "cost_usd" not in result.usage and result.usage["partial_cost_usd"] == 0.25 assert "timed out" in result.usage["cost_unavailable_reason"] - assert any(event.text == "Agent timed out after 4 seconds" for event in events) + assert any(event.text == "Agent timed out after 4s" for event in events) def test_a_failed_call_says_its_status_and_keeps_its_cost(self, monkeypatch, tmp_path): result, _ = self._run(monkeypatch, tmp_path, exit_code=3) @@ -741,3 +741,25 @@ def test_a_failed_call_says_its_status_and_keeps_its_cost(self, monkeypatch, tmp def test_a_finished_call_is_priced(self, monkeypatch, tmp_path): result, _ = self._run(monkeypatch, tmp_path) assert result.success and result.error is None and result.usage["cost_usd"] == 0.25 + + +@pytest.mark.parametrize("agent_class,cli", [(ClaudeCodeAgent, "claude-code"), (CodexAgent, "codex"), + (OpenCodeAgent, "opencode")]) +@pytest.mark.parametrize("line", ["0", "[1]", "true", "null", '"text"']) +def test_a_json_line_that_isnt_an_object_is_raw_output(agent_class, cli, line): + # A wrapper script's stderr (a PID, a count) parses as JSON but is no event. + events = _collect_events(agent_class(config=AgentConfig(cli=cli)), line) + assert [(event.kind, event.text) for event in events] == [(AgentEventKind.RAW, line)] + + +def test_a_claude_code_wrapper_printing_a_number_on_stderr_still_finishes(tmp_path, monkeypatch): + fake = tmp_path / "claude" + result_line = json.dumps({"type": "result", "subtype": "success", "is_error": False, "result": "done", + "duration_ms": 10, "total_cost_usd": 0.5, "usage": {}}) + fake.write_text(f"#!/bin/sh\necho 0 >&2\necho '{result_line}'\n") + fake.chmod(0o755) + monkeypatch.setenv("AUTOHELIX_CLAUDE_CODE_CMD", str(fake)) + agent = ClaudeCodeAgent(config=AgentConfig(cli="claude-code", timeout=20)) + result = agent.run(copy_path=tmp_path, prompt="test", iteration=1, log_path=tmp_path / "agent.log", + event_callback=lambda event: None) + assert result.success and result.usage["cost_usd"] == 0.5 diff --git a/tests/test_cli_entry.py b/tests/test_cli_entry.py index 5b815abb..c3767b22 100644 --- a/tests/test_cli_entry.py +++ b/tests/test_cli_entry.py @@ -568,6 +568,8 @@ def test_the_template_is_a_valid_config_once_it_has_a_goal(project): config = load_config(project, config_file=path) assert [i for i in config.validate() if i.level == "error"] == [] assert config.title == "Make main.py faster." + # No live model: changing only `cli:` must not keep a Claude model name for Codex. + assert config.agent.model is None # --- the docs in the package ------------------------------------------------------------- @@ -626,3 +628,12 @@ def test_the_old_claude_variable_refuses_the_session(project, monkeypatch, execs result = entry(input="\n") assert result.exit_code == 1 and not execs assert "AUTOHELIX_CLAUDE_CMD is now AUTOHELIX_CLAUDE_CODE_CMD" in flat(result.output) + + +def test_the_package_version_has_one_home(): + """`__version__` was a second, hand-written copy of pyproject.toml's version.""" + import autohelix + from autohelix import terminal + + assert autohelix.__version__ == terminal.version() + assert "__version__ = \"" not in Path(autohelix.__file__).read_text() diff --git a/tests/test_cli_lifecycle.py b/tests/test_cli_lifecycle.py index de133220..1fb9164b 100644 --- a/tests/test_cli_lifecycle.py +++ b/tests/test_cli_lifecycle.py @@ -161,8 +161,17 @@ def test_ids_sort_by_start_and_commands_accept_the_suffix(project, tmp_path, mon assert paths.run_id.startswith(time.strftime("%Y%m%d-")) and paths.run_id.split("-")[2] == "perf" result = cli(project, "view", short_id(paths.run_id), "--json") assert result.exit_code == 0 and json.loads(result.stdout)["run"]["id"] == paths.run_id - result = cli(project, "view", "perf", "--json") - assert result.exit_code == 1 and "names aren't ids" in result.output + short = short_id(paths.run_id) + for args in (["view", "perf", "--json"], ["land", "perf"], ["hint", "--run", "perf", "x"], ["stop", "perf"]): + result = cli(project, *args) # a config name: the run it means, named + assert result.exit_code == 1, args + assert f"perf is an experiment, not a run: its latest run is {short}; use {short}." in " ".join( + result.output.split()), (args, result.output) + assert cli(project, "archive", short).exit_code == 0 + result = cli(project, "archive", "--undo", "perf") # only archived runs: still named + assert f"its latest run is {short} (archived); use {short}." in " ".join(result.output.split()) + result = cli(project, "view", "nope", "--json") # real ids, not a made-up one + assert f"Use a run id or its last part (the latest: {short});" in " ".join(result.output.split()) (tmp_path / "bench").mkdir() monkeypatch.chdir(tmp_path) result = cli(project, "view", "bench", "--json") @@ -426,7 +435,7 @@ def run(self, *args, **kwargs): return result monkeypatch.setattr(MockAgent, "run", run) - configure(project, gates=["ask: Is it fine?"]) + configure(project, gates=[{"ask": "Is it fine?"}]) # an `ask:` entry (a string would be a shell command) result = cli(project, "run", "--no-report", "--cost", "5") assert result.exit_code == 0, result.output paths = latest_run(project) @@ -597,3 +606,22 @@ def test_the_segment_log_survives_damage_and_reports_open_segments(tmp_path): def test_n_help_says_more_only_on_resume(project): assert "Run up to N iterations" in cli(project, "run", "--help").output assert "Run up to N more iterations" in cli(project, "resume", "--help").output + + +def test_run_help_forks_on_a_branch_and_words_previous_as_the_code_does(project): + """The help's fork recipe was a detached `git checkout`, a run that can't land.""" + text = " ".join(cli(project, "run", "--help").output.split()) + assert "git switch -c autohelix/" in text and "git checkout autohelix/`" not in text + assert "until the entry succeeds here (normally the baseline)" in text + + +def test_the_run_screens_baseline_row_has_its_judges_cost_as_view_shows_it(project): + """The baseline row came from a fresh result without the judges' calls: no cost on + the `run` screen, `$0.05` in `view` for the same row.""" + configure(project, gates=[{"ask": "Is it fine?"}]) + result = cli(project, "run", "--no-report") + assert result.exit_code == 0, result.output + base = next(line for line in result.output.splitlines() if " base " in line) + shown = cli(project, "view", "--once", short_id(latest_run(project).run_id)) + assert "$" in base and base.strip() in [line.strip() for line in shown.output.splitlines()], ( + base, shown.output) diff --git a/tests/test_config_lookup.py b/tests/test_config_lookup.py index e940e03e..5f9b8413 100644 --- a/tests/test_config_lookup.py +++ b/tests/test_config_lookup.py @@ -11,7 +11,7 @@ from autohelix.cli import main from autohelix.config import ConfigNotFound, config_name, find_config, project_configs, run_command -from autohelix.judge import CONFIG_ENV, load_base_config +from autohelix.judge import CONFIG_ENV, base_config from autohelix.harness import Harness from autohelix.history import History from autohelix.runs import NoRunToResume, RunPaths, git, load_run_config, new_run_name, select_run, short_id @@ -387,9 +387,9 @@ def test_run_without_a_commit_refuses_and_leaves_nothing(tmp_path, monkeypatch): def test_ask_and_review_read_the_only_config_in_the_folder(tmp_path, monkeypatch): monkeypatch.delenv(CONFIG_ENV, raising=False) write(tmp_path / "autohelix" / "perf" / "config.yaml", yaml.safe_dump({"agent": {"cli": "codex", "model": "m"}})) - assert (load_base_config(tmp_path).cli, load_base_config(tmp_path).model) == ("codex", "m") + assert (base_config(tmp_path)[0].cli, base_config(tmp_path)[0].model) == ("codex", "m") write(tmp_path / "autohelix" / "fast" / "config.yaml", yaml.safe_dump({"agent": {"cli": "codex"}})) - assert load_base_config(tmp_path).cli == "claude-code" # ambiguous: the defaults, not an error + assert base_config(tmp_path)[0].cli == "claude-code" # ambiguous: the defaults, not an error def _answers(path, answer): diff --git a/tests/test_console.py b/tests/test_console.py index 5a779fac..38c22281 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -219,8 +219,8 @@ def test_metric_gate_rejection_names_the_iteration_it_compares_with(): def test_a_timed_out_agent_row(): table = Table.of(Config.from_dict({"goal": "g", "agent": {"timeout": "30m"}}), 100) - [_, row] = table.add(Row(4, False, reason="Iteration 4 agent failed: timed out after 30 minutes", - agent_error="timed out after 30 minutes")) + [_, row] = table.add(Row(4, False, reason="Iteration 4 agent failed: timed out after 30m", + agent_error="timed out after 30m")) assert row.plain.rstrip().endswith("agent timed out (30m)") @@ -363,7 +363,11 @@ def test_an_error_heads_the_ending_then_landing_and_the_run_page(project): totals = next(i for i, line in enumerate(ending) if line.startswith(" run ")) assert " ".join(" ".join(ending[:totals]).split()) == f"Error {message}" # wrapped, not cut # Run from outside the project: the run's folder is absolute, as the page is. - assert [line.split()[0] for line in ending[totals:]] == ["run", "landed", "next", "autohelix", "folder", "page"] + # The next commands: a new run and delete, as the error says (a failed first baseline). + assert [line.split()[0] for line in ending[totals:]] == ["run", "landed", "next", "autohelix", "autohelix", + "folder", "page"] + assert [line.split()[:3] for line in ending[totals + 2:totals + 5]] == [ + ["next", "autohelix", "view"], ["autohelix", "run", NAME], ["autohelix", "delete", short]] assert ending[-2].split() == ["folder", f"{project / '.autohelix' / 'runs' / run_id}/"] assert result.output.count("Error") == 1 # not repeated by the CLI diff --git a/tests/test_docker.py b/tests/test_docker.py new file mode 100644 index 00000000..2a0645ce --- /dev/null +++ b/tests/test_docker.py @@ -0,0 +1,14 @@ +"""docker/run.sh, without Docker: what it refuses before starting a container.""" + +import subprocess +from pathlib import Path + +RUN = Path(__file__).resolve().parents[1] / "docker" / "run.sh" + + +def test_a_missing_env_script_refuses_instead_of_running_without_credentials(tmp_path): + result = subprocess.run(["bash", str(RUN), "--env", str(tmp_path / "typo.sh"), "run"], cwd=tmp_path, + capture_output=True, text=True, timeout=30, + env={"PATH": "/usr/bin:/bin"}) # no docker on PATH: it must stop before that + assert result.returncode == 1 and result.stderr == f"env script not found: {tmp_path / 'typo.sh'}\n" + diff --git a/tests/test_docs_prompts.py b/tests/test_docs_prompts.py index 0a4871fc..55f9be62 100644 --- a/tests/test_docs_prompts.py +++ b/tests/test_docs_prompts.py @@ -12,7 +12,7 @@ from autohelix.config import load_config from autohelix.history import History, IterationResult from autohelix.judge import Target, build_system_prompt, describe_change -from autohelix.prompt_template import build_prompt_variables, load_template, render_template +from autohelix.prompt_template import SAMPLE_RECORDS, build_prompt_variables, load_template, render_template PHASES = Path(__file__).resolve().parents[1] / "docs" / "phases.md" @@ -29,24 +29,7 @@ "scope": {"editable": ["sort.py"]}, "agent": {"timeout": "30m"}, } -OBSERVED = [{"name": "bench", "ok": True, "error": None, "metrics": {"speed": 10.0}}, - {"name": "clarity", "ok": True, "error": None, "metrics": {}}] -RECORDS = [ - {"iteration": 0, "accepted": True, "metrics": {"speed": 10.0}, "reason": "baseline", - "gates": [{"text": "pytest -q", "kind": "command", "passed": True}, - {"text": "speed regress 5%", "kind": "metric", "passed": None}], - "observe": OBSERVED}, - {"iteration": 1, "accepted": True, "metrics": {"speed": 14.2}, "summary": "Insertion sort for short runs", - "gates": [{"text": "pytest -q", "kind": "command", "passed": True}, - {"text": "speed regress 5%", "kind": "metric", "passed": True}], - "observe": [{**OBSERVED[0], "metrics": {"speed": 14.2}}, OBSERVED[1]]}, - {"iteration": 2, "accepted": False, "reason": "gate failed: pytest -q", - "failure_output": "FAILED test_sort.py::test_negative_numbers - assert [-1, -3] == [-3, -1]", - "summary": "Radix sort", "discarded": ["test_sort.py"], "tree": "abc", - "rejected_ref": "refs/autohelix-rejected/20261118-1205-sort-x7k2/2", - "gates": [{"text": "pytest -q", "kind": "command", "passed": False}, - {"text": "speed regress 5%", "kind": "metric", "passed": None}]}, -] +RECORDS = SAMPLE_RECORDS # the sample a custom template is validated against def main_agent_prompt(tmp_path: Path) -> str: diff --git a/tests/test_evaluation.py b/tests/test_evaluation.py index 616353d7..fd1ac45e 100644 --- a/tests/test_evaluation.py +++ b/tests/test_evaluation.py @@ -5,7 +5,9 @@ import json import os +import re import subprocess +import time import pytest import yaml @@ -91,6 +93,19 @@ def test_failing_gate_skips_later_gates_and_observe(project, log): assert [g["passed"] for g in baseline.gates] == [True, True, True, None] +def test_a_long_output_line_is_cut_in_the_record_and_the_next_prompt(project): + # A gate ending with one 1.5 MB line made the next prompt too large to start the agent. + _configure(project, gates=['[ "$AUTOHELIX_ITERATION" = 0 ] || ' + 'python3 -c "print(\'x\' * 1500000); raise SystemExit(1)"']) + records = _run(project, 2) + assert [r.accepted for r in records] == [True, False, False] + assert records[1].failure_output == "x" * 500 + "…" + assert records[1].gates[0]["output"] == records[1].failure_output + paths = latest_run(project) + assert len((paths.iteration_dir(2) / "prompt.md").read_text()) < 20_000 + assert len((paths.iteration_dir(1) / "gates" / "1" / "stdout.txt").read_bytes()) > 1_000_000 # capped 64 KB + 1 MB + + def test_metric_gate_failure_after_an_entry_skips_the_next(project, log): _configure(project, gates=[{"metric": "speed", "regress": "5%"}], observe=[ {"name": "bench", "command": 'if [ "$AUTOHELIX_ITERATION" = 0 ]; then echo "##autohelix[speed=10]"; ' @@ -412,6 +427,63 @@ def test_failed_command_entry_at_the_baseline_is_a_setup_error(project): assert not record.accepted and record.observe[0]["error"] == "exited 1" +@pytest.mark.parametrize("gate,said", [ + ("pytset -q", "gate `pytset -q` could not run (exit 127: command not found): "), + ("./.gitignore", "gate `./.gitignore` could not run (exit 126: not executable): "), + ("autohelix/lib/check.sh", "gate `autohelix/lib/check.sh` could not run (exit 127: command not found): "), + ("sh -c 'exit 127'", "gate `sh -c 'exit 127'` could not run (exit 127: command not found)"), +]) +def test_a_gate_that_cant_run_at_the_baseline_is_a_setup_error(project, gate, said): + """Every iteration would be paid for and rejected the same way; `autohelix/` is + frozen, so the agent can't create a missing helper there either.""" + _configure(project, gates=[gate], scope={"editable": ["hello.py", "checks/"]}) + with pytest.raises(RuntimeError, match="^Baseline setup error: " + re.escape(said)) as error: + Harness(project, verbose=False).run(Budget(until=1), report=False) + assert "Fix it and run `autohelix run demo` again" in str(error.value) + [record] = History(project, latest_run(project).run_id).load() + assert not record.accepted and record.reason.startswith("baseline failed: Baseline setup error: gate ") + + +def test_a_gate_in_an_ignored_folder_is_a_setup_error_also_without_editable(project): + """No `editable:` lets the agent write any path, but not an ignored one: `.venv/` + never reaches a copy, so the gate would fail every iteration.""" + (project / ".gitignore").write_text(".autohelix/\n.venv/\n") + git(project, "commit", "-qam", "ignore .venv") + _configure(project, gates=[".venv/bin/pytest -q"]) + with pytest.raises(RuntimeError, match=r"^Baseline setup error: gate `\.venv/bin/pytest -q` could not run " + r"\(exit 127: command not found\)"): + Harness(project, verbose=False).run(Budget(until=1), report=False) + + +def test_a_missing_gate_script_the_agent_may_create_is_left_to_it(project): + _configure(project, gates=["./checks/new_check.sh"], scope={"editable": ["hello.py", "checks/"]}) + records = _run(project, 1) + assert records[0].accepted and records[0].gates[0]["return_code"] == 127 # a note, as any failing gate + assert not records[1].accepted + + +def test_an_ask_gate_without_an_answer_at_the_baseline_is_a_setup_error(project): + _configure(project, gates=[{"ask": "Does it keep the API?"}]) + config = yaml.safe_load(config_file(project).read_text()) + config["agent"]["mock"]["judge_change_file"] = "hello.py" + write_config(project, yaml.safe_dump(config, sort_keys=False)) + with pytest.raises(RuntimeError, match=r"^Baseline setup error: gate `ask: Does it keep the API\?` got no " + r"answer \(autohelix ask: no valid answer: the judge changed files"): + Harness(project, verbose=False).run(Budget(until=1), report=False) + + +def test_an_ask_gate_answering_no_at_the_baseline_continues(project): + _configure(project, gates=[{"ask": "Is it fast yet?"}]) + config = yaml.safe_load(config_file(project).read_text()) + config["agent"]["mock"]["judge_answer"] = "no" + write_config(project, yaml.safe_dump(config, sort_keys=False)) + harness = Harness(project, verbose=False) + harness._capture_baseline() + harness.close() + [baseline] = History(project, latest_run(project).run_id).load() + assert baseline.accepted and baseline.gates[0]["return_code"] == 1 + + def test_failed_entry_without_metrics_at_the_baseline_continues(project): _configure(project, gates=["exit 1", {"metric": "speed", "regress": "5%"}], observe=[ {"name": "notes", "command": "echo nothing; exit 4"}, @@ -577,6 +649,19 @@ def test_run_command_kills_background_children_after_a_normal_exit(tmp_path): assert not late.exists() +def test_a_background_child_holding_the_output_ends_with_the_shell(tmp_path): + # `./server & curl ...`: the child keeps stdout and stderr open after the shell exits. + from autohelix.checks import run_command + + late = tmp_path / "late" + start = time.monotonic() + result = run_command(f"(sleep 2; touch {late}) & sleep 30 & echo started; exit 3", tmp_path, timeout=20) + assert time.monotonic() - start < 5 + assert not result.timed_out and result.return_code == 3 and result.output == "started\n" + subprocess.run(["sleep", "3"]) + assert not late.exists() # the group went with the shell + + def test_metrics_file_is_not_passed_to_gates_and_observe(project, log, monkeypatch): monkeypatch.setenv("AUTOHELIX_METRICS", "/nowhere") _configure(project, gates=[f'echo "gate ${{AUTOHELIX_METRICS-unset}}" >> {log}'], diff --git a/tests/test_events.py b/tests/test_events.py index 7fc2034d..ba370aed 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -223,8 +223,8 @@ def test_cursors_round_trip_and_bad_ones_are_refused(tmp_path): for bad in ["", "nonsense", "2.", "2.!!!", good[:-3], "2." + "A" * 40]: with pytest.raises(ValueError, match="not a cursor"): decode_cursor(bad) - with pytest.raises(ValueError, match="older AutoHelix.*no --after"): - decode_cursor("1." + good[2:]) # the previous format's: says so + with pytest.raises(ValueError, match="not a cursor"): + decode_cursor("1." + good[2:]) # the previous format's, as any other import base64 import zlib for payload in [b"[]", b'{"r": []}', b'{"r": {"x/y": [1, 2]}}', b'{"r": {"a": [1, 2, 3]}}', b'{"r": {"a": [1]}}', diff --git a/tests/test_example_scripts.py b/tests/test_example_scripts.py index e883cedd..4282a177 100644 --- a/tests/test_example_scripts.py +++ b/tests/test_example_scripts.py @@ -171,3 +171,48 @@ class Completed: calls = read_usage(usage) assert [call["cost_usd"] for call in calls] == [0.25, 0.25] assert all(call["source"] == "workflow-benchmark" for call in calls) + + +# --- algotune: collect.py reads what a run stores --- + +def test_algotune_collect_reads_the_runs_base_commit_and_each_iterations_files(tmp_path): + """collect.py read `run.json`'s `base`, a key no run has: a no-op best iteration's + code was None. Its files list is the iteration's own, not everything since the base.""" + project = tmp_path / "task" / "project" + project.mkdir(parents=True) + + def git(*args): + return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", + *args], cwd=project, capture_output=True, text=True, check=True).stdout.strip() + + git("init", "-q") + (project / "a.py").write_text("a\n") + git("add", "a.py") + git("commit", "-qm", "base") + base = git("rev-parse", "HEAD") + (project / "b.py").write_text("b\n") + git("add", "b.py") + git("commit", "-qm", "one") + one = git("rev-parse", "HEAD") + (project / "c.py").write_text("c\n") + git("add", "c.py") + git("commit", "-qm", "two") + two = git("rev-parse", "HEAD") + run = project / ".autohelix" / "runs" / "20261115-1402-task-krp3" + run.mkdir(parents=True) + (run / "run.json").write_text(json.dumps({"base_commit": base})) + records = [{"iteration": 0, "accepted": True, "metrics": {"speedup": 1.0}}, + {"iteration": 1, "accepted": True, "metrics": {"speedup": 3.0}}, # a no-op accept: no commit + {"iteration": 2, "accepted": True, "metrics": {"speedup": 2.0}, "commit": one}, + {"iteration": 3, "accepted": True, "metrics": {"speedup": 2.5}, "commit": two}] + (run / "history.jsonl").write_text("".join(json.dumps(r) + "\n" for r in records)) + sys.path.insert(0, str(EXAMPLES / "algotune")) + try: + collect = runpy.run_path(str(EXAMPLES / "algotune" / "collect.py")) + rescore = runpy.run_path(str(EXAMPLES / "algotune" / "rescore.py")) + finally: + sys.path.remove(str(EXAMPLES / "algotune")) + runs = collect["autohelix_runs"](str(tmp_path / "task")) + assert runs[0]["base"] == base + assert [it.get("files") for it in runs[0]["iterations"]] == [None, None, ["b.py"], ["c.py"]] + assert rescore["best_iteration"](runs, limit=3)["code"] == base # the no-op best: the run's base diff --git a/tests/test_exit_codes.py b/tests/test_exit_codes.py index f1aedce1..d6f2b2e2 100644 --- a/tests/test_exit_codes.py +++ b/tests/test_exit_codes.py @@ -3,6 +3,8 @@ as soon as its command holds the run's lock: a start its checks refuse is a recorded segment that failed.""" +import json + import pytest from autohelix.events import Watcher @@ -46,6 +48,49 @@ def test_a_resume_whose_preflight_fails_exits_1_and_records_a_failed_segment(pro assert read_run_status(project, paths.run_id)["segment"] == second["segment"] == 2 +def test_a_resume_after_the_baseline_checks_the_agents_command_first(project, tmp_path, monkeypatch): + """A missing agent executable on a later resume (another shell, another machine) is + refused before an iteration is spent, as on the first start.""" + agent = tmp_path / "bin" / "claude" + agent.parent.mkdir() + agent.write_text("#!/bin/sh\nexit 1\n") + agent.chmod(0o755) + monkeypatch.setenv("AUTOHELIX_CLAUDE_CODE_CMD", str(agent)) + configure(project, agent={"cli": "claude-code"}) + cli(project, "run", "-n", "1", "--no-report") + paths = latest_run(project) + assert [r.iteration for r in History(project, paths.run_id).load()] == [0, 1] + agent.unlink() + result = cli(project, "resume", short_id(paths.run_id), "-n", "1", "--no-report") + assert result.exit_code == 1 and "Preflight checks failed" in result.output, result.output + assert str(agent) in "".join(result.output.split()) + assert [r.iteration for r in History(project, paths.run_id).load()] == [0, 1] # nothing spent + + +@pytest.mark.parametrize(("status", "kind", "failed"), [ + (503, "agent", 3), # an outage is an ordinary failure: three in a row end the run + (429, "agent", 3), + (401, "infrastructure", 1), # a rejected key stops it at once +]) +def test_only_401_and_403_stop_a_run_at_once(project, tmp_path, monkeypatch, status, kind, failed): + """A Claude Code that answers every call with an API error, through the real backend.""" + result_line = json.dumps({"type": "result", "subtype": "success", "is_error": True, "terminal_reason": "api_error", + "api_error_status": status, "result": f"API Error: {status}", "usage": {}}) + agent = tmp_path / "bin" / "claude" + agent.parent.mkdir() + agent.write_text(f"#!/bin/sh\necho '{result_line}'\nexit 1\n") + agent.chmod(0o755) + monkeypatch.setenv("AUTOHELIX_CLAUDE_CODE_CMD", str(agent)) + configure(project, agent={"cli": "claude-code"}) + result = cli(project, "run", "-n", "5", "--no-report") + assert result.exit_code == 1, result.output + paths = latest_run(project) + records = History(project, paths.run_id).load() + assert [r.accepted for r in records] == [True] + [False] * failed + assert {r.agent_error for r in records[1:]} == {f"API Error: {status}"} + assert read_run_status(project, paths.run_id)["stop_reason"]["kind"] == kind + + def test_an_interrupt_in_the_loop_exits_130(project, monkeypatch): def interrupted(self, n): raise KeyboardInterrupt @@ -72,6 +117,18 @@ def interrupted(self): assert segment["state"] == "interrupted" +def test_an_interrupted_baseline_is_recorded_as_interrupted(project, monkeypatch): + """Not "baseline failed: " with nothing after it (str of a KeyboardInterrupt).""" + def interrupted(self, *args, **kwargs): + raise KeyboardInterrupt + + monkeypatch.setattr(Harness, "_evaluate", interrupted) + result = cli(project, "run", "-n", "1", "--no-report") + assert result.exit_code == 130, result.output + [record] = History(project, latest_run(project).run_id).load() + assert (record.iteration, record.accepted, record.reason) == (0, False, "baseline interrupted") + + def test_no_run_to_resume_exits_1(project): result = cli(project, "resume") assert result.exit_code == 1 and "No run to resume for autohelix/demo/config.yaml" in result.output diff --git a/tests/test_experiment_snapshot.py b/tests/test_experiment_snapshot.py index b7c15921..08eeb6d8 100644 --- a/tests/test_experiment_snapshot.py +++ b/tests/test_experiment_snapshot.py @@ -422,7 +422,8 @@ def test_a_changed_folder_refuses(project, folder, run_of_folder, edit, words): message = " ".join(result.output.split()) assert f"autohelix/exp/ changed since run {short} started ({words}); the run keeps the experiment folder" in message assert f"`autohelix run exp --import {short}`" in message - assert "restore the files." in message + remedy = "remove the added files." if words.startswith("added") else "restore the files." # added: not restored + assert message.endswith(f"To continue this run, {remedy}") assert History(project, run_of_folder.run_id).get_last_iteration() == 1 # nothing ran @@ -432,7 +433,9 @@ def test_several_changes_are_named_together(project, folder, run_of_folder): (folder / "b.txt").write_text("b\n") result = resumed(project, run_of_folder) assert result.exit_code == 1 - assert "(changed: data.txt; added: b.txt; removed: render.sh)" in " ".join(result.output.split()) + message = " ".join(result.output.split()) + assert "(changed: data.txt; added: b.txt; removed: render.sh)" in message + assert message.endswith("To continue this run, restore the files and remove the added ones.") def test_a_folder_that_can_no_longer_be_stored_refuses(project, folder, run_of_folder, tmp_path): @@ -852,3 +855,18 @@ def test_the_advice_follows_what_the_snapshot_stores(project, folder): "`$AUTOHELIX_EXPERIMENT/lib/m.py`."] + + +def test_the_remedy_does_not_read_file_names(project, folder): + """A changed file whose name looks like the message's own `; added: ` is still only + a change to restore.""" + odd = folder / "x; added: y.txt" + odd.write_text("a\n") + assert cli(project, "run", "exp", "-n", "1", "--no-report").exit_code == 0 + [(paths, _)] = project_runs(project) + odd.write_text("b\n") + result = resumed(project, paths) + assert result.exit_code == 1 + message = " ".join(result.output.split()) + assert "(changed: x; added: y.txt)" in message + assert message.endswith("To continue this run, restore the files.") diff --git a/tests/test_formatting.py b/tests/test_formatting.py index c5a798a9..f759abb1 100644 --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -12,7 +12,7 @@ def test_known_zero_is_distinct_from_unknown_cost(): def test_complete_partial_and_unavailable_totals(): assert format_total_cost([{"cost_usd": 0.25}, {"cost_usd": 0}]) == "$0.25" - assert format_total_cost([{"cost_usd": 0.25}, {}]) == "$0.25 (incomplete)" + assert format_total_cost([{"cost_usd": 0.25}, {}]) == "$0.25+" assert format_total_cost([{}, {"cost_usd": None}]) == "cost unavailable" @@ -31,7 +31,7 @@ def test_an_unavailable_total_says_why_when_its_calls_agree(): assert format_total_cost([{"cost_unavailable_reason": "a"}, {"cost_unavailable_reason": "b"}]) == "cost unavailable" assert format_total_cost([{"cost_unavailable_reason": "a"}, {}]) == "cost unavailable" # A known part: incomplete, as before (no reason). - assert format_total_cost([{"cost_usd": 0.25}, {"cost_unavailable_reason": "a"}]) == "$0.25 (incomplete)" + assert format_total_cost([{"cost_usd": 0.25}, {"cost_unavailable_reason": "a"}]) == "$0.25+" @pytest.mark.parametrize("reason", [["a"], {"a": 1}, 3]) diff --git a/tests/test_groups.py b/tests/test_groups.py index f82de199..c16ac1cf 100644 --- a/tests/test_groups.py +++ b/tests/test_groups.py @@ -96,7 +96,7 @@ def test_group_and_landing_mode_are_stored_kept_and_changed(project): assert identity(grouped)["group"] == "other" and identity(grouped)["land"] == "manual" result = cli(project, "resume", short_id(run_id), "-n", "1", "--no-report", "--group", "", "--land", "auto") assert result.exit_code == 0, result.output - assert "leaves group other" in result.output and re.search(r"^ landed \d+ commits? on main$", result.output, re.M) + assert "leaves group other" in result.output and re.search(r"^ landed \d+ commits? on main \(this segment\)$", result.output, re.M) data = identity(grouped) assert "group" not in data and data["land"] == "auto" diff --git a/tests/test_hardening.py b/tests/test_hardening.py index 558607b1..1c76e23b 100644 --- a/tests/test_hardening.py +++ b/tests/test_hardening.py @@ -16,7 +16,7 @@ from autohelix.config import Config from autohelix.harness import Budget, AutoHelixRunError, Harness from autohelix.history import History, IterationResult -from autohelix.prompt_template import build_prompt_variables, load_template, render_template, unknown_variables +from autohelix.prompt_template import build_prompt_variables, load_template, render_template from autohelix.workspace import ITERATION_DIR from tests.helpers import CONFIG, config_file, git, latest_run, write_config @@ -352,19 +352,48 @@ def act(copy_dir, iteration): assert body.index("w" * 500) < body.index("AutoHelix-Run:") -def test_unknown_template_variables(): - template = ("{{ goal }} {{ constraints }} {% for g in gates %}{{ g.text }}{% endfor %} {{ range(2) }} " - "{% if history_summary %}{% endif %}{% set local = 1 %}{{ local }}") - assert unknown_variables(template) == ["constraints", "history_summary"] +def _refused(project, capsys) -> str: + """The config errors a new run prints, refused before anything is written.""" + with pytest.raises(SystemExit, match="Config validation failed"): + Harness(project, verbose=False, land_mode="manual") + assert not (project / ".autohelix" / "runs").exists() + return " ".join(capsys.readouterr().out.split()) -def test_a_custom_template_with_old_variables_warns_at_run_start(repo, capsys): +def test_unknown_template_variables_are_a_config_error(repo, capsys): + """Old names (`constraints`, `history_summary`) rendered empty: the agent got a prompt + without them. Loop, `set` names and Jinja globals are not unknown.""" project = _project(repo) - _prompt(project, "Goal: {{ goal }}\n{{ history_summary }}\n") + _prompt(project, "{{ goal }} {{ constraints }} {% for g in gates %}{{ g.text }}{{ loop.index }}{% endfor %} " + "{{ range(2) | list }} {% if history_summary %}{% endif %}{% set local = 1 %}{{ local }}\n") + _configure(project, repo, prompt_template="prompt.md") + assert ("prompt_template prompt.md uses variables the prompt doesn't have: constraints, history_summary. " + "See docs/concepts.md#prompt for the names.") in _refused(project, capsys) + + +def test_a_template_that_fails_to_render_is_a_config_error(repo, capsys): + """It used to fail iteration 1, after the baseline, and the stored template kept the + run from taking the fix.""" + project = _project(repo) + _prompt(project, "{{ goal }}{% if last %}{{ last.gates.x.y }}{% endif %}\n") + _configure(project, repo, prompt_template="prompt.md") + assert "prompt_template prompt.md could not be rendered:" in _refused(project, capsys) + + +def test_a_template_branch_over_observe_items_is_rendered_too(repo, capsys): + """After an accepted iteration, `last.observe` has items: that branch is rendered.""" + project = _project(repo) + _prompt(project, "{{ goal }}{% for item in last.observe %}{{ item.name.x.y }}{% endfor %}\n") + _configure(project, repo, prompt_template="prompt.md") + assert "prompt_template prompt.md could not be rendered:" in _refused(project, capsys) + + +def test_a_good_custom_template_passes(repo): + project = _project(repo) + _prompt(project, "{{ goal }}{% if last %}{% for g in last.gates %}{{ g.text }} {{ g.status }}{% endfor %}" + "{% for o in last.observe %}{{ o.name }}{% endfor %}{% endif %} {{ notes_path }}\n") _configure(project, repo, prompt_template="prompt.md") Harness(project, verbose=False, land_mode="manual").run(Budget(until=1), report=False) - out = capsys.readouterr().out - assert "prompt.md uses variables the prompt doesn't have" in out and "history_summary" in out def test_status_names_the_running_observe_entry(repo): @@ -476,16 +505,23 @@ def test_run_start_warnings_wrap_under_their_label(repo, capsys): project = _project(repo) (project / ".autohelix").mkdir(exist_ok=True) (project / ".autohelix" / "prompt.md").write_text("old\n") - _prompt(project, "Goal: {{ goal }}; notes in .autohelix/notes/iter-1.md\n") - _configure(project, repo, prompt_template="prompt.md") + _configure(project, repo) Harness(project, verbose=False, land_mode="manual").run(Budget(until=1), report=False) out = capsys.readouterr().out text = " ".join(out.split()) assert ".autohelix/prompt.md is no longer read" in text - assert "prompt.md names .autohelix/ paths in the agent's copy" in text + assert "No gates or observe entries defined" in text # another warning assert all(not line.strip() or line.startswith(" ") for line in out.splitlines()[:12]) +def test_a_template_naming_the_old_copy_layout_is_a_config_error(repo, capsys): + project = _project(repo) + _prompt(project, "Goal: {{ goal }}; notes in .autohelix/notes/iter-1.md\n") + _configure(project, repo, prompt_template="prompt.md") + assert ("prompt_template prompt.md names .autohelix/ paths in the agent's copy; they are now " + ".autohelix-iteration/.") in _refused(project, capsys) + + def test_a_preflight_failure_keeps_a_long_path_whole(repo, capsys, monkeypatch): """The FAIL line wraps at spaces (`terminal.show`): an agent command's path wider than the screen is printed whole, never split across lines.""" @@ -547,12 +583,12 @@ def test_a_timeout_then_an_accept_with_its_patch(repo): project = _project(repo) _configure(project, repo) harness = Harness(project, verbose=False, land_mode="manual") - agent = Agent(harness, _failing({1}, error="timed out after 30 minutes")) + agent = Agent(harness, _failing({1}, error="timed out after 30m")) harness.run(Budget(until=2), report=False) records = History(project, latest_run(project).run_id).load() assert [(r.iteration, r.accepted) for r in records] == [(0, True), (1, False), (2, True)] timed_out = records[1] - assert timed_out.agent_error == "timed out after 30 minutes" and timed_out.gates == [] + assert timed_out.agent_error == "timed out after 30m" and timed_out.gates == [] assert timed_out.rejected_ref and timed_out.cost is not None patch = agent.seen[2]["patch"] assert patch and b"+attempt 1" in patch and "rejected.patch" in agent.seen[2]["prompt"] diff --git a/tests/test_history.py b/tests/test_history.py index 756e524e..31505f3d 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -61,7 +61,7 @@ def test_rejects_earlier_corruption_and_tolerates_unknown_fields(self, history): history._invalidate_cache() with history.history_path.open("a") as stream: stream.write('corrupt\n{"iteration":3,"accepted":true}\n') - with pytest.raises(RuntimeError, match="Corrupt history"): + with pytest.raises(RuntimeError, match="line 3 is damaged: fix or remove the line"): history.load() def test_empty(self, history): diff --git a/tests/test_infrastructure_failures.py b/tests/test_infrastructure_failures.py index e2429b24..a9d02a23 100644 --- a/tests/test_infrastructure_failures.py +++ b/tests/test_infrastructure_failures.py @@ -1,4 +1,4 @@ -"""Infrastructure failures (credentials, the model service): each backend reports one +"""Infrastructure failures (HTTP 401/403: credentials, access): each backend reports one from its CLI's specific signals only; anything else stays an ordinary failure. The lines are small hand-made fixtures with only the fields the backends read, in the @@ -29,8 +29,8 @@ def fake_run_process(**kwargs): @pytest.mark.parametrize(("status", "reason"), [ (401, "authentication failed (HTTP 401)"), (403, "authentication failed (HTTP 403)"), - (429, "model service error (HTTP 429)"), - (503, "model service error (HTTP 503)"), + # A rate limit or an outage is an ordinary failure: three in a row end the run. + (429, None), (503, None), (400, None), (404, None), (None, None), ("403", None), (True, None), ]) def test_infrastructure_reason(status, reason): @@ -55,8 +55,8 @@ def _run(self, monkeypatch, tmp_path, lines, **kwargs): (401, "authentication failed (HTTP 401)"), (403, "authentication failed (HTTP 403)"), # No real sample of these (none captured): the same fields, by the CLI's schema. - (429, "model service error (HTTP 429)"), - (529, "model service error (HTTP 529)"), + (429, None), + (529, None), ]) def test_an_api_error_result_is_an_infrastructure_failure(self, monkeypatch, tmp_path, status, reason): result = self._run(monkeypatch, tmp_path, [_api_error(status)]) @@ -137,8 +137,8 @@ def test_an_error_event_fails_the_call_at_exit_0(self, monkeypatch, tmp_path): @pytest.mark.parametrize(("status", "reason"), [ (403, "authentication failed (HTTP 403)"), - (429, "model service error (HTTP 429)"), - (502, "model service error (HTTP 502)"), + (429, None), + (502, None), (400, None), (None, None), ]) diff --git a/tests/test_judge.py b/tests/test_judge.py index 577cd5c2..8cde480c 100644 --- a/tests/test_judge.py +++ b/tests/test_judge.py @@ -79,16 +79,16 @@ def test_judge_config_inherits_cli_but_not_extra_args(): assert judge_config(base, model="n", timeout=30).model == "n" -def test_load_base_config_reads_v2_agent_and_rejects_old_keys(tmp_path, monkeypatch): - from autohelix.judge import load_base_config +def test_base_config_reads_v2_agent_and_rejects_old_keys(tmp_path, monkeypatch): + from autohelix.judge import base_config monkeypatch.delenv("AUTOHELIX_CONFIG", raising=False) _write(tmp_path, "goal: g\nagent:\n cli: codex\n timeout: 5m\n") - config = load_base_config(tmp_path) + config = base_config(tmp_path)[0] assert (config.cli, config.timeout) == ("codex", 300) _write(tmp_path, "goal: g\nagent:\n backend: claude\n") with pytest.raises(JudgeError, match="`agent.backend` is now `agent.cli`"): - load_base_config(tmp_path) + base_config(tmp_path) def test_cli_option_reaches_the_judge(tmp_path, monkeypatch): diff --git a/tests/test_kernelbench_example.py b/tests/test_kernelbench_example.py index d78e63ee..27c9484b 100644 --- a/tests/test_kernelbench_example.py +++ b/tests/test_kernelbench_example.py @@ -356,3 +356,42 @@ def test_download_repairs_a_partially_populated_level(tmp_path, monkeypatch): assert data_dir.joinpath("L1", "1_Test", "reference.py").read_text() == ( "class Model: pass\n" ) + + +def _no_git_identity(monkeypatch, tmp_path): + """A machine without a git identity (a fresh GPU box, a container).""" + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull) + monkeypatch.setenv("GIT_CONFIG_SYSTEM", os.devnull) + for name in ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL", "EMAIL"): + monkeypatch.delenv(name, raising=False) + + +def test_kernelbench_commits_without_a_git_identity(tmp_path, monkeypatch): + _no_git_identity(monkeypatch, tmp_path) + project = tmp_path / "project" + project.mkdir() + (project / "a.txt").write_text("a\n") + _load_setup_module().git_init(project) + assert subprocess.run(["git", "log", "--format=%an"], cwd=project, capture_output=True, text=True, + check=True).stdout == "AutoHelix\n" + + +def test_autoresearch_lays_out_without_a_git_identity_and_reruns(tmp_path, monkeypatch): + """Its commit failed without an identity, after the project was written; a rerun + then refused the folder ("exists and isn't empty"), despite "it can be re-run".""" + spec = importlib.util.spec_from_file_location("autoresearch_setup", ROOT / "examples" / "autoresearch" / "setup.py") + setup = importlib.util.module_from_spec(spec) + spec.loader.exec_module(setup) + _no_git_identity(monkeypatch, tmp_path) + local = tmp_path / "local" + (local / "upstream").mkdir(parents=True) + for name in ("train.py", "prepare.py"): + (local / "upstream" / name).write_text("# upstream\n") + monkeypatch.setattr(setup, "run", lambda *args, **kwargs: None if args[0] == "patch" else + subprocess.run([str(a) for a in args], check=True, **kwargs)) + project = tmp_path / "project" + setup.lay_out(project, local) + assert subprocess.run(["git", "-C", project, "log", "--format=%an"], capture_output=True, text=True, + check=True).stdout == "AutoHelix\n" + setup.lay_out(project, local) # a rerun: skipped, not refused diff --git a/tests/test_landing.py b/tests/test_landing.py index c579c0b7..38b261dd 100644 --- a/tests/test_landing.py +++ b/tests/test_landing.py @@ -195,9 +195,13 @@ def test_an_auto_resume_after_a_squash_merged_landing_refuses(project): data = harness.paths.read_identity() assert data["landed"]["tip"] == harness.run_state.expected_tip squash_main_onto_base(project, data) - with pytest.raises(RuntimeError, match=r"landed on main \(`autohelix land`\), which has other commits in their place since .* --import"): + with pytest.raises(RuntimeError, match=r"landed on main, which has other commits in their place since .* --import"): Harness(project) - delete(harness.paths) # nothing unlanded: no --force needed + # Landed, but its tip is on no branch: a squash merge can't be told from a reset. + with pytest.raises(RuntimeError, match=r"its tip isn't on any branch, tag or remote-tracking branch.* It reads " + r"landed: `land` put it on main, which lacks it now"): + delete(harness.paths) + delete(harness.paths, force=True) assert not harness.paths.run_dir.exists() @@ -377,3 +381,43 @@ def test_run_json_commit_ids_that_are_not_hex_count_as_missing(project): found = landing(paths, bad) assert (found.relation, found.since, found.accepted) == ("diverged", None, True) assert found.ahead == 1 # the landed commit, no longer excused + + +def test_delete_refuses_a_landed_run_whose_target_was_reset(project): + """05-1's reproduction: auto landing, then `git reset --hard` to the base and a new + commit. The run reads landed, but `delete` without --force would drop the only ref + to its commits; `land` says it did nothing.""" + from tests.helpers import cli + + harness = Harness(project) + harness.run(Budget(until=1), report=False) # lands on main, records `landed` + paths, tip = harness.paths, harness.run_state.expected_tip + short = short_id(paths.run_id) + git(project, "reset", "-q", "--hard", harness.run_info["base_commit"]) + commit_on_main(project, "after") + assert relation(paths, paths.read_identity())[0] == "landed" + result = cli(project, "land", short) + assert result.exit_code == 0, result.output + said = " ".join(result.output.split()) + assert (f"Run {short} landed on main before, which has other commits in their place since; to land it again: " + f"`git merge autohelix/{paths.run_id}`.") in said and "Landed" not in said + result = cli(project, "delete", short) + assert result.exit_code == 1 and paths.run_dir.exists() + assert (f"Not deleting run {short}: its tip isn't on any branch, tag or remote-tracking branch, so its commits " + f"would be lost.") in " ".join(result.output.split()) + git(project, "tag", "kept", tip) # on a tag: deleting loses nothing + assert cli(project, "delete", short).exit_code == 0 and not paths.run_dir.exists() + + +def test_land_says_when_there_is_nothing_to_do(project): + from tests.helpers import cli + + harness = Harness(project) + harness.run(Budget(until=1), report=False) # auto landing: already on main + short = short_id(harness.paths.run_id) + result = cli(project, "land", short) + assert result.exit_code == 0 and f"Run {short} is already in main." in result.output + assert "Landed" not in result.output + git(project, "update-ref", harness.paths.ref, harness.run_info["base_commit"]) # as if it accepted nothing + result = cli(project, "land", short) + assert result.exit_code == 0 and f"Run {short} has nothing accepted to land." in result.output diff --git a/tests/test_live.py b/tests/test_live.py index a8a0f37a..389581dc 100644 --- a/tests/test_live.py +++ b/tests/test_live.py @@ -28,7 +28,10 @@ def test_status_line(): assert W.status_line(_status(iteration=0, phase="baseline", phase_started_at=now), now) == "Running · measuring the baseline · 0s" assert W.status_line(_status(phase="report", phase_started_at=now - 75), now) == "Running · writing the summary · 1m 15s" finished = W.status_line({"state": "finished", "stopped_at": now}) - assert finished.startswith("Finished at ") and finished.endswith("Waiting for the next run…") + assert finished.startswith("Finished at ") and finished.endswith("Waiting for `autohelix resume`…") + # The view follows one run: it waits for that run's resume, not "the next run". + assert W.status_line({"state": "finished", "stopped_at": now}, run_id="20261115-1402-sorting-krp3").endswith( + "Waiting for `autohelix resume krp3`…") def test_log_for_follows_phases(tmp_path, run_paths): @@ -163,6 +166,24 @@ def test_view_serves_the_web_page_by_default(tmp_path, monkeypatch, args, page): assert served == [(9000, True, page)] +def test_a_second_view_names_the_port_in_use_and_the_page(tmp_path): + """A second `view` while one serves: not a bare "Address already in use", but the + page to open there (one server serves every run), or --port 0.""" + import socket + + import autohelix.cli as cli + + with socket.socket() as taken: + taken.bind(("127.0.0.1", 0)) + taken.listen() + port = taken.getsockname()[1] + with pytest.raises(cli.click.ClickException) as raised: + cli._serve(tmp_path, port, False, "/run/20261115-1402-sorting-krp3/") + assert raised.value.message == ( + f"Port {port} is in use (another `autohelix view`?). If it serves this project, open " + f"http://127.0.0.1:{port}/run/20261115-1402-sorting-krp3/ there; else pass --port 0 (any free port).") + + @pytest.mark.parametrize("flags", [["--json"], [], ["r1", "--once"]]) def test_metric_goes_with_the_runs_table(tmp_path, flags): result = _cli("view", "-p", tmp_path, "--metric", "speed", *flags) @@ -182,22 +203,22 @@ def _run_data(iterations: int) -> dict: def test_the_time_cap_is_the_running_segments_own(): - """What is left of --time is shown against the segment's clock while it runs, - "time up" past it, nothing once the run stopped; the run's total time has no cap.""" + """The segment's time used of --time is shown while it runs, as the web pages say it, + "(time up)" past it, nothing once the run stopped; the run's total time has no cap.""" data = _run_data(3) run = data["run"] assert W.run_table.time_cap(run, 1000) == "" # not running run["status"] = {"state": "running", "iteration": 2, "segment_started_at": 1000 - 725, "max_time_seconds": 3600, "phase": "agent", "phase_started_at": 990} - assert W.run_table.time_cap(run, 1000) == "47m 55s left (--time 1h)" # the cap as --time spells it + assert W.run_table.time_cap(run, 1000) == "12m 05s of 1h (this segment)" # the cap as --time spells it once = W.run_table.format_run(data, W.run_table.Saved(), now=1000) # no stored config: the header still has it - assert " Budget 47m 55s left (--time 1h)" in once and once.count("left") == 1 # the live row has the iteration's time + assert " Budget 12m 05s of 1h (this segment)" in once and once.count("12m 05s") == 1 # the live row has the iteration's time run["status"].update(segment_started_at=1000 - 6000, max_time_seconds=5400) - assert W.run_table.time_cap(run, 1000) == "time up (--time 1h30m)" + assert W.run_table.time_cap(run, 1000) == "1h 40m of 1h30m (this segment) (time up)" config = Config.from_dict({"goal": "Go faster", "gates": ["true"]}) - assert "Budget time up (--time 1h30m)" in W.run_table.format_run(data, W.run_table.Saved(config), now=1000) + assert "Budget 1h 40m of 1h30m (this segment) (time up)" in W.run_table.format_run(data, W.run_table.Saved(config), now=1000) run["status"]["segment_started_at"] = 1000 + 5 # clock skew - assert W.run_table.time_cap(run, 1000) == "1h 30m left (--time 1h30m)" + assert W.run_table.time_cap(run, 1000) == "0s of 1h30m (this segment)" run["status"].update(state="finished") assert W.run_table.time_cap(run, 1000) == "" assert "1h30m" not in W.run_table.format_run(data, W.run_table.Saved(config), now=1000) diff --git a/tests/test_prompt_template.py b/tests/test_prompt_template.py index a476b70f..3c439770 100644 --- a/tests/test_prompt_template.py +++ b/tests/test_prompt_template.py @@ -355,6 +355,18 @@ def test_after_a_rejection_with_patch_and_discarded_paths(tmp_path): assert "Last accepted" not in rendered +def test_discarded_paths_past_the_listed_ones_are_counted(tmp_path): + rejected = {"iteration": 1, "accepted": False, "reason": "gate failed: pytest -q", + "discarded": ["data/a.bin", "tests/test_sort.py"], "discarded_frozen": ["tests/test_sort.py"], + "discarded_more": 4998, "tree": "abc", + "gates": [{"text": "pytest -q", "kind": "command", "passed": False}]} + variables, rendered = _render(tmp_path, [BASELINE, rejected], 2) + assert variables["discarded_more"] == 4998 + assert "Your changes to data/a.bin were discarded: outside the editable scope." in rendered + assert "Your changes to tests/test_sort.py were discarded: frozen." in rendered + assert "Your changes to 4998 more paths outside the scope were discarded too." in rendered + + def test_rejection_after_observe_shows_what_it_produced(tmp_path): rejected = {"iteration": 1, "accepted": False, "reason": "metric gate: speed 5 is 50.0% worse than 10", "gates": [{"text": "pytest -q", "kind": "command", "passed": True}, diff --git a/tests/test_rejected_work.py b/tests/test_rejected_work.py index 80ac0baa..cdcff6f3 100644 --- a/tests/test_rejected_work.py +++ b/tests/test_rejected_work.py @@ -131,6 +131,48 @@ def test_discarded_paths_are_recorded(project): assert _refs(project, harness) == [] +def test_the_discarded_list_is_capped_in_the_record_and_the_prompt(project): + """Thousands of files written outside the scope (a dataset): the record lists the + first 20 and counts the rest; so does the next prompt.""" + _configure(project, scope={"editable": ["hello.py"]}) + harness = Harness(project, verbose=False, land_mode="manual") + + def dataset(copy_dir): + (copy_dir / "data").mkdir(exist_ok=True) + for index in range(25): + (copy_dir / "data" / f"part-{index:02}.txt").write_text(f"{index}\n") + + spy = Spy(harness, edit=dataset) + harness.run(Budget(until=2), report=False) + record = History(project, latest_run(project).run_id).load()[1] + assert record.discarded == [f"data/part-{index:02}.txt" for index in range(20)] + assert record.discarded_more == 5 + prompt = spy.seen[2]["prompt"] + assert "Your changes to data/part-00.txt, data/part-01.txt," in prompt and "data/part-20.txt" not in prompt + assert "Your changes to 5 more paths outside the scope were discarded too." in prompt + + +def test_a_frozen_discard_stays_listed_past_the_cap(project): + """A frozen file edited among a dataset written outside the scope: the cap keeps + the frozen one listed (frozen first), so the next prompt still names it.""" + _configure(project, scope={"editable": ["hello.py", "zz/"], "frozen": ["zz/"]}) + harness = Harness(project, verbose=False, land_mode="manual") + + def dataset(copy_dir): + (copy_dir / "data").mkdir(exist_ok=True) + for index in range(25): + (copy_dir / "data" / f"part-{index:02}.txt").write_text(f"{index}\n") + (copy_dir / "zz").mkdir(exist_ok=True) + (copy_dir / "zz" / "check.txt").write_text("weakened\n") + + spy = Spy(harness, edit=dataset) + harness.run(Budget(until=2), report=False) + record = History(project, latest_run(project).run_id).load()[1] + assert record.discarded[0] == "zz/check.txt" and record.discarded_frozen == ["zz/check.txt"] + assert len(record.discarded) == 20 and record.discarded_more == 6 + assert "Your changes to zz/check.txt were discarded: frozen." in spy.seen[2]["prompt"] + + def test_no_scope_warns_at_run_start(project, capsys): _configure(project, gates=["true"]) Harness(project, verbose=False, land_mode="manual").run(Budget(until=1), report=False) diff --git a/tests/test_run_check.py b/tests/test_run_check.py index 674741b7..9c0e8cdf 100644 --- a/tests/test_run_check.py +++ b/tests/test_run_check.py @@ -57,3 +57,57 @@ def test_uncommitted_tracked_changes_fail_the_check(project): result = cli(project, "run", "--check") assert result.exit_code == 1 assert "Uncommitted changes in tracked files" in result.output + + +def test_the_check_says_what_run_says_about_other_runs_and_names_the_flags(project): + """`run --check --import X` warns that X's commit isn't in main, as `run` does, + and its OK line names the command checked, flags included.""" + from autohelix.runs import short_id + from tests.test_groups import started + + first, _ = started(project, "--land", "manual") # its commit stays on autohelix/ + short = short_id(first.run_id) + result = cli(project, "run", "--check", "--import", short) + assert result.exit_code == 0, result.output + said = " ".join(result.output.split()) + assert f"{short}'s 1 accepted commit isn't in main: land it first" in said + assert f"`autohelix run demo --import {short}` would start a new run." in said + result = cli(project, "run", "--check", "--group", "g", "--land", "auto") + assert result.exit_code == 0, result.output + assert "`autohelix run demo --group g --land auto` would start a new run." in " ".join(result.output.split()) + + +def test_the_check_warns_about_an_uncommitted_config_as_run_does(project): + from autohelix.runs import git + + exclude = project / ".git" / "info" / "exclude" # autohelix/ shared: not private as setup makes it + exclude.write_text("".join(line for line in exclude.read_text().splitlines(keepends=True) + if line.strip() != "/autohelix/")) + (config_file(project).parent / "bench.sh").write_text("true\n") + before = _snapshot(project) + result = cli(project, "run", "--check") + assert result.exit_code == 0, result.output + said = " ".join(result.output.split()) + assert ("commit autohelix/demo/config.yaml first: a commit on main after this run lands makes `resume` refuse. " + "Or keep autohelix/ private (docs/concepts.md#where-configs-live).") in said + assert "commit autohelix/demo/ first (bench.sh)" in said + assert "would start a new run" in said and _snapshot(project) == before + result = cli(project, "run", "--check", "--land", "manual") + assert "first: a commit on" not in result.output + git(project, "add", "-f", "autohelix") + git(project, "commit", "-qm", "config") + assert "first: a commit on" not in cli(project, "run", "--check").output + + +@pytest.mark.parametrize(("text", "message"), [ + ("Goal: {{ goall }}\n", "prompt_template p.md uses variables the prompt doesn't have: goall."), + ("{{ goal }}{% if last %}{{ last.gates.x.y }}{% endif %}\n", "prompt_template p.md could not be rendered:"), +]) +def test_a_template_mistake_fails_the_check(project, text, message): + """`run --check` said OK for both; `run` then sent a prompt without the goal, or + failed iteration 1 after the baseline.""" + (config_file(project).parent / "p.md").write_text(text) + configure(project, prompt_template="p.md") + result = cli(project, "run", "--check") + assert result.exit_code == 1, result.output + assert message in " ".join(result.output.split()) diff --git a/tests/test_run_config.py b/tests/test_run_config.py index 871cdcb5..d977ecb2 100644 --- a/tests/test_run_config.py +++ b/tests/test_run_config.py @@ -155,15 +155,16 @@ def refused(paths, result, keys, unlanded): text = " ".join(result.output.split()) assert result.exit_code == 1, result.output said = (f"{CONFIG_PATH} changed since run {short} started (changed: {keys}); the run keeps the config it " - f"started with. To apply the new config, start a new run that continues from this one: " - f"`autohelix run {NAME} --import {short}`. ") + f"started with. ") assert said in text and text.endswith("To continue this run, restore the file."), text between = text[text.index(said) + len(said):].removesuffix("To continue this run, restore the file.") # Its unlanded commits (`unlanded`: manual landing; main can fast-forward to them): land - # them first, to start the new run from them. + # them first, then the new run starts from them. assert between == (f"{short}'s 1 accepted commit isn't in main: land it first (`autohelix land {short}`, " - f"or `git switch -c autohelix/{paths.run_id}`) to start " - "from it. " if unlanded else ""), between + f"or `git switch -c autohelix/{paths.run_id}`) to start from it. Then " + f"`autohelix run {NAME} --import {short}` applies the new config. " if unlanded else + f"To apply the new config, start a new run that continues from this one: " + f"`autohelix run {NAME} --import {short}`. "), between assert History(paths.project, paths.run_id).get_last_iteration() == 1 # nothing spent @@ -245,7 +246,7 @@ def changes(a, b): assert changes("goal: g\ngates: [pytest]\n", "goal: g\ngates: [{command: pytest, timeout: 1800}]\n") == [] assert changes("goal: g\nagent: {timeout: 10m}\n", "goal: g\nagent: {timeout: 600, cli: claude-code}\n") == [] assert changes("goal: g\nscope: {editable: null}\ngates: []\n", "goal: g\n") == [] - assert changes("goal: g\nagent: {timeout: 10m}\n", "goal: g\nagent: {timeout: 11m}\n") == ["agent"] + assert changes("goal: g\nagent: {timeout: 10m}\n", "goal: g\nagent: {timeout: 11m}\n") == ["agent.timeout"] assert changes("goal: g\nscope: {editable: [src/]}\n", "goal: h\nscope: {editable: [./src/]}\n") == ["goal"] assert changes("goal: g\nscope: {frozen: [a]}\n", "goal: g\nscope: {frozen: [b]}\n") == ["scope.frozen"] @@ -323,3 +324,18 @@ def test_an_agent_edit_to_the_config_or_template_is_reverted(project, target): tip = git(project, "rev-parse", harness.paths.ref).stdout.strip() assert git(project, "diff", "--name-only", harness.run_info["base_commit"], tip).stdout == "" assert harness.config.frozen == [] # `scope:` unset: its warning still applies (`scope_warning`) + + +def test_config_changes_name_the_field_and_the_entry(tmp_path): + """"(changed: observe)" over a five-entry list meant diffing the stored copy by hand.""" + def changes(a, b): + return config_changes(parsed(tmp_path, "goal: g\n" + a), parsed(tmp_path, "goal: g\n" + b)) + + assert changes("agent: {model: a, effort: low}\n", "agent: {model: b, effort: high}\n") == [ + "agent.model", "agent.effort"] + assert changes("gates: [a, b]\n", "gates: [a, c, d]\n") == ["gates entry 2", "gates entry 3 (added)"] + assert changes("stop: [a, b]\n", "stop: [a]\n") == ["stop entry 2 (removed)"] + one, two = "{name: one, command: 'true'}", "{name: two, command: 'true'}" + assert changes(f"observe: [{one}, {two}]\n", f"observe: [{one}, {{name: two, command: x}}]\n") == ["observe two"] + assert changes(f"observe: [{one}]\n", f"observe: [{two}]\n") == ["observe one (removed)", "observe two (added)"] + assert changes(f"observe: [{one}, {two}]\n", f"observe: [{two}, {one}]\n") == ["observe (order)"] diff --git a/tests/test_run_notices.py b/tests/test_run_notices.py index 7de76570..9918d0df 100644 --- a/tests/test_run_notices.py +++ b/tests/test_run_notices.py @@ -46,7 +46,10 @@ def test_the_config_change_refusal_says_land_it_first(project): result = cli(project, "resume", short, "-n", "1", "--no-report") assert result.exit_code == 1 said = " ".join(result.output.split()) - assert f"`autohelix run demo --import {short}`. {short}'s 1 accepted commit isn't in main: land it first" in said + assert (f"started with. {short}'s 1 accepted commit isn't in main: land it first (`autohelix land {short}`, or " + f"`git switch -c autohelix/{first.run_id}`) to start from it. Then `autohelix run demo --import " + f"{short}` applies the new config.") in said + assert result.output.count("\n") >= 3 # a line each def failing_baseline(project): @@ -60,6 +63,13 @@ def test_a_failed_baseline_is_a_disposable_attempt(project): paths = latest_run(project) short = short_id(paths.run_id) said = " ".join(result.output.split()) + # The end block's next commands say what the error says, not `resume` (02-2). + assert "autohelix run demo a new run, once the setup is fixed" in said, said + assert f"autohelix delete {short} remove this attempt" in said and f"autohelix resume {short}" not in said + import json + from autohelix.run_table import suggestion + [run] = json.loads(cli(project, "view", "--json").stdout)["runs"] + assert run["baseline"] is False and suggestion(run)[1] == "autohelix run demo" assert (f"every declared metric needs a value at the baseline. Fix it and run `autohelix run demo` again " f"(`autohelix delete {short}` removes this attempt).") in said # The history keeps the error itself, without the advice. @@ -150,3 +160,34 @@ def test_import_on_a_detached_head_offers_the_branch(project): _, result = started(project, "--import", short, "--land", "manual") # detached: nothing to land on assert (f"{short}'s 1 accepted commit isn't in HEAD: land it first (`git switch -c " f"autohelix/{first.run_id}`) to start from it.") in before_header(result) + + +def _damage(paths, line: str) -> None: + """Insert `line` as the history's second line.""" + lines = paths.history.read_text().splitlines(keepends=True) + paths.history.write_text("".join(lines[:1] + [line] + lines[1:])) + + +def test_a_damaged_history_of_the_previous_run_doesnt_stop_a_new_run(project): + """A bad line before the last in the previous run's history: `run` starts as `run + --check` said, and that run's own commands name the line and what works, without + a traceback.""" + first, _ = started(project, "--land", "manual") + short = short_id(first.run_id) + _damage(first, "{broken\n") + assert cli(project, "run", "--check").exit_code == 0 + started(project, "--land", "manual") + message = f"Run {short}'s history.jsonl line 2 is damaged: fix or remove the line, or `autohelix archive {short}`." + for args in (["resume", short, "-n", "1", "--no-report"], ["resume", short, "--until", "5", "--no-report"], + ["report", short]): + result = cli(project, *args) + assert result.exit_code == 1, (args, result.output) + assert message in " ".join(result.output.split()), (args, result.output) + assert not isinstance(result.exception, RuntimeError), args # said, not a traceback + + +def test_a_blank_history_line_resumes_as_it_views(project): + first, _ = started(project, "--land", "manual") + _damage(first, "\n") + result = cli(project, "resume", short_id(first.run_id), "-n", "1", "--no-report") + assert result.exit_code == 0, result.output diff --git a/tests/test_run_selection.py b/tests/test_run_selection.py index 8eddfe11..ef96a814 100644 --- a/tests/test_run_selection.py +++ b/tests/test_run_selection.py @@ -36,13 +36,23 @@ def test_default_run_is_the_running_one_else_the_latest_not_archived(tmp_path): old = add_run(tmp_path, "old-aaaa", created_at=1000) add_run(tmp_path, "new-bbbb", created_at=3000, archived=True) middle = add_run(tmp_path, "mid-cccc", created_at=2000) - assert default_run(tmp_path)[::2] == (middle, "most recently active") + assert default_run(tmp_path)[::2] == (middle, "most recently active run") with RunLock(old.lock): - assert default_run(tmp_path)[::2] == (old, "running") + assert default_run(tmp_path)[::2] == (old, "running run") with RunLock(middle.lock), pytest.raises(RuntimeError, match="Several runs are running: (aaaa, cccc|cccc, aaaa); name one"): default_run(tmp_path) +def test_land_and_report_default_to_a_run_that_isnt_running(tmp_path): + """They take the run's lock: the running run (06-1) could only refuse.""" + old = add_run(tmp_path, "old-aaaa", created_at=1000) + middle = add_run(tmp_path, "mid-cccc", created_at=2000) + with RunLock(middle.lock): + assert default_run(tmp_path, running=False)[::2] == (old, "most recently active run that isn't running") + with RunLock(old.lock), pytest.raises(RuntimeError, match=r"Every run is running or archived \(running: "): + default_run(tmp_path, running=False) + + def test_a_probe_creates_no_lock_file(tmp_path): paths = add_run(tmp_path, "old-aaaa", created_at=1000) default_run(tmp_path) diff --git a/tests/test_runner.py b/tests/test_runner.py index c068e8fc..bc0ea61a 100644 --- a/tests/test_runner.py +++ b/tests/test_runner.py @@ -21,7 +21,7 @@ def _run(tmp_path, script, **kwargs): cmd=["sh", "-c", script], cwd=tmp_path, log_path=tmp_path / "agent.log", - line_callback=lines.append, + line_callback=kwargs.pop("line_callback", lines.append), **kwargs, ) return result, lines, time.monotonic() - started @@ -181,3 +181,17 @@ def test_a_signal_while_a_child_starts_is_still_ignored(): handler = signal.getsignal(signal.SIGINT) with child_signals(): assert signal.getsignal(signal.SIGINT) is handler + + +def test_an_exception_while_the_agent_runs_kills_its_group(tmp_path): + """A line callback that raises (or a full disk writing the log) ends the call: the + agent doesn't go on working, past its timeout, after the harness has moved on.""" + late = tmp_path / "late" + + def fail(line): + raise RuntimeError(f"can't handle {line}") + + with pytest.raises(RuntimeError, match="can't handle hi"): + _run(tmp_path, f"echo hi; sleep 2; touch {late}", line_callback=fail) + time.sleep(3) + assert not late.exists() diff --git a/tests/test_runs.py b/tests/test_runs.py index 6670e6fb..6793e996 100644 --- a/tests/test_runs.py +++ b/tests/test_runs.py @@ -150,7 +150,7 @@ def test_history_tail_repair_preserves_valid_unterminated_record(run_paths, tail def test_history_corruption_is_not_repaired(run_paths, content): path = run_paths.history path.write_bytes(content) - with pytest.raises(RuntimeError, match="history record"): + with pytest.raises(RuntimeError, match=r"history\.jsonl line [12] is damaged: fix or remove the line"): repair_history(run_paths) assert path.read_bytes() == content diff --git a/tests/test_snapshots.py b/tests/test_snapshots.py index f6a60667..ab7341ca 100644 --- a/tests/test_snapshots.py +++ b/tests/test_snapshots.py @@ -46,8 +46,8 @@ def _gates(command: bool | None, metric: bool | None = None, **values) -> list[d Row(2, False, {}, 143, 0.48, reason="gate failed: pytest -q test_sort.py", gates=_gates(False)), Row(3, True, {"speed": 35310.7, "mem_mb": 96}, 126, 0.32, commit="a3", summary="Switch to built-in sorted() with key caching", gates=_gates(True, True)), - Row(4, False, {}, 1800, 1.10, reason="Iteration 4 agent failed: timed out after 30 minutes", - agent_error="timed out after 30 minutes"), + Row(4, False, {}, 1800, 1.10, reason="Iteration 4 agent failed: timed out after 30m", + agent_error="timed out after 30m"), Row(5, False, {"speed": 33002.0, "mem_mb": 140}, 108, 0.29, reason="metric gate: speed 33002 is 6.5% worse than 35310.7 (regress: 5% allowed)", gates=_gates(True, False, value=33002.0, reference=35310.7), @@ -69,10 +69,10 @@ def _header(width: int, budget: Budget, done: int = 0, show_mark: bool = True) - def _ending(table: Table, stop: dict, first: int = 1) -> list: """The end block as the harness assembles it (`Harness._print_ending`): auto landing - of this segment's commits, the run's cost so far.""" + of this segment's commits (said so after the first), the run's cost so far.""" landed = [row for row in table.rows if row.iteration >= first and row.accepted and row.commit] return table.ending(terminal.outcome(stop, None, None), spent=terminal.money(sum(r.cost or 0 for r in table.rows)), - landing=terminal.landed(len(landed), "main"), commands=terminal.next_commands("krp3"), + landing=terminal.landed(len(landed), "main", segment=first > 1), commands=terminal.next_commands("krp3"), files=FILES, folder=FOLDER) diff --git a/tests/test_stop.py b/tests/test_stop.py index 52013cf7..01a7d812 100644 --- a/tests/test_stop.py +++ b/tests/test_stop.py @@ -227,7 +227,7 @@ def test_stop_writes_a_request_for_the_running_segment(project, running): result = cli(project, "stop", short, "--why", "done for today") assert result.exit_code == 0, result.output assert result.output.splitlines() == [f"Run {short} stops after its current iteration (3).", - f"See when it has ended: autohelix wait -p {project} {short} " + f"See when it has ended: autohelix wait -p {cli_module._shown(project)} {short} " "(repeat until it prints ended or idle)"] request = json.loads(running.stop_request.read_text()) assert {k: request[k] for k in ("why", "now", "segment", "host", "pid")} == { @@ -297,6 +297,15 @@ def test_stop_with_an_unknown_id_stops_nothing(project, running): assert not running.stop_request.exists() # ids are resolved before anything is asked +def test_stop_advice_names_the_project_relative_to_where_it_is_typed(project, running, monkeypatch): + # From a folder near the project (a checkout under $TMPDIR, say) the advice is relative. + monkeypatch.chdir(project.parent) + short = short_id(running.run_id) + result = cli(project, "stop", short) + assert result.exit_code == 0, result.output + assert f"See when it has ended: autohelix wait -p {project.name} {short} " in result.output + + def test_stop_handles_every_known_id_and_fails_if_any_failed(project, running): short = short_id(running.run_id) other = RunPaths(project, "20260101-0000-idle-zzzz") @@ -305,8 +314,9 @@ def test_stop_handles_every_known_id_and_fails_if_any_failed(project, running): assert result.exit_code == 1 assert "Run zzzz is not running." in result.output assert f"Run {short} stops after its current iteration (3)." in result.output - assert (f"See when it has ended: autohelix wait -p {project} {short} (repeat until it prints ended or idle)" - in result.output) + # The project as the CLI names it from here (relative when that is shorter), wherever pytest runs. + assert (f"See when it has ended: autohelix wait -p {cli_module._shown(project)} {short} " + "(repeat until it prints ended or idle)" in result.output) assert running.stop_request.exists() diff --git a/tests/test_viewer.py b/tests/test_viewer.py index f86af3d4..a8298b3c 100644 --- a/tests/test_viewer.py +++ b/tests/test_viewer.py @@ -16,7 +16,7 @@ from autohelix.harness import Budget, AutoHelixRunError, Harness from autohelix.run_status import RunStatus, read_run_status from autohelix.runs import RunLock -from autohelix.viewer import make_server +from autohelix.viewer import ProjectRuns, make_server from autohelix.runs import RunPaths, short_id from tests.test_integration import integration_project # noqa: F401 (fixture) from tests.helpers import CONFIG, NAME, config_file, latest_run, with_words @@ -325,7 +325,7 @@ def test_viewer_index_is_private_and_one_per_run(viewer, integration_project): assert [p.name for p in _private_index_dir().glob(f"view-{run}-*")] == [f"view-{run}-iter-4-agent.index"] -@pytest.mark.parametrize("phase, shown", [("preparing checks", True), ("checks", True), ("review", True), +@pytest.mark.parametrize("phase, shown", [("preparing checks", True), ("checks", True), ("observe", True), ("agent", False), ("between iterations", False)]) def test_frozen_candidate_diff_only_once_this_iteration_froze(viewer, integration_project, phase, shown): # noqa: F811 # As if a segment were live: the pin holds iteration 2's tree; iteration 3 has no copy yet. @@ -442,6 +442,10 @@ def test_dashboard_lists_runs_and_serves_each_run(integration_project): # noqa: progress = one["progress"] assert (progress["iterations"], progress["max_iterations"], progress["max_cost_usd"]) == (2, 2, None) assert progress["seconds"] > 0 and progress["max_seconds"] is None + # The run page's rows (what its Time stat sums) count the baseline too, as the list does. + rows = ProjectRuns(integration_project).run(first.paths.run_id)["run"]["iterations"] + assert rows[0]["iteration"] == 0 and rows[0]["seconds"] > 0 + assert sum(r["seconds"] for r in rows) == pytest.approx(progress["seconds"]) # Budget figures come from the run's status (its latest segment's flags: iterations # and cost as run totals, time as the segment's own), never from the config. assert (two["progress"]["max_iterations"], two["progress"]["max_cost_usd"], @@ -684,3 +688,14 @@ def test_pin_is_announced_before_the_checks_copy(integration_project, monkeypatc phases.append(phase), original(self, phase, iteration))[1]) Harness(integration_project).run(Budget(until=1), report=False) assert phases.index("agent") < phases.index("preparing checks") < phases.index("checks") + + +def test_the_run_page_words_the_phase_as_the_console_does(): + """The running row and the panel title said "Running gates…" or "accept…" from a + table of the page's own while the status line said `gates`: now both use the + server's `phase_word` (`run_table._live_what`), as the run list does.""" + from importlib.resources import files + + source = files("autohelix").joinpath("viewer_resources", "viewer.js").read_text() + assert "PHASES" not in source and "phaseText" not in source + assert source.count("state.status.phase_word") == 2 diff --git a/tests/test_viewer_v2.py b/tests/test_viewer_v2.py index 8bdbe155..1a7a54f6 100644 --- a/tests/test_viewer_v2.py +++ b/tests/test_viewer_v2.py @@ -468,6 +468,23 @@ def test_the_stored_template_is_shown_with_the_config(project): assert config["template"] == {"file": f"autohelix/{NAME}/prompt.md", "text": "Stored: {{ goal }}\n"} +def test_a_stored_config_or_template_that_is_a_symlink_is_not_shown(project, tmp_path): + """The page's config and template text are run state: read without following a + symlink, so report.html can't embed a file an agent pointed them at.""" + paths = RunPaths(project, "test") + secret = tmp_path / "secret.txt" + secret.write_text("SECRET-KEY-MATERIAL\n") + paths.config.write_text(CONFIG + "prompt_template: prompt.md\n") + paths.template.symlink_to(secret) + config = RunData(project, run_id="test").state()["config"] + assert config["text"].endswith("prompt_template: prompt.md\n") and config["template"]["text"] is None + paths.config.unlink() + paths.config.symlink_to(secret) + data = RunData(project, run_id="test") + assert "SECRET" not in json.dumps(data.state()) + assert "SECRET" not in write_static(project, run_id="test").read_text() + + def test_config_is_parsed_again_only_when_its_file_changes(project, monkeypatch): import autohelix.viewer as viewer_module diff --git a/tests/test_workspace.py b/tests/test_workspace.py index 399f7e83..86eef7ce 100644 --- a/tests/test_workspace.py +++ b/tests/test_workspace.py @@ -140,6 +140,24 @@ def test_frozen_directory_replaced_by_symlink_is_restored(repo_dir, copies, tmp_ assert (elsewhere / "test_a.py").read_text() == "weakened\n" +@pytest.mark.parametrize("editable", [(), ("tests/test_a.py",)]) +def test_a_directory_replaced_by_a_symlink_in_scope(repo_dir, copies, tmp_path, editable): + """The files below the link are gone (git refuses them as pathspecs); the link is + kept when it is in scope, discarded when only the file below it was.""" + (repo_dir / "tests").mkdir() + (repo_dir / "tests" / "test_a.py").write_text("frozen\n") + head = commit_all(repo_dir) + copy = Copy.create(Repo(repo_dir), copies / "c", files=head, head=head, watched=True) + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + (elsewhere / "test_a.py").write_text("weakened\n") + shutil.rmtree(copy.path / "tests") + (copy.path / "tests").symlink_to(elsewhere) + tree, discarded = copy.snapshot(Scope(editable=editable)) + assert discarded == ([] if not editable else ["tests"]) + assert names(repo_dir, tree) == {"code.py", "test_code.py"} | ({"tests"} if not editable else set()) + + def test_crlf_autocrlf_and_working_tree_encoding_round_trip(repo_dir, copies): (repo_dir / ".gitattributes").write_text( "*.txt eol=crlf\nutf16.dat working-tree-encoding=UTF-16LE-BOM text\n") @@ -429,6 +447,134 @@ def test_the_freeze_never_hashes_harness_material(repo_dir, copies): assert subprocess.run(["git", "cat-file", "-e", f"{tree}:code.py"], cwd=repo_dir).returncode == 0 +def _objects(root) -> set[str]: + """Every object in the repository's store, loose or packed, reachable or not.""" + listing = subprocess.run(["git", "cat-file", "--batch-all-objects", "--batch-check=%(objectname)"], + cwd=root, capture_output=True, text=True, check=True).stdout + return set(listing.split()) + + +def test_an_unreadable_out_of_scope_file_is_discarded_not_rejected(repo_dir, copies): + """Only kept files are read: an unreadable file outside the scope is listed and + discarded; the in-scope edit is kept.""" + _, _, copy = agent_copy(repo_dir, copies) + unreadable = copy.path / "new.txt" + unreadable.write_text("secret") + unreadable.chmod(0) + (copy.path / "code.py").write_text("print('edited')\n") + try: + if os.access(unreadable, os.R_OK): + pytest.skip("running as a user that reads anything") + tree, discarded = copy.snapshot(Scope(editable=("code.py",))) + assert discarded == ["new.txt"] and blob(repo_dir, tree, "code.py") == b"print('edited')\n" + finally: + unreadable.chmod(0o644) + + +def test_many_kept_files_are_added_and_the_frozen_still_reset(repo_dir, copies): + """No path outside the scope (the one-pathspec add): every new file is kept, and + .autohelix-iteration/ still isn't.""" + _, _, copy = agent_copy(repo_dir, copies) + (copy.path / "data").mkdir() + for index in range(50): + (copy.path / "data" / f"part-{index}.txt").write_text(f"{index}\n") + (copy.path / ".autohelix-iteration").mkdir(exist_ok=True) + (copy.path / ".autohelix-iteration" / "commit_summary.txt").write_text("summary\n") + tree, discarded = copy.snapshot(Scope()) + assert discarded == [] + assert {f"data/part-{index}.txt" for index in range(50)} <= names(repo_dir, tree) + assert not any(name.startswith(".autohelix") for name in names(repo_dir, tree)) + + +def _stored(root, content: bytes) -> bool: + oid = subprocess.run(["git", "hash-object", "--stdin"], cwd=root, input=content, + capture_output=True, check=True).stdout.decode().strip() + return subprocess.run(["git", "cat-file", "-e", oid], cwd=root).returncode == 0 + + +def test_out_of_scope_files_are_never_hashed_into_the_users_store(repo_dir, copies): + """A dataset or checkpoint outside `editable:`: listed and discarded, never hashed. + The store gains only the in-scope edit's blob and the tree.""" + _, _, copy = agent_copy(repo_dir, copies) + big = os.urandom(3_000_000) + (copy.path / "data").mkdir() + (copy.path / "data" / "big.bin").write_bytes(big) + for index in range(200): + (copy.path / "data" / f"part-{index}.txt").write_text(f"part {index} {os.urandom(8).hex()}\n") + (copy.path / "test_code.py").write_text("assert 'out of scope'\n") + (copy.path / "code.py").write_text("print('edited')\n") + before = _objects(repo_dir) + tree, discarded = copy.snapshot(Scope(editable=("code.py",))) + assert len(discarded) == 202 and discarded[:2] == ["data/big.bin", "data/part-0.txt"] + assert discarded[-1] == "test_code.py" + assert names(repo_dir, tree) == {"code.py", "test_code.py"} + assert blob(repo_dir, tree, "code.py") == b"print('edited')\n" + assert len(_objects(repo_dir) - before) == 2 # code.py's blob and the tree + assert not _stored(repo_dir, big) and not _stored(repo_dir, b"assert 'out of scope'\n") + + +def test_a_touched_out_of_scope_file_is_not_discarded(repo_dir, copies): + _, _, copy = agent_copy(repo_dir, copies) + later = time.time() + 5 + os.utime(copy.path / "test_code.py", (later, later)) + (copy.path / "code.py").write_text("print('edited')\n") + tree, discarded = copy.snapshot(Scope(editable=("code.py",))) + assert discarded == [] and blob(repo_dir, tree, "code.py") == b"print('edited')\n" + + +@pytest.mark.parametrize("edit", [True, False]) +def test_a_tracked_file_in_an_ignored_folder_is_staged(repo_dir, copies, edit): + """A file committed despite `.gitignore` (`.vscode/settings.json` under `.vscode/`): + its edit or deletion is kept, also beside an out-of-scope change.""" + (repo_dir / ".gitignore").write_text(".vscode/\n") + (repo_dir / ".vscode").mkdir() + (repo_dir / ".vscode" / "settings.json").write_text("{}\n") + git(repo_dir, "add", "-f", ".gitignore", ".vscode/settings.json") + git(repo_dir, "commit", "-qm", "settings") + head = git(repo_dir, "rev-parse", "HEAD").stdout.strip() + copy = Copy.create(Repo(repo_dir), copies / "c", files=head, head=head, watched=True) + settings = copy.path / ".vscode" / "settings.json" + if edit: + settings.write_text('{"edited": true}\n') + else: + settings.unlink() + (copy.path / "test_code.py").write_text("assert 'out of scope'\n") + tree, discarded = copy.snapshot(Scope(frozen=("test_code.py",))) + assert discarded == ["test_code.py"] + if edit: + assert blob(repo_dir, tree, ".vscode/settings.json") == b'{"edited": true}\n' + else: + assert ".vscode/settings.json" not in names(repo_dir, tree) + + +@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="no FIFOs") +def test_a_fifo_in_place_of_a_kept_file_is_rejected(repo_dir, copies): + """A special file can't be committed: the iteration is rejected, not taken as a deletion.""" + _, _, copy = agent_copy(repo_dir, copies) + (copy.path / "code.py").unlink() + os.mkfifo(copy.path / "code.py") + (copy.path / "test_code.py").write_text("assert 'out of scope'\n") + with pytest.raises(CandidateRejected, match="code.py is not a regular file or symbolic link"): + copy.snapshot(Scope(editable=("code.py",))) + + +def test_a_file_turned_into_a_folder_keeps_its_out_of_scope_files_unhashed(repo_dir, copies): + """An in-scope name now a folder: adding it would add what is below it; the frozen + file there is excluded, discarded and never hashed.""" + (repo_dir / "data").write_text("a file\n") + head = commit_all(repo_dir) + copy = Copy.create(Repo(repo_dir), copies / "c", files=head, head=head, watched=True) + (copy.path / "data").unlink() + (copy.path / "data").mkdir() + (copy.path / "data" / "ok.txt").write_text("in scope\n") + secret = os.urandom(64) + (copy.path / "data" / "secret.bin").write_bytes(secret) + tree, discarded = copy.snapshot(Scope(frozen=("data/secret.bin",))) + assert discarded == ["data/secret.bin"] + assert names(repo_dir, tree) == {"code.py", "test_code.py", "data/ok.txt"} + assert not _stored(repo_dir, secret) + + def test_linked_worktree_project(repo_dir, tmp_path): linked = tmp_path / "linked" git(repo_dir, "worktree", "add", "-q", "-b", "side", str(linked)) @@ -481,6 +627,13 @@ def test_changed_or_new_gitlink_is_rejected(repo_dir, copies, with_submodule): copy.snapshot(Scope()) +def test_a_deleted_submodule_is_rejected_also_outside_the_scope(repo_dir, copies, with_submodule): + copy = Copy.create(Repo(repo_dir), copies / "c", files=with_submodule, head=with_submodule, watched=True) + (copy.path / "lib").rmdir() + with pytest.raises(CandidateRejected, match="^submodule changes are not supported: lib$"): + copy.snapshot(Scope(editable=("code.py",))) + + @pytest.mark.parametrize("commits", [True, False]) def test_a_nested_repository_is_rejected_with_what_to_do(repo_dir, copies, commits): """[01-3] A repository the agent cloned or made, also outside the scope and also