From 2f79b699772b2d352b32d75a17783a232f947959 Mon Sep 17 00:00:00 2001 From: hermes <3+hermes@noreply.localhost> Date: Thu, 12 Nov 2026 23:21:21 +0000 Subject: [PATCH] O2: gate retry with failure log (#10) --- src/profile.rs | 13 ++++-- src/run.rs | 116 ++++++++++++++++++++++++++++++++++--------------- src/state.rs | 19 +++++++- tests/e2e.py | 20 ++++++++- 4 files changed, 127 insertions(+), 41 deletions(-) diff --git a/src/profile.rs b/src/profile.rs index d15390d..e0560d8 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -7,11 +7,11 @@ use std::path::PathBuf; #[derive(Deserialize, Debug, Default, Clone)] #[serde(deny_unknown_fields)] pub struct Budget { - /// Wall clock limit for the hx run (not the gate). Default 30 min. + /// Wall clock limit per hx attempt (not the gate). Default 30 min. pub wall_secs: Option, - /// Max `turn_start` events before hx is killed. + /// Max `turn_start` events over the whole run (all attempts) before hx is killed. pub max_turns: Option, - /// Max input+output tokens, summed over `stream/done` events. + /// Max input+output tokens over the whole run, summed over `stream/done` events. pub max_tokens: Option, } @@ -31,10 +31,17 @@ pub struct Profile { pub yolo: bool, /// Shell command run in the worktree after hx; exit 0 = pass. None = no gate. pub gate: Option, + /// Extra hx attempts after a red gate (default 2). 0 = fail straight to needs-human. + #[serde(default = "default_retries")] + pub max_retries: u32, #[serde(default)] pub budget: Budget, } +fn default_retries() -> u32 { + 2 +} + fn default_hx() -> String { "hx".into() } diff --git a/src/run.rs b/src/run.rs index 2f96a55..cdc66cc 100644 --- a/src/run.rs +++ b/src/run.rs @@ -1,7 +1,7 @@ //! One run: worktree -> hx (NDJSON, budgets, process group) -> commit -> gate -> final state. use crate::profile::Profile; -use crate::state::{Run, Status, kill_group, log_path, now}; +use crate::state::{Run, Status, gate_log_path, kill_group, log_path, now}; use anyhow::{Context, Result, bail}; use serde_json::Value; use std::io::{BufRead, Write}; @@ -88,6 +88,9 @@ pub fn new_run(task: &Path, repo: &Path, profile: &str) -> Result { input_tokens: 0, output_tokens: 0, session: None, + attempts: 0, + turns: 0, + spent_tokens: 0, }) } @@ -98,7 +101,29 @@ fn fail(r: &mut Run, reason: impl Into) -> Result<()> { r.save() } -/// Runs the whole pipeline. Errors only for orch-internal problems; task failures end as `Failed` state. +/// Max bytes of gate output fed back to hx (the tail: errors are at the end). +const GATE_LOG_LIMIT: usize = 8000; + +fn tail(b: &[u8], limit: usize) -> String { + let s = String::from_utf8_lossy(&b[b.len().saturating_sub(limit)..]).into_owned(); + s.trim_start_matches('\u{FFFD}').to_string() +} + +fn retry_prompt(gate: &str, code: Option, out: &[u8], resumed: bool, body: &str) -> String { + let task = if resumed { + String::new() + } else { + format!("Task:\n{body}\n\n") + }; + format!( + "{task}The check `{gate}` failed (exit {}). Fix the code so it passes. Output (last {GATE_LOG_LIMIT} bytes):\n{}", + code.map_or("signal".into(), |c| c.to_string()), + tail(out, GATE_LOG_LIMIT) + ) +} + +/// Runs the whole pipeline. Errors only for orch-internal problems; task failures end as `Failed` or +/// `NeedsHuman` state. After a failed gate hx gets the gate output on the same session, up to `max_retries`. pub fn execute(r: &mut Run, p: &Profile, task: &Path) -> Result<()> { let (_, body) = read_task(task)?; r.save()?; @@ -108,50 +133,71 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Path) -> Result<()> { fail(r, format!("setup: {e}"))?; return Ok(()); } - r.status = Status::Running; - r.save()?; - let mut log = std::fs::File::create(log_path(&r.id))?; - let reason = run_hx(r, p, &body, &mut log)?; - if !git(&r.worktree, &["status", "--porcelain"])? - .trim() - .is_empty() - { - // keep hx's work on the branch even when it failed: nothing is lost - git(&r.worktree, &["add", "-A"])?; - git( - &r.worktree, - &["commit", "-qm", &format!("orch: {}", r.title)], - )?; - } - if let Some(reason) = reason { - return fail(r, reason); - } - if let Some(gate) = &p.gate { + let mut prompt = body.clone(); + let mut session: Option = None; + loop { + r.attempts += 1; + r.status = Status::Running; + r.save()?; + writeln!(log, "\n--- attempt {}", r.attempts)?; + let reason = run_hx(r, p, &prompt, session.as_deref(), &mut log)?; + if !git(&r.worktree, &["status", "--porcelain"])? + .trim() + .is_empty() + { + // keep hx's work on the branch even when it failed: nothing is lost + git(&r.worktree, &["add", "-A"])?; + let msg = format!("orch: {} (attempt {})", r.title, r.attempts); + git(&r.worktree, &["commit", "-qm", &msg])?; + } + if let Some(reason) = reason { + return fail(r, reason); + } + let Some(gate) = &p.gate else { break }; r.status = Status::Gating; r.save()?; writeln!(log, "\n--- gate: {gate}")?; - let st = Command::new("sh") - .args(["-c", gate]) + // ponytail: no gate timeout; a hanging gate hangs the run. Add gate_secs when it bites. + let o = Command::new("sh") + .args(["-c", &format!("({gate}) 2>&1")]) .current_dir(&r.worktree) - .stdout(log.try_clone()?) - .stderr(log.try_clone()?) - .status()?; - r.gate_exit = st.code(); - if !st.success() { - return fail(r, "gate-failed"); + .output()?; + log.write_all(&o.stdout)?; + r.gate_exit = o.status.code(); + if o.status.success() { + break; } + std::fs::write(gate_log_path(&r.id), &o.stdout)?; + if r.attempts > p.max_retries { + r.status = Status::NeedsHuman; + r.reason = Some("gate-failed".into()); + r.ended = Some(now()); + return r.save(); + } + session = r.session.clone(); + prompt = retry_prompt(gate, r.gate_exit, &o.stdout, session.is_some(), &body); } r.status = Status::Done; + r.reason = None; r.ended = Some(now()); r.save() } /// Returns the failure reason, or None when hx finished cleanly. -fn run_hx(r: &mut Run, p: &Profile, body: &str, log: &mut std::fs::File) -> Result> { +fn run_hx( + r: &mut Run, + p: &Profile, + body: &str, + session: Option<&str>, + log: &mut std::fs::File, +) -> Result> { let mut parts = p.hx.split_whitespace(); let mut cmd = Command::new(parts.next().context("empty hx command")?); cmd.args(parts).args(["-p", body, "--mode", "json"]); + if let Some(s) = session { + cmd.args(["--session", s]); + } if p.sandbox { cmd.arg("--sandbox"); } @@ -187,7 +233,7 @@ fn run_hx(r: &mut Run, p: &Profile, body: &str, log: &mut std::fs::File) -> Resu }); let deadline = Instant::now() + Duration::from_secs(p.wall_secs()); - let (mut turns, mut tokens, mut done) = (0u64, 0u64, None::); + let mut done = None::; let mut killed = None; loop { let left = deadline.saturating_duration_since(Instant::now()); @@ -199,16 +245,16 @@ fn run_hx(r: &mut Run, p: &Profile, body: &str, log: &mut std::fs::File) -> Resu }; match ev["type"].as_str() { Some("turn_start") => { - turns += 1; - if p.budget.max_turns.is_some_and(|m| turns > m) { + r.turns += 1; + if p.budget.max_turns.is_some_and(|m| r.turns > m) { killed = Some("budget:turns".to_string()); } } Some("stream") if ev["event"]["type"] == "done" => { let u = &ev["event"]["usage"]; - tokens += u["input_tokens"].as_u64().unwrap_or(0) + r.spent_tokens += u["input_tokens"].as_u64().unwrap_or(0) + u["output_tokens"].as_u64().unwrap_or(0); - if p.budget.max_tokens.is_some_and(|m| tokens > m) { + if p.budget.max_tokens.is_some_and(|m| r.spent_tokens > m) { killed = Some("budget:tokens".to_string()); } } diff --git a/src/state.rs b/src/state.rs index b97542e..6971d09 100644 --- a/src/state.rs +++ b/src/state.rs @@ -4,7 +4,7 @@ use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use std::path::PathBuf; -/// queued -> running -> gating -> done | failed. (retry and needs-human arrive with O2.) +/// queued -> running -> gating -> (retry: running) -> done | failed | needs-human. #[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)] #[serde(rename_all = "kebab-case")] pub enum Status { @@ -13,6 +13,8 @@ pub enum Status { Gating, Done, Failed, + /// Gate still red after all retries: branch holds the best attempt, gate output in `ID.gate.log`. + NeedsHuman, } impl Status { @@ -41,6 +43,14 @@ pub struct Run { pub input_tokens: u64, pub output_tokens: u64, pub session: Option, + /// hx runs so far (1 + retries). + #[serde(default)] + pub attempts: u32, + /// Budget counters, summed over all attempts. + #[serde(default)] + pub turns: u64, + #[serde(default)] + pub spent_tokens: u64, } pub fn now() -> u64 { @@ -53,6 +63,10 @@ pub fn runs_dir() -> PathBuf { crate::state_dir().join("runs") } +pub fn gate_log_path(id: &str) -> PathBuf { + runs_dir().join(format!("{id}.gate.log")) +} + pub fn log_path(id: &str) -> PathBuf { runs_dir().join(format!("{id}.log")) } @@ -144,6 +158,9 @@ mod tests { input_tokens: 0, output_tokens: 0, session: None, + attempts: 0, + turns: 0, + spent_tokens: 0, } } diff --git a/tests/e2e.py b/tests/e2e.py index 3df43e8..f9fc1cc 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -25,6 +25,9 @@ for i in range(int(body.split("TURNS=")[1].split()[0]) if "TURNS=" in body else e({"type": "turn_start"}) e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50}}}) if "WRITE" in body: open("out.txt", "w").write("x") +if "--session" in sys.argv: + open("retry-prompt.txt", "w").write(body) + if "RETRYFIX" in os.environ.get("MODE", "RETRYFIX"): open("out.txt", "w").write("x") e({"type": "done", "error": "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50}, "session": "/s.jsonl"}) ''') @@ -55,11 +58,24 @@ def check(p, st, reason=None): return s -profile("p", 'gate = "test -f out.txt"\n') +profile("p", 'gate = "test -f out.txt || { echo MARKER-GATE-OUT; exit 3; }"\n') s = check(run("ok", body="WRITE"), "done") assert s["gate_exit"] == 0 and s["input_tokens"] == 100 and s["session"] == "/s.jsonl", s assert "out.txt" in subprocess.run(["git", "ls-tree", "--name-only", s["branch"]], cwd=repo, capture_output=True, text=True).stdout -check(run("nowrite", body="x"), "failed", "gate-failed") +s = check(run("nowrite", body="NEVERFIX", env={"MODE": "NEVER"}), "needs-human", "gate-failed") +assert s["attempts"] == 3 and s["gate_exit"] != 0, s # 1 + 2 retries +assert "MARKER-GATE-OUT" in (tmp / "state/runs" / (s["id"] + ".gate.log")).read_text() +profile("r", 'gate = "test -f out.txt || { echo MARKER-GATE-OUT; exit 3; }"\nmax_retries = 1\n') +s = check(run("fixes", "r", body="x"), "done") +assert s["attempts"] == 2 and s["gate_exit"] == 0 and s["reason"] is None, s +sent = subprocess.run(["git", "show", s["branch"] + ":retry-prompt.txt"], cwd=repo, capture_output=True, text=True).stdout +assert "MARKER-GATE-OUT" in sent and "exit 3" in sent, sent # failure log reached hx on the resumed session +profile("z", 'gate = "false"\nmax_retries = 0\n') +s = check(run("noretry", "z", body="x"), "needs-human") +assert s["attempts"] == 1, s +profile("b", 'gate = "false"\nmax_retries = 2\n[budget]\nmax_turns = 2\n') +s = check(run("budget-across", "b", body="x"), "failed", "budget:turns") # budget spans attempts +assert (s["attempts"], s["turns"]) == (3, 3), s # 1 turn per attempt; 3rd turn exceeds 2 check(run("hxerr", body="FAIL WRITE"), "failed", "hx-failed: boom") check(run("nojson", body="NOJSON"), "failed", "hx-failed")