garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

cartopolis-agent · 2026-11-21T19:38:58Z

fix(hook): run a project's hooks only as they are on its main

`midas hook projects` ran the hooks in each worktree's
.claude/settings.json and settings.local.json as `sh -c`, in the
runner's account with its environment, hub key included. Claude Code
has the person look at a project's hook changes before they run; this
relay had nobody to ask, so a branch that edited the file — a session's
own, or a project a prompt had it add — ran on the runner at the next
tool call, before anyone read the diff. Found by the review before the
code went public.

A worktree's hooks now run only when its settings.json is exactly the
one on the project's main (origin/main, or main where there is no
origin): landing is the review. A differing copy is said on stderr and
runs nothing, not even the unchanged entries. settings.local.json is
nobody's reviewed file and never runs. The hook's environment loses
MIDAS_HUB_KEY.
src/hook.rs | 75 +++++++++++++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 58 insertions(+), 17 deletions(-)

diff --git a/src/hook.rs b/src/hook.rs
index 2596cfe..897222d 100644
--- a/src/hook.rs
+++ b/src/hook.rs
@@ -468,27 +468,50 @@ fn matches(matcher: Option<&str>, tool: Option<&str>) -> bool {
     })
 }
 
-/// The hooks project worktree `tree` has for `event` (its settings and its
-/// local settings), each as (command, timeout in seconds), for `tool`.
+/// The hooks project worktree `tree` has for `event`, each as (command,
+/// timeout in seconds), for `tool` — from its `.claude/settings.json` as it is
+/// **on the project's main**, and only when the worktree's copy is that one.
+///
+/// Claude Code has the person look at a project's hook changes before it runs
+/// them; this relay has nobody to ask, and runs in the runner's account with
+/// its environment. A branch that edits the file (a session's own, or a
+/// project a prompt had it add) would otherwise run on the runner at the next
+/// tool call, before anyone read the diff. Landed is what counts as read.
+/// `settings.local.json` is nobody's reviewed file and is never run.
 fn hooks_of(tree: &Path, event: &str, tool: Option<&str>) -> Vec<(String, u64)> {
     let mut found = Vec::new();
-    for f in ["settings.json", "settings.local.json"] {
-        let Ok(text) = std::fs::read_to_string(tree.join(".claude").join(f)) else { continue };
-        let Ok(v) = serde_json::from_str::<Value>(&text) else { continue };
-        for entry in v["hooks"][event].as_array().into_iter().flatten() {
-            if !matches(entry["matcher"].as_str(), tool) {
-                continue;
-            }
-            for h in entry["hooks"].as_array().into_iter().flatten().filter(|h| h["type"] == "command") {
-                if let Some(c) = h["command"].as_str() {
-                    found.push((c.to_string(), h["timeout"].as_u64().unwrap_or(60).clamp(1, 600)));
-                }
+    let Some(text) = landed_settings(tree) else { return found };
+    let Ok(v) = serde_json::from_str::<Value>(&text) else { return found };
+    for entry in v["hooks"][event].as_array().into_iter().flatten() {
+        if !matches(entry["matcher"].as_str(), tool) {
+            continue;
+        }
+        for h in entry["hooks"].as_array().into_iter().flatten().filter(|h| h["type"] == "command") {
+            if let Some(c) = h["command"].as_str() {
+                found.push((c.to_string(), h["timeout"].as_u64().unwrap_or(60).clamp(1, 600)));
             }
         }
     }
     found
 }
 
+/// `.claude/settings.json` of `tree` when it is exactly the one on the
+/// project's main (`origin/main`, or `main` in a checkout with no origin);
+/// None, and a line on stderr, when the worktree's differs or main has none.
+fn landed_settings(tree: &Path) -> Option<String> {
+    let working = std::fs::read_to_string(tree.join(".claude/settings.json")).ok()?;
+    let landed = ["origin/main", "main"].iter().find_map(|r| {
+        let out = Command::new("git").args(["-C"]).arg(tree).args(["show", &format!("{r}:.claude/settings.json")])
+            .stdin(Stdio::null()).output().ok()?;
+        out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
+    })?;
+    if landed != working {
+        eprintln!("midas: {}/.claude/settings.json differs from main's: its hooks run once that lands", tree.display());
+        return None;
+    }
+    Some(working)
+}
+
 /// A pipe read to its end on a thread of its own; what it read comes on the channel.
 fn drain<R: Read + Send + 'static>(pipe: Option<R>) -> std::sync::mpsc::Receiver<String> {
     let (tx, rx) = std::sync::mpsc::channel();
@@ -511,7 +534,9 @@ fn drain<R: Read + Send + 'static>(pipe: Option<R>) -> std::sync::mpsc::Receiver
 fn run_hook(tree: &Path, command: &str, timeout: u64, input: &str) -> Said {
     use std::io::Write;
     use std::os::unix::process::CommandExt;
+    // Without the hub key: a project's hook reads the session's input, not the workspace's credential.
     let child = Command::new("sh").arg("-c").arg(command).current_dir(tree).env("CLAUDE_PROJECT_DIR", tree)
+        .env_remove("MIDAS_HUB_KEY")
         .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).process_group(0).spawn();
     let Ok(mut child) = child else { return Said { code: 1, out: String::new(), err: format!("could not run {command}") } };
     if let Some(mut stdin) = child.stdin.take() {
@@ -685,17 +710,33 @@ mod project_hook_tests {
     }
 
     #[test]
-    fn a_projects_hooks_run_in_its_worktree_with_its_own_dir() {
+    fn a_projects_hooks_run_in_its_worktree_with_its_own_dir_once_landed() {
         let tree = std::env::temp_dir().join(format!("midas-project-hooks-{}", std::process::id()));
+        let _ = std::fs::remove_dir_all(&tree);
         std::fs::create_dir_all(tree.join(".claude")).unwrap();
-        std::fs::write(tree.join(".claude/settings.json"), json!({"hooks": {"PostToolUse": [
+        let settings = json!({"hooks": {"PostToolUse": [
             {"matcher": "Read|Edit", "hooks": [{"type": "command", "command": "printf '%s' \"$CLAUDE_PROJECT_DIR\"; cat >/dev/null", "timeout": 5}]},
             {"matcher": "Bash", "hooks": [{"type": "command", "command": "echo never"}]},
-        ]}}).to_string()).unwrap();
+        ]}}).to_string();
+        std::fs::write(tree.join(".claude/settings.json"), &settings).unwrap();
+        assert!(hooks_of(&tree, "PostToolUse", Some("Edit")).is_empty(), "not in any checkout: nothing landed, nothing runs");
+        let git = |args: &[&str]| {
+            let st = Command::new("git").args(["-C"]).arg(&tree).args(["-c", "user.name=t", "-c", "user.email=t@example.org"])
+                .args(args).stdout(Stdio::null()).stderr(Stdio::null()).status().unwrap();
+            assert!(st.success(), "git {args:?}");
+        };
+        git(&["init", "-q", "-b", "main"]);
+        git(&["add", ".claude/settings.json"]);
+        git(&["commit", "-q", "-m", "hooks"]);
         let hooks = hooks_of(&tree, "PostToolUse", Some("Edit"));
-        assert_eq!(hooks.len(), 1);
+        assert_eq!(hooks.len(), 1, "landed on main: its hooks run");
         let s = run_hook(&tree, &hooks[0].0, hooks[0].1, "{}");
         assert_eq!((s.code, s.out), (0, tree.to_string_lossy().to_string()));
+        // The branch edits the file: its hooks wait until that lands.
+        std::fs::write(tree.join(".claude/settings.json"), settings.replace("echo never", "echo now")).unwrap();
+        assert!(hooks_of(&tree, "PostToolUse", Some("Edit")).is_empty(), "an unlanded change runs nothing, not even the unchanged entries");
+        std::fs::write(tree.join(".claude/settings.local.json"), &settings).unwrap();
+        assert!(hooks_of(&tree, "PostToolUse", Some("Edit")).is_empty(), "local settings are nobody's reviewed file");
         assert!(folder_settings()["hooks"]["PostToolUse"][0]["hooks"][0]["command"].as_str().unwrap().contains("hook projects PostToolUse"));
         let _ = std::fs::remove_dir_all(&tree);
     }