Allowlist with claude_cli: fail closed until hx#182; record provider mode (#18)

This commit was merged in pull request #18.
This commit is contained in:
hermes committed 2026-11-14 10:32:32 +00:00
1 parent 374cf28aed
commit a76c0ac16f
9 files changed
+259 -14

No files matched your search

+8 -1
View File
@@ -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 {
+2
View File
@@ -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).
//! 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};
+106 -8
View File
@@ -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<String>,
@@ -39,11 +43,56 @@ impl Rec {
}
}
fn unknown() -> String {
"unknown".into()
}
/// 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();
}
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 +103,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 +259,10 @@ fn pct(v: Option<f64>) -> 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 +274,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 +292,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 +312,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<String> {
let mut m: Vec<String> = 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 +332,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 +474,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 +565,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()));
+25
View File
@@ -112,6 +112,11 @@ fn usage_total(u: &Value) -> u64 {
.sum()
}
/// 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 {
let r = reason.to_lowercase();
@@ -304,6 +309,9 @@ fn run_hx(
let deadline = Instant::now() + Duration::from_secs(p.wall_secs());
let mut done = None::<Value>;
// 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());
@@ -320,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"]) {
@@ -397,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!(