From 2ff8abe7a355786b53db74aad62cdc5954d8b56e Mon Sep 17 00:00:00 2001 From: hermes Date: Fri, 13 Nov 2026 19:06:13 +0000 Subject: [PATCH 1/3] allow forces direct provider; provider_mode in telemetry; eval refuses mixed modes (closes #17) --- docs/safety.md | 20 ++++++++ src/main.rs | 9 +++- src/policy.rs | 7 ++- src/report.rs | 117 ++++++++++++++++++++++++++++++++++++++++--- tests/e2e.py | 17 +++++++ tests/fake_claude.py | 20 ++++++++ tests/fake_hx.py | 1 + tests/real_hx.py | 38 ++++++++++++++ 8 files changed, 219 insertions(+), 10 deletions(-) create mode 100644 tests/fake_claude.py diff --git a/docs/safety.md b/docs/safety.md index b876300..c23bbc2 100644 --- a/docs/safety.md +++ b/docs/safety.md @@ -32,6 +32,26 @@ after each attempt, rewritten before the next) and blocks the call before it exe Limit: plain `bash` (no pattern) is not confined; a shell cannot be parsed reliably. Use `sandbox = true` for that. A repo that already has its own `.hx/config.toml` is refused (`setup:` failure) so the guard is never silently skipped. +## Provider modes + +hx has two ways to reach Claude. They differ in what orch can enforce: + +| mode | who runs the tools | `allow` | `max_turns` | +|---|---|---|---| +| `direct` (API provider) | hx | enforced (guard + stream check) | counts model turns | +| `claude_cli` (hx starts the `claude` binary; auto-on when `claude` is in PATH and `HX_BASE_URL` is unset) | the `claude` binary; hx emits no `tool_call` events | cannot be enforced | meaningless: 1 hx request per run | + +With `allow` set, orch writes `claude_cli = false` into the generated worktree `.hx/config.toml` (project config +beats `~/.hx/config.toml`), so the run uses the direct provider and the allowlist holds. The direct Claude provider +bills OAuth calls as extra usage; if that is not acceptable, profiles for `claude_cli` must go without `allow` and +rely on `home`, the cleared environment and `sandbox = true`. orch warns for those (no allowlist). + +Telemetry records the mode (`provider_mode`: `claude_cli`, `direct`, `codex`; old lines `unknown`). `orch report` +shows it as a column and `orch eval` refuses to compare files with different (or mixed) modes ("NOT COMPARABLE", +exit 1): tokens, turns and tool behaviour differ by an order of magnitude between the modes. +Limit: the mode is derived from config and the `claude` binary, not from hx itself; hx' remembered last provider +(`last.json`) is not read, so set `provider` in profiles you compare. + ## Audit log `/audit.log`, append-only JSONL: `run_start` (profile, allowlist, sandbox, yolo), one `tool` line per call diff --git a/src/main.rs b/src/main.rs index deb400b..aa58d61 100644 --- a/src/main.rs +++ b/src/main.rs @@ -272,7 +272,14 @@ fn process( serde_json::json!({"status": r.status, "reason": r.reason, "attempts": r.attempts}), ); // a telemetry failure must not lose the run - if let Err(e) = report::append(telemetry, &report::rec(&r, &report::hx_version(p))) { + if let Err(e) = report::append( + telemetry, + &report::rec( + &r, + &report::hx_version(p), + &report::provider_mode(p, &r.worktree), + ), + ) { eprintln!("{}: telemetry: {e:#}", r.id); } if r.status == state::Status::Done { diff --git a/src/policy.rs b/src/policy.rs index 36be6c0..7b1d5f7 100644 --- a/src/policy.rs +++ b/src/policy.rs @@ -8,6 +8,8 @@ //! must stay inside the worktree or `read_roots`. Hard rules apply to every allowed call: no `git push` //! (publishing is the sink's job), no secret-looking paths, file tools stay in the worktree (reads may also //! use `read_roots`), writes never touch `.git` or `.hx` (guard config). +//! With `allow` set orch writes `claude_cli = false` into the generated worktree config: the `claude_cli` +//! provider executes tools inside the `claude` binary, invisible to hx' event bus, so it cannot be guarded. //! ponytail: plain `bash` is not confined (a shell cannot be parsed reliably); use `sandbox = true` for that. use anyhow::{Result, bail}; @@ -292,7 +294,10 @@ pub fn install(run: &str, wt: &Path, allow: &[String], read_roots: &[PathBuf]) - } std::fs::create_dir_all(cfg.parent().unwrap())?; let exe = std::env::current_exe()?.to_string_lossy().into_owned(); - let ext = toml::to_string(&json!({"extensions": [{ + // `claude_cli = false`: with the claude_cli provider the `claude` binary runs its own tools and hx emits no + // tool_call events, so neither the guard nor the stream check would see anything. The project config beats + // ~/.hx/config.toml, so this holds even when the profile's home enables claude_cli. + let ext = toml::to_string(&json!({"claude_cli": false, "extensions": [{ "command": [exe, "guard", pp.to_string_lossy()], "timeout_secs": 10}]}))?; std::fs::write(cfg, format!("{MARK}\n{ext}"))?; Ok(pol) diff --git a/src/report.rs b/src/report.rs index fe40b91..6620f79 100644 --- a/src/report.rs +++ b/src/report.rs @@ -15,6 +15,10 @@ pub struct Rec { pub task: String, pub profile: String, pub hx_version: String, + /// How hx talks to the model: `claude_cli` (the claude binary runs the tools; one hx request per run, turns + /// and tool events are not comparable), `direct`, `codex`. Old lines: `unknown`. + #[serde(default = "unknown")] + pub provider_mode: String, /// done | failed | needs-human | requeued pub status: String, pub reason: Option, @@ -39,11 +43,59 @@ impl Rec { } } +fn unknown() -> String { + "unknown".into() +} + +/// The mode hx will use for this profile and worktree, derived the way hx decides it: `allow` forces direct (see +/// policy.rs); else `claude_cli` in the worktree/home config; else auto = on when the claude binary starts and no +/// HX_BASE_URL is set. ponytail: ignores hx' remembered last provider (`last.json`), so a profile without +/// `provider` that hx routes to codex is still labelled claude_cli; set `provider` in profiles you compare. +pub fn provider_mode(p: &Profile, wt: &Path) -> String { + if p.provider.as_deref() == Some("codex") { + return "codex".into(); + } + if p.allow.is_some() { + return "direct".into(); + } + let home = p.home.clone().map(|h| h.join(".hx")); + let explicit = [ + Some(wt.join(".hx")), + std::env::var_os("HX_HOME") + .filter(|_| p.home.is_none()) + .map(PathBuf::from), + home, + ] + .into_iter() + .flatten() + .find_map(|d| { + let v: toml::Value = + toml::from_str(&std::fs::read_to_string(d.join("config.toml")).ok()?).ok()?; + v.get("claude_cli").map(|c| c.as_bool().unwrap_or(true)) // a list of args = on + }); + let on = explicit.unwrap_or_else(|| { + let env: Vec<_> = crate::run::hx_env(std::env::vars(), p); + let get = |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()); + get("HX_BASE_URL").is_none() && { + let bin = get("HX_CLAUDE_BIN").unwrap_or_else(|| "claude".into()); + let mut c = std::process::Command::new(bin); + c.arg("--version") + .env_clear() + .envs(env) + .stdin(std::process::Stdio::null()); + c.stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + c.status().is_ok_and(|s| s.success()) + } + }); + if on { "claude_cli" } else { "direct" }.into() +} + pub fn default_path() -> PathBuf { crate::state_dir().join("telemetry.jsonl") } -pub fn rec(r: &crate::state::Run, hx_version: &str) -> Rec { +pub fn rec(r: &crate::state::Run, hx_version: &str, mode: &str) -> Rec { let mut reason = r.reason.clone(); if let Some(s) = &mut reason { *s = s.chars().take(200).collect(); // keep every line far below PIPE_BUF: appends stay atomic @@ -54,6 +106,7 @@ pub fn rec(r: &crate::state::Run, hx_version: &str) -> Rec { task: r.task.clone(), profile: r.profile.clone(), hx_version: hx_version.into(), + provider_mode: mode.into(), status: serde_json::to_value(r.status) .ok() .and_then(|v| v.as_str().map(String::from)) @@ -209,9 +262,10 @@ fn pct(v: Option) -> String { pub fn report(recs: &[Rec]) -> String { let mut out = format!( - "{:<14} {:<22} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6}\n", + "{:<14} {:<22} {:<10} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6}\n", "profile", "hx-version", + "mode", "runs", "done", "rate", @@ -223,11 +277,12 @@ pub fn report(recs: &[Rec]) -> String { "cache", "med-s" ); - let mut line = |a: &str, b: &str, g: &Agg| { + let mut line = |a: &str, b: &str, m: &str, g: &Agg| { out.push_str(&format!( - "{:<14} {:<22} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6}\n", + "{:<14} {:<22} {:<10} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6}\n", a, b, + m, g.runs, g.done, pct(g.rate()), @@ -240,12 +295,18 @@ pub fn report(recs: &[Rec]) -> String { n(g.median_secs()) )); }; - for ((p, v), g) in group(recs, |r| (r.profile.clone(), r.hx_version.clone())) { - line(&p, &v, &g); + for ((p, v, m), g) in group(recs, |r| { + ( + r.profile.clone(), + r.hx_version.clone(), + r.provider_mode.clone(), + ) + }) { + line(&p, &v, &m, &g); } let mut all = Agg::default(); recs.iter().for_each(|r| all.add(r)); - line("all", "", &all); + line("all", "", "", &all); out.push_str(&format!( "retries (extra hx attempts after a red gate): {}\n", all.retries @@ -254,6 +315,13 @@ pub fn report(recs: &[Rec]) -> String { } /// Per case: done/finished and tokens per run, A vs B, plus a verdict. Returns (text, regressed). +fn modes(r: &[Rec]) -> Vec { + let mut m: Vec = r.iter().map(|r| r.provider_mode.clone()).collect(); + m.sort(); + m.dedup(); + m +} + pub fn compare(a: &[Rec], b: &[Rec], a_name: &str, b_name: &str) -> (String, bool) { let (ga, gb) = (group(a, |r| r.task.clone()), group(b, |r| r.task.clone())); let mut cases: Vec<&String> = ga.keys().chain(gb.keys()).collect(); @@ -267,7 +335,19 @@ pub fn compare(a: &[Rec], b: &[Rec], a_name: &str, b_name: &str) -> (String, boo (Some(x), Some(y)) if x > 0 => format!("{:+.0}%", (y as f64 - x as f64) * 100.0 / x as f64), _ => "-".into(), }; - let mut out = format!("A = {a_name}\nB = {b_name}\n\n"); + let (ma, mb) = (modes(a), modes(b)); + let mut out = format!( + "A = {a_name} [{}]\nB = {b_name} [{}]\n", + ma.join(","), + mb.join(",") + ); + // claude_cli runs the tools inside the claude binary (1 hx request per run): its tokens, turns and tool + // behaviour say nothing about the direct provider. Mixing modes would make any delta meaningless. + if ma != mb || ma.len() > 1 { + out.push_str("\nNOT COMPARABLE: the files use different provider modes (or mix modes). Re-run both with the same mode.\n"); + return (out, true); + } + out.push('\n'); out.push_str(&format!( "{:<24} {:>7} {:>7} {:>9} {:>9} {:>7}\n", "case", "A done", "B done", "A tok/run", "B tok/run", "tokens" @@ -397,6 +477,7 @@ mod tests { task: task.into(), profile: "p".into(), hx_version: "v1".into(), + provider_mode: "direct".into(), status: status.into(), reason: None, attempts, @@ -487,6 +568,26 @@ mod tests { ); } + #[test] + fn mixed_provider_modes_are_not_compared() { + let mut cli = r("x", "done", 1, 100, 1); + cli.provider_mode = "claude_cli".into(); + let (t, bad) = compare(&[r("x", "done", 1, 100, 1)], &[cli.clone()], "A", "B"); + assert!( + bad && t.contains("NOT COMPARABLE") + && t.contains("[direct]") + && t.contains("[claude_cli]"), + "{t}" + ); + let (_, bad) = compare(&[cli.clone()], &[cli.clone()], "A", "B"); + assert!(!bad, "same mode compares fine"); + let (_, bad) = compare(&[cli.clone(), r("y", "done", 1, 1, 1)], &[cli], "A", "B"); + assert!(bad, "a file that mixes modes is refused"); + // old lines (no field) are `unknown` and only compare with each other + let old: Rec = serde_json::from_str(r#"{"ts":1,"run":"r","task":"t","profile":"p","hx_version":"v","status":"done","reason":null,"attempts":1,"turns":1,"input_tokens":1,"output_tokens":0,"seconds":1}"#).unwrap(); + assert_eq!(old.provider_mode, "unknown"); + } + #[test] fn roundtrip_and_bad_lines() { let d = std::env::temp_dir().join(format!("orch-tel-{}", std::process::id())); diff --git a/tests/e2e.py b/tests/e2e.py index b372665..d6fb3ca 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -268,6 +268,23 @@ g.stdin.close() assert g.wait(timeout=5) == 0 assert len((tmp / "g-audit.log").read_text().splitlines()) == 4 +# O5 follow-up (#17): the generated guard config forces the direct provider, telemetry records the mode +s = check(run("cfgseen", "sec", env=senv, body="CALL write a.txt"), "done") +seen = git_show(s["branch"], "cfg-seen.txt") +assert "claude_cli = false" in seen and "orch-guard" in seen, seen +tel = tmp / "state/telemetry.jsonl" +recs2 = [json.loads(l) for l in tel.read_text().splitlines() if l.strip()] +assert [r["provider_mode"] for r in recs2 if r["task"] == "cfgseen"] == ["direct"], recs2[-3:] +# mode comparison: files from different modes are refused +fa, fb = tmp / "ma.jsonl", tmp / "mb.jsonl" +base = next(r for r in recs2 if r["task"] == "ok") +fa.write_text(json.dumps({**base, "provider_mode": "direct"}) + "\n") +fb.write_text(json.dumps({**base, "provider_mode": "claude_cli"}) + "\n") +cmp_ = subprocess.run([orch, "eval", str(fa), str(fb)], env=env, capture_output=True, text=True) +assert cmp_.returncode == 1 and "NOT COMPARABLE" in cmp_.stdout, cmp_ +assert subprocess.run([orch, "eval", str(fa), str(fa)], env=env, capture_output=True, text=True).returncode == 0 +assert "mode" in subprocess.run([orch, "report", str(fb)], env=env, capture_output=True, text=True).stdout.splitlines()[0] + # warning for unrestricted profiles assert "no `allow` list" in run("warn", "p", body="WRITE").stderr diff --git a/tests/fake_claude.py b/tests/fake_claude.py new file mode 100644 index 0000000..b2a589c --- /dev/null +++ b/tests/fake_claude.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +"""Fake `claude -p` for the claude_cli provider (orch tests). It is the process that "executes tools": it reads the +file named in $FAKE_CLAUDE_READ the way the real claude would (directly, no hx involved) and writes what it saw to +./claude-read.txt, then answers. Logs argv to $FAKE_CLAUDE_LOG.""" +import json, os, sys + +if "--version" in sys.argv: + print("fake") + sys.exit(0) +open(os.environ.get("FAKE_CLAUDE_LOG", "/dev/null"), "a").write(json.dumps(sys.argv[1:]) + "\n") +out = lambda o: print(json.dumps(o), flush=True) +target = os.environ.get("FAKE_CLAUDE_READ") +if target: + try: + open("claude-read.txt", "w").write(open(target).read()) + except OSError as e: + open("claude-read.txt", "w").write("ERR " + str(e)) +out({"type": "system", "subtype": "init", "session_id": "S1"}) +out({"type": "stream_event", "session_id": "S1", "event": {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "done"}}}) +out({"type": "result", "session_id": "S1", "is_error": False, "result": "done", "usage": {"input_tokens": 3, "output_tokens": 4}}) diff --git a/tests/fake_hx.py b/tests/fake_hx.py index 98ec9dd..7f7502e 100644 --- a/tests/fake_hx.py +++ b/tests/fake_hx.py @@ -39,6 +39,7 @@ if os.environ.get("SOLVE_DIR"): t = open(os.path.join(os.environ["SOLVE_DIR"], c, "task.md")).read().split("\n", 2)[2].strip() if t == body.strip() and c not in os.environ.get("SOLVE_SKIP", "").split(","): subprocess.run(["cp", "-R", os.path.join(os.environ["SOLVE_DIR"], c, "solution") + "/.", "."], check=True) +if os.path.exists(".hx/config.toml"): open("cfg-seen.txt", "w").write(open(".hx/config.toml").read()) if "ENVDUMP" in body: open("env.txt", "w").write("\n".join(sorted(os.environ))) if "NOJSON" in body: sys.exit(1) if "HANG" in body: diff --git a/tests/real_hx.py b/tests/real_hx.py index 364fa12..c64f955 100644 --- a/tests/real_hx.py +++ b/tests/real_hx.py @@ -51,6 +51,44 @@ try: ver = subprocess.run([str(hx), "--version"], capture_output=True, text=True).stdout.strip() assert ver and tel[-1]["hx_version"] == ver and tel[-1]["status"] == "needs-human", (tel, ver) print("real hx e2e ok:", st["reason"], "| audit by:", sorted({json.loads(l)["detail"].get("by", "guard") for l in audit.splitlines() if "decision" in l})) + # --- claude_cli mode (issue #17): the claude binary executes tools itself and hx emits no tool_call events --- + shutil.copy(root / "tests/fake_claude.py", tmp / "claude") + os.chmod(tmp / "claude", 0o755) + (home / ".hx/config.toml").write_text("claude_cli = []\n") # the profile's own home turns the provider on + cenv = '["HX_BASE_URL", "HX_CLAUDE_BIN", "FAKE_CLAUDE_READ", "FAKE_CLAUDE_LOG"]' + (cfg / "guarded.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["write"]\n') + (cfg / "open.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\n') + cenv_vars = {**env, "HX_CLAUDE_BIN": str(tmp / "claude"), "FAKE_CLAUDE_READ": str(secret), "FAKE_CLAUDE_LOG": str(tmp / "argv.log")} + + def go(profile_name, name): + (tmp / f"{name}.md").write_text(f"# {name}\nread the secret\n") + p = subprocess.run([orch, "run", str(tmp / f"{name}.md"), "--repo", str(repo), "--profile", profile_name], + env=cenv_vars, capture_output=True, text=True, timeout=120) + rid = p.stdout.split()[0] + st = json.loads(subprocess.run([orch, "status", rid], env=env, capture_output=True, text=True).stdout) + seen = subprocess.run(["git", "show", f"{st['branch']}:claude-read.txt"], cwd=repo, capture_output=True, text=True) + return st, seen.stdout if seen.returncode == 0 else None, p + + # control: without `allow` the claude binary really runs and reads the secret (proves the test is sensitive) + st, seen, p = go("open", "ctl") + assert seen == "PRIVATE-TOKEN-123", (seen, p.stdout, p.stderr, st) + last = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()][-1] + assert last["provider_mode"] == "claude_cli", last + # with `allow`: orch forces the direct provider, the claude binary never starts, the guard denies the Read + n_calls = len((tmp / "argv.log").read_text().splitlines()) + srv2 = subprocess.Popen([sys.executable, str(fake), str(port + 1), str(turns)]) + time.sleep(0.7) + cenv_vars["HX_BASE_URL"] = f"http://127.0.0.1:{port + 1}" + try: + st, seen, p = go("guarded", "gd") + finally: + srv2.terminate() + assert len((tmp / "argv.log").read_text().splitlines()) == n_calls, "claude binary was started despite allow" + assert seen is None or "PRIVATE-TOKEN-123" not in seen, seen + assert st["status"] == "needs-human" and st["reason"].startswith("policy:"), (st, p.stdout, p.stderr) + last = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()][-1] + assert last["provider_mode"] == "direct", last + print("claude_cli mode ok: allow forces direct, secret not read") finally: srv.terminate() shutil.rmtree(tmp, ignore_errors=True) -- 2.54.1 From 2751bcf27b5e0dc10924c2d343f702065c5a2ab8 Mon Sep 17 00:00:00 2001 From: hermes Date: Fri, 13 Nov 2026 19:14:31 +0000 Subject: [PATCH 2/3] refuse allow with claude_cli instead of forcing the direct provider --- docs/safety.md | 12 +++++++----- src/policy.rs | 9 +++------ src/report.rs | 9 +++------ src/run.rs | 10 ++++++++++ tests/e2e.py | 36 ++++++++++++++++++++++++++---------- tests/fake_hx.py | 1 - tests/real_hx.py | 17 +++++++++++------ 7 files changed, 60 insertions(+), 34 deletions(-) diff --git a/docs/safety.md b/docs/safety.md index c23bbc2..9ca88ef 100644 --- a/docs/safety.md +++ b/docs/safety.md @@ -39,12 +39,14 @@ hx has two ways to reach Claude. They differ in what orch can enforce: | mode | who runs the tools | `allow` | `max_turns` | |---|---|---|---| | `direct` (API provider) | hx | enforced (guard + stream check) | counts model turns | -| `claude_cli` (hx starts the `claude` binary; auto-on when `claude` is in PATH and `HX_BASE_URL` is unset) | the `claude` binary; hx emits no `tool_call` events | cannot be enforced | meaningless: 1 hx request per run | +| `claude_cli` (hx starts the `claude` binary; auto-on when `claude` is in PATH and `HX_BASE_URL` is unset) | the `claude` binary; hx emits no `tool_call` events and its permission bridge skips reads | cannot be enforced | meaningless: 1 hx request per run | -With `allow` set, orch writes `claude_cli = false` into the generated worktree `.hx/config.toml` (project config -beats `~/.hx/config.toml`), so the run uses the direct provider and the allowlist holds. The direct Claude provider -bills OAuth calls as extra usage; if that is not acceptable, profiles for `claude_cli` must go without `allow` and -rely on `home`, the cleared environment and `sandbox = true`. orch warns for those (no allowlist). +A profile with `allow` in `claude_cli` mode is **refused** before hx starts: the run ends `needs-human` with +`policy: allow cannot be enforced ...`. orch never runs "guarded" without a guard and never switches providers +silently (the direct Claude provider is not usable on every subscription). Options for such a profile: +no `allow` plus `sandbox = true`, `home`, the cleared environment; or `claude_cli = false` in the profile's hx config +if the direct provider works for you. Planned: make the claude_cli provider guardable in hx (permission bridge on +the event bus, tool events), see the linked hx issue. Telemetry records the mode (`provider_mode`: `claude_cli`, `direct`, `codex`; old lines `unknown`). `orch report` shows it as a column and `orch eval` refuses to compare files with different (or mixed) modes ("NOT COMPARABLE", diff --git a/src/policy.rs b/src/policy.rs index 7b1d5f7..45e89f7 100644 --- a/src/policy.rs +++ b/src/policy.rs @@ -8,8 +8,8 @@ //! must stay inside the worktree or `read_roots`. Hard rules apply to every allowed call: no `git push` //! (publishing is the sink's job), no secret-looking paths, file tools stay in the worktree (reads may also //! use `read_roots`), writes never touch `.git` or `.hx` (guard config). -//! With `allow` set orch writes `claude_cli = false` into the generated worktree config: the `claude_cli` -//! provider executes tools inside the `claude` binary, invisible to hx' event bus, so it cannot be guarded. +//! Not enforceable with hx' `claude_cli` provider: the `claude` binary runs its own tools, invisible to hx' event +//! bus. `run::execute` refuses such a run up front (see `report::provider_mode`) instead of running it unguarded. //! ponytail: plain `bash` is not confined (a shell cannot be parsed reliably); use `sandbox = true` for that. use anyhow::{Result, bail}; @@ -294,10 +294,7 @@ pub fn install(run: &str, wt: &Path, allow: &[String], read_roots: &[PathBuf]) - } std::fs::create_dir_all(cfg.parent().unwrap())?; let exe = std::env::current_exe()?.to_string_lossy().into_owned(); - // `claude_cli = false`: with the claude_cli provider the `claude` binary runs its own tools and hx emits no - // tool_call events, so neither the guard nor the stream check would see anything. The project config beats - // ~/.hx/config.toml, so this holds even when the profile's home enables claude_cli. - let ext = toml::to_string(&json!({"claude_cli": false, "extensions": [{ + let ext = toml::to_string(&json!({"extensions": [{ "command": [exe, "guard", pp.to_string_lossy()], "timeout_secs": 10}]}))?; std::fs::write(cfg, format!("{MARK}\n{ext}"))?; Ok(pol) diff --git a/src/report.rs b/src/report.rs index 6620f79..e4651eb 100644 --- a/src/report.rs +++ b/src/report.rs @@ -47,17 +47,14 @@ fn unknown() -> String { "unknown".into() } -/// The mode hx will use for this profile and worktree, derived the way hx decides it: `allow` forces direct (see -/// policy.rs); else `claude_cli` in the worktree/home config; else auto = on when the claude binary starts and no -/// HX_BASE_URL is set. ponytail: ignores hx' remembered last provider (`last.json`), so a profile without +/// The mode hx will use for this profile and worktree, derived the way hx decides it: `provider = "codex"`; else +/// `claude_cli` in the worktree/home config; else auto = on when the claude binary starts and no HX_BASE_URL is +/// set (HX_BASE_URL only counts when the profile passes it on, like hx sees it). ponytail: ignores hx' remembered last provider (`last.json`), so a profile without /// `provider` that hx routes to codex is still labelled claude_cli; set `provider` in profiles you compare. pub fn provider_mode(p: &Profile, wt: &Path) -> String { if p.provider.as_deref() == Some("codex") { return "codex".into(); } - if p.allow.is_some() { - return "direct".into(); - } let home = p.home.clone().map(|h| h.join(".hx")); let explicit = [ Some(wt.join(".hx")), diff --git a/src/run.rs b/src/run.rs index ebaf2a1..d2e6a1d 100644 --- a/src/run.rs +++ b/src/run.rs @@ -112,6 +112,8 @@ fn usage_total(u: &Value) -> u64 { .sum() } +const REFUSE_CLAUDE_CLI: &str = "`allow` cannot be enforced with hx' claude_cli provider (the claude binary runs its own tools, hx sees no tool calls). Remove `allow` and use `sandbox = true`, or set `claude_cli = false` in the profile's hx config to use the direct provider."; + /// hx surfaces provider rejections as `api 429: ...`; also match the usual wording. fn is_rate_limit(reason: &str) -> bool { let r = reason.to_lowercase(); @@ -169,6 +171,14 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> { return Ok(()); } let mut log = std::fs::File::create(log_path(&r.id))?; + if p.allow.is_some() && crate::report::provider_mode(p, &r.worktree) == "claude_cli" { + // never run "guarded" without a guard: the claude binary's tools are invisible to hx and orch + writeln!(log, "{REFUSE_CLAUDE_CLI}")?; + r.status = Status::NeedsHuman; + r.reason = Some(format!("policy: {REFUSE_CLAUDE_CLI}")); + r.ended = Some(now()); + return r.save(); + } let mut prompt = body.clone(); let mut session: Option = None; loop { diff --git a/tests/e2e.py b/tests/e2e.py index d6fb3ca..b10783b 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -5,7 +5,8 @@ import json, os, pathlib, shutil, signal, subprocess, sys, tempfile, time root = pathlib.Path(__file__).resolve().parent.parent orch = sys.argv[1] if len(sys.argv) > 1 else str(root / "target/debug/orch") tmp = pathlib.Path(tempfile.mkdtemp()) -env = {**os.environ, "ORCH_CONFIG_DIR": str(tmp / "cfg"), "ORCH_STATE_DIR": str(tmp / "state")} +# hermetic provider mode: no `claude` binary, whatever the host has (a host with claude in PATH would be claude_cli) +env = {**os.environ, "HX_CLAUDE_BIN": "/nonexistent/claude", "ORCH_CONFIG_DIR": str(tmp / "cfg"), "ORCH_STATE_DIR": str(tmp / "state")} repo = tmp / "repo" repo.mkdir() subprocess.run(["git", "init", "-q", "-b", "main"], cwd=repo, check=True) @@ -18,10 +19,10 @@ shutil.copy(root / "tests/fake_hx.py", fake) def profile(name, extra=""): # test knobs pass through the (otherwise cleared) hx environment; the secrets used by the O5 tests do not top, _, rest = extra.partition("\n[") if "\n[" in extra else (extra, "", "") - body = f'hx = "{sys.executable} {fake}"\nenv = ["MODE", "CONC", "PIDFILE"]\n{top}' + body = f'hx = "{sys.executable} {fake}"\nenv = ["MODE", "CONC", "PIDFILE", "HX_CLAUDE_BIN"]\n{top}' if "env = [" in extra: # profile brings its own env list: merge - body = body.replace('env = ["MODE", "CONC", "PIDFILE"]\n', "") - top = top.replace("env = [", 'env = ["MODE", "CONC", "PIDFILE", ') + body = body.replace('env = ["MODE", "CONC", "PIDFILE", "HX_CLAUDE_BIN"]\n', "") + top = top.replace("env = [", 'env = ["MODE", "CONC", "PIDFILE", "HX_CLAUDE_BIN", ') body = f'hx = "{sys.executable} {fake}"\n{top}' (tmp / f"cfg/profiles/{name}.toml").write_text(body + (f"\n[{rest}" if rest else "")) @@ -50,6 +51,7 @@ def check(p, st, reason=None): profile("p", 'gate = "test -f out.txt || { echo MARKER-GATE-OUT; exit 3; }"\n') s = check(run("ok", body="WRITE"), "done") +ok_id = s["id"] assert s["gate_exit"] == 0 and s["input_tokens"] == 100 and s["session"] == "/s.jsonl", s assert (s["cache_read_tokens"], s["cache_write_tokens"]) == (1000, 10), s assert "out.txt" in subprocess.run(["git", "ls-tree", "--name-only", s["branch"]], cwd=repo, capture_output=True, text=True).stdout @@ -268,13 +270,27 @@ g.stdin.close() assert g.wait(timeout=5) == 0 assert len((tmp / "g-audit.log").read_text().splitlines()) == 4 -# O5 follow-up (#17): the generated guard config forces the direct provider, telemetry records the mode -s = check(run("cfgseen", "sec", env=senv, body="CALL write a.txt"), "done") -seen = git_show(s["branch"], "cfg-seen.txt") -assert "claude_cli = false" in seen and "orch-guard" in seen, seen +# provider mode is recorded; with `allow` + claude_cli the run is refused instead of running unguarded (#17) +s = check(run("direct-mode", "sec", env=senv, body="CALL write a.txt"), "done") tel = tmp / "state/telemetry.jsonl" recs2 = [json.loads(l) for l in tel.read_text().splitlines() if l.strip()] -assert [r["provider_mode"] for r in recs2 if r["task"] == "cfgseen"] == ["direct"], recs2[-3:] +assert [r["provider_mode"] for r in recs2 if r["task"] == "direct-mode"] == ["direct"], recs2[-3:] +fakecl = tmp / "claude" +fakecl.write_text("#!/bin/sh\n[ \"$1\" = --version ] && echo fake\nexit 0\n") +fakecl.chmod(0o755) +cenv = {"HX_CLAUDE_BIN": str(fakecl)} # a claude binary exists => hx would pick claude_cli +s = check(run("refuse", "sec", env=cenv, body="CALL write a.txt"), "needs-human", "policy: `allow` cannot be enforced") +assert s["attempts"] == 0 and s["hx_exit"] is None, s # hx was never started +assert "claude_cli = false" in (tmp / "state/runs" / (s["id"] + ".log")).read_text() +# explicit opt-out in the profile's hx config => direct, allowed again +(work_home / ".hx").mkdir(exist_ok=True) +(work_home / ".hx/config.toml").write_text("claude_cli = false\n") +check(run("optout", "sec", env=cenv, body="CALL write a.txt"), "done") +(work_home / ".hx/config.toml").unlink() +# without `allow` claude_cli runs as before (recorded as claude_cli) +profile("noallow", f'home = "{work_home}"\n') +check(run("cli-ok", "noallow", env=cenv, body="WRITE"), "done") +assert [json.loads(l)["provider_mode"] for l in tel.read_text().splitlines() if l.strip()][-1] == "claude_cli" # mode comparison: files from different modes are refused fa, fb = tmp / "ma.jsonl", tmp / "mb.jsonl" base = next(r for r in recs2 if r["task"] == "ok") @@ -371,6 +387,6 @@ try: except ProcessLookupError: pass -logs = subprocess.run([orch, "logs", s["id"]], env=env, capture_output=True, text=True).stdout +logs = subprocess.run([orch, "logs", ok_id], env=env, capture_output=True, text=True).stdout assert '"type": "done"' in logs or '"type":"done"' in logs, logs print("e2e ok") diff --git a/tests/fake_hx.py b/tests/fake_hx.py index 7f7502e..98ec9dd 100644 --- a/tests/fake_hx.py +++ b/tests/fake_hx.py @@ -39,7 +39,6 @@ if os.environ.get("SOLVE_DIR"): t = open(os.path.join(os.environ["SOLVE_DIR"], c, "task.md")).read().split("\n", 2)[2].strip() if t == body.strip() and c not in os.environ.get("SOLVE_SKIP", "").split(","): subprocess.run(["cp", "-R", os.path.join(os.environ["SOLVE_DIR"], c, "solution") + "/.", "."], check=True) -if os.path.exists(".hx/config.toml"): open("cfg-seen.txt", "w").write(open(".hx/config.toml").read()) if "ENVDUMP" in body: open("env.txt", "w").write("\n".join(sorted(os.environ))) if "NOJSON" in body: sys.exit(1) if "HANG" in body: diff --git a/tests/real_hx.py b/tests/real_hx.py index c64f955..7686c69 100644 --- a/tests/real_hx.py +++ b/tests/real_hx.py @@ -74,21 +74,26 @@ try: assert seen == "PRIVATE-TOKEN-123", (seen, p.stdout, p.stderr, st) last = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()][-1] assert last["provider_mode"] == "claude_cli", last - # with `allow`: orch forces the direct provider, the claude binary never starts, the guard denies the Read + # with `allow`: refused before hx starts, so the claude binary never runs and the secret stays unread n_calls = len((tmp / "argv.log").read_text().splitlines()) + st, seen, p = go("guarded", "gd") + assert len((tmp / "argv.log").read_text().splitlines()) == n_calls, "claude binary was started despite allow" + assert seen is None, seen + assert st["status"] == "needs-human" and "cannot be enforced" in st["reason"], (st, p.stdout, p.stderr) + # the escape hatch: the direct provider in the profile's hx config makes `allow` enforceable again + (home / ".hx/config.toml").write_text("claude_cli = false\n") srv2 = subprocess.Popen([sys.executable, str(fake), str(port + 1), str(turns)]) time.sleep(0.7) cenv_vars["HX_BASE_URL"] = f"http://127.0.0.1:{port + 1}" try: - st, seen, p = go("guarded", "gd") + st, seen, p = go("guarded", "gd2") finally: srv2.terminate() - assert len((tmp / "argv.log").read_text().splitlines()) == n_calls, "claude binary was started despite allow" - assert seen is None or "PRIVATE-TOKEN-123" not in seen, seen - assert st["status"] == "needs-human" and st["reason"].startswith("policy:"), (st, p.stdout, p.stderr) + assert st["status"] == "needs-human" and st["reason"].startswith("policy: ") and "cannot be enforced" not in st["reason"], (st, p.stdout) + assert seen is None or "PRIVATE-TOKEN-123" not in seen last = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()][-1] assert last["provider_mode"] == "direct", last - print("claude_cli mode ok: allow forces direct, secret not read") + print("claude_cli mode ok: allow refused with claude_cli, enforced with direct") finally: srv.terminate() shutil.rmtree(tmp, ignore_errors=True) -- 2.54.1 From 80ea84f8f6e60c0096a9239e077bfb93f2721591 Mon Sep 17 00:00:00 2001 From: hermes Date: Sat, 14 Nov 2026 10:22:29 +0000 Subject: [PATCH 3/3] accept allow with claude_cli, fail closed when tool calls are unseen --- docs/safety.md | 23 ++++++++++++----------- src/run.rs | 33 ++++++++++++++++++++++++--------- tests/e2e.py | 16 ++++++++-------- tests/fake_claude.py | 3 +++ tests/fake_hx.py | 4 ++++ tests/real_hx.py | 23 +++++------------------ 6 files changed, 56 insertions(+), 46 deletions(-) diff --git a/docs/safety.md b/docs/safety.md index 9ca88ef..33035df 100644 --- a/docs/safety.md +++ b/docs/safety.md @@ -34,19 +34,20 @@ A repo that already has its own `.hx/config.toml` is refused (`setup:` failure) ## Provider modes -hx has two ways to reach Claude. They differ in what orch can enforce: +hx reaches Claude in two ways: -| mode | who runs the tools | `allow` | `max_turns` | -|---|---|---|---| -| `direct` (API provider) | hx | enforced (guard + stream check) | counts model turns | -| `claude_cli` (hx starts the `claude` binary; auto-on when `claude` is in PATH and `HX_BASE_URL` is unset) | the `claude` binary; hx emits no `tool_call` events and its permission bridge skips reads | cannot be enforced | meaningless: 1 hx request per run | +| mode | who runs the tools | what orch sees | +|---|---|---| +| `direct` (API provider) | hx | every tool as a `tool_call` event | +| `claude_cli` (hx starts the `claude` binary; auto-on when `claude` is in PATH and `HX_BASE_URL` is unset) | the `claude` binary | with johannes/hx#182: every tool as a `tool_call` event, decided by the guard through hx' permission bridge; without it: only a `[claude TOOL: ...]` text line | -A profile with `allow` in `claude_cli` mode is **refused** before hx starts: the run ends `needs-human` with -`policy: allow cannot be enforced ...`. orch never runs "guarded" without a guard and never switches providers -silently (the direct Claude provider is not usable on every subscription). Options for such a profile: -no `allow` plus `sandbox = true`, `home`, the cleared environment; or `claude_cli = false` in the profile's hx config -if the direct provider works for you. Planned: make the claude_cli provider guardable in hx (permission bridge on -the event bus, tool events), see the linked hx issue. +`allow` works in both modes **provided hx reports claude's tools as `tool_call` events** (hx#182). orch checks this +on every run: it counts the `[claude ...]` tool lines in the text stream and the `tool_call` events. If claude used +more tools than hx reported, the run ends `needs-human` with `policy: claude used N tool(s) but hx reported M +tool_call event(s) ...`: a profile is never silently unguarded. On an hx without #182 every claude_cli run that +uses a tool therefore fails closed; the tool has already run by then (the check is after the fact), so on such an hx +use no `allow` plus `sandbox = true` for claude_cli profiles. +`max_turns` counts model turns; in claude_cli mode there is one hx request per run, so it is not a useful limit there. Telemetry records the mode (`provider_mode`: `claude_cli`, `direct`, `codex`; old lines `unknown`). `orch report` shows it as a column and `orch eval` refuses to compare files with different (or mixed) modes ("NOT COMPARABLE", diff --git a/src/run.rs b/src/run.rs index d2e6a1d..af444e9 100644 --- a/src/run.rs +++ b/src/run.rs @@ -112,7 +112,10 @@ fn usage_total(u: &Value) -> u64 { .sum() } -const REFUSE_CLAUDE_CLI: &str = "`allow` cannot be enforced with hx' claude_cli provider (the claude binary runs its own tools, hx sees no tool calls). Remove `allow` and use `sandbox = true`, or set `claude_cli = false` in the profile's hx config to use the direct provider."; +/// The line hx' claude_cli provider writes into the text stream for every tool claude runs: `\n[claude Bash: ls]\n`. +fn is_claude_tool_line(t: &str) -> bool { + t.starts_with("\n[claude ") && t.ends_with("]\n") && t.len() > 12 +} /// hx surfaces provider rejections as `api 429: ...`; also match the usual wording. fn is_rate_limit(reason: &str) -> bool { @@ -171,14 +174,6 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> { return Ok(()); } let mut log = std::fs::File::create(log_path(&r.id))?; - if p.allow.is_some() && crate::report::provider_mode(p, &r.worktree) == "claude_cli" { - // never run "guarded" without a guard: the claude binary's tools are invisible to hx and orch - writeln!(log, "{REFUSE_CLAUDE_CLI}")?; - r.status = Status::NeedsHuman; - r.reason = Some(format!("policy: {REFUSE_CLAUDE_CLI}")); - r.ended = Some(now()); - return r.save(); - } let mut prompt = body.clone(); let mut session: Option = None; loop { @@ -314,6 +309,9 @@ fn run_hx( let deadline = Instant::now() + Duration::from_secs(p.wall_secs()); let mut done = None::; + // claude_cli: claude runs the tools; hx prints a `[claude TOOL: ...]` line per tool use and (hx#182) reports + // each one as a tool_call event so the guard can decide. Fewer events than lines = something ran unseen. + let (mut claude_lines, mut calls) = (0u32, 0u32); let mut killed = None; loop { let left = deadline.saturating_duration_since(Instant::now()); @@ -330,7 +328,17 @@ fn run_hx( killed = Some("budget:turns".to_string()); } } + Some("stream") + if pol.is_some() + && ev["event"]["type"] == "text_delta" + && is_claude_tool_line( + ev["event"]["text"].as_str().unwrap_or_default(), + ) => + { + claude_lines += 1; + } Some("tool_call") if pol.is_some() => { + calls += 1; // second line of defence: hx treats a dead or slow guard as "continue" let name = ev["name"].as_str().unwrap_or_default(); if let Decision::Deny(why) = pol.unwrap().decide(name, &ev["args"]) { @@ -407,6 +415,13 @@ fn run_hx( if let Some(k) = killed { return Ok(Some(k)); } + if pol.is_some() && calls < claude_lines { + // fail closed: never call a run guarded when claude used tools hx did not report to the guard + return Ok(Some(format!( + "policy: claude used {claude_lines} tool(s) but hx reported {calls} tool_call event(s); the allowlist \ + could not be enforced for this run (hx without claude_cli tool events, see johannes/hx#182)" + ))); + } Ok(match &done { None => Some("hx-failed: no done event".into()), Some(d) if !d["error"].is_null() => Some(format!( diff --git a/tests/e2e.py b/tests/e2e.py index b10783b..5a1b7af 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -279,14 +279,14 @@ fakecl = tmp / "claude" fakecl.write_text("#!/bin/sh\n[ \"$1\" = --version ] && echo fake\nexit 0\n") fakecl.chmod(0o755) cenv = {"HX_CLAUDE_BIN": str(fakecl)} # a claude binary exists => hx would pick claude_cli -s = check(run("refuse", "sec", env=cenv, body="CALL write a.txt"), "needs-human", "policy: `allow` cannot be enforced") -assert s["attempts"] == 0 and s["hx_exit"] is None, s # hx was never started -assert "claude_cli = false" in (tmp / "state/runs" / (s["id"] + ".log")).read_text() -# explicit opt-out in the profile's hx config => direct, allowed again -(work_home / ".hx").mkdir(exist_ok=True) -(work_home / ".hx/config.toml").write_text("claude_cli = false\n") -check(run("optout", "sec", env=cenv, body="CALL write a.txt"), "done") -(work_home / ".hx/config.toml").unlink() +# claude_cli + allow: every tool claude runs must reach the guard as a tool_call (hx#182); fewer = fail closed +s = check(run("cli-seen", "sec", env=cenv, body="CLAUDE\nCALL write a.txt\nCALL bash cargo test -p x"), "done") +s = check(run("cli-deny", "sec", env=cenv, body=f"CLAUDE\nCALL read {private}/auth.json"), "needs-human", "policy:") +assert "PRIVATE-TOKEN-123" not in git_show(s["branch"], "calls.txt") +s = check(run("cli-unseen", "sec", env=cenv, body="CLAUDE UNSEEN\nCALL write a.txt"), "needs-human", "policy: claude used 1 tool(s) but hx reported 0") +assert "johannes/hx#182" in s["reason"] or "hx#182" in s["reason"], s +# no claude lines => nothing to cross-check (direct provider): unaffected +check(run("direct-ok", "sec", env=senv, body="CALL write a.txt"), "done") # without `allow` claude_cli runs as before (recorded as claude_cli) profile("noallow", f'home = "{work_home}"\n') check(run("cli-ok", "noallow", env=cenv, body="WRITE"), "done") diff --git a/tests/fake_claude.py b/tests/fake_claude.py index b2a589c..8d6bfef 100644 --- a/tests/fake_claude.py +++ b/tests/fake_claude.py @@ -16,5 +16,8 @@ if target: except OSError as e: open("claude-read.txt", "w").write("ERR " + str(e)) out({"type": "system", "subtype": "init", "session_id": "S1"}) +if os.environ.get("FAKE_CLAUDE_READ"): + out({"type": "assistant", "session_id": "S1", "message": {"content": [ + {"type": "tool_use", "name": "Read", "input": {"file_path": os.environ["FAKE_CLAUDE_READ"]}}]}}) out({"type": "stream_event", "session_id": "S1", "event": {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "done"}}}) out({"type": "result", "session_id": "S1", "is_error": False, "result": "done", "usage": {"input_tokens": 3, "output_tokens": 4}}) diff --git a/tests/fake_hx.py b/tests/fake_hx.py index 98ec9dd..5ba686f 100644 --- a/tests/fake_hx.py +++ b/tests/fake_hx.py @@ -21,6 +21,10 @@ def guard(name, args): for n, l in enumerate(x for x in body.splitlines() if x.startswith("CALL ")): _, name, arg = l.split(" ", 2) args = {"command": arg} if name == "bash" else {"path": arg} + if "CLAUDE" in body: # claude_cli: hx prints a text line per tool claude runs + e({"type": "stream", "event": {"type": "text_delta", "text": f"\n[claude {name}: {arg}]\n"}}) + if "UNSEEN" in body: # hx without #182: the line is there, the tool_call event is not + continue e({"type": "tool_call", "id": f"c{n}", "name": name, "args": args}) r = guard(name, args) if r and r["action"] == "block": diff --git a/tests/real_hx.py b/tests/real_hx.py index 7686c69..371529f 100644 --- a/tests/real_hx.py +++ b/tests/real_hx.py @@ -74,26 +74,13 @@ try: assert seen == "PRIVATE-TOKEN-123", (seen, p.stdout, p.stderr, st) last = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()][-1] assert last["provider_mode"] == "claude_cli", last - # with `allow`: refused before hx starts, so the claude binary never runs and the secret stays unread - n_calls = len((tmp / "argv.log").read_text().splitlines()) + # with `allow` on today's hx (no tool events for claude's tools, hx#182): fail closed, never "guarded" st, seen, p = go("guarded", "gd") - assert len((tmp / "argv.log").read_text().splitlines()) == n_calls, "claude binary was started despite allow" - assert seen is None, seen - assert st["status"] == "needs-human" and "cannot be enforced" in st["reason"], (st, p.stdout, p.stderr) - # the escape hatch: the direct provider in the profile's hx config makes `allow` enforceable again - (home / ".hx/config.toml").write_text("claude_cli = false\n") - srv2 = subprocess.Popen([sys.executable, str(fake), str(port + 1), str(turns)]) - time.sleep(0.7) - cenv_vars["HX_BASE_URL"] = f"http://127.0.0.1:{port + 1}" - try: - st, seen, p = go("guarded", "gd2") - finally: - srv2.terminate() - assert st["status"] == "needs-human" and st["reason"].startswith("policy: ") and "cannot be enforced" not in st["reason"], (st, p.stdout) - assert seen is None or "PRIVATE-TOKEN-123" not in seen + assert st["status"] == "needs-human" and "could not be enforced" in st["reason"], (st, p.stdout, p.stderr) last = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()][-1] - assert last["provider_mode"] == "direct", last - print("claude_cli mode ok: allow refused with claude_cli, enforced with direct") + assert last["provider_mode"] == "claude_cli", last + # (the fake claude has already read the secret by then: this hx cannot stop it, which is what hx#182 is for) + print("claude_cli mode ok: unseen tool use fails closed (hx#182 missing)") finally: srv.terminate() shutil.rmtree(tmp, ignore_errors=True) -- 2.54.1