Skip to main content

cellix_agent/
hook.rs

1//! `cellix hook <kind>`: what Claude Code's hooks call. Nothing here may disturb the agent,
2//! so with no Cellix running every kind quietly does nothing but keep its checkpoints.
3
4use std::path::{Path, PathBuf};
5use std::process::{Command, Stdio};
6use std::time::{Duration, Instant};
7
8use cellix_review::{Comment, Thread, checkpoint};
9use serde_json::{Value, json};
10
11use crate::{AgentEvent, AgentState, TestRun, request, socket_path};
12
13/// Longest test output kept, from the end, where failures are.
14const MAX_OUTPUT: usize = 20_000;
15const LABEL_LENGTH: usize = 60;
16/// Where `handle_for` leaves the agent's name in a hook's input.
17const AGENT_KEY: &str = "cellix_agent";
18/// What an agent reports while its plan is with the reviewer.
19pub const PLAN_WAITING: &str = "Plan waiting for review";
20/// How long the prompt hook waits for its checkpoint. An agent gives a hook a fixed time and
21/// drops what it says after that, comments included, and a first checkpoint of a large tree
22/// can take longer; past this it finishes on its own.
23const CHECKPOINT_WAIT: Duration = Duration::from_secs(3);
24
25/// Commands whose results belong beside the diff.
26const TEST_COMMANDS: [&str; 13] = [
27    "cargo test",
28    "cargo nextest",
29    "pytest",
30    "npm test",
31    "npm run test",
32    "pnpm test",
33    "yarn test",
34    "vitest",
35    "jest",
36    "go test",
37    "rspec",
38    "make test",
39    "harness/x",
40];
41
42pub fn is_test_command(command: &str) -> bool {
43    TEST_COMMANDS.iter().any(|c| command.contains(c))
44}
45
46/// The folders a Cellix for this session might be serving, most specific first.
47fn roots(input: &Value) -> Vec<PathBuf> {
48    let cwd = input["cwd"]
49        .as_str()
50        .map(PathBuf::from)
51        .or_else(|| std::env::current_dir().ok())
52        .unwrap_or_default();
53    workspaces(&cwd)
54}
55
56/// The folders a Cellix for `folder` might be serving: it, then its repository's root.
57pub fn workspaces(folder: &std::path::Path) -> Vec<PathBuf> {
58    let cwd = dunce::canonicalize(folder).unwrap_or_else(|_| folder.to_path_buf());
59    let mut roots = vec![cwd.clone()];
60    let top = Command::new("git")
61        .arg("-C")
62        .arg(&cwd)
63        .args(["rev-parse", "--show-toplevel"])
64        .output();
65    if let Ok(output) = top
66        && output.status.success()
67    {
68        let text = String::from_utf8_lossy(&output.stdout);
69        let top = PathBuf::from(text.trim());
70        // git on Windows writes `C:/x`, and the socket is found by the path as Cellix has it.
71        let top = if cfg!(windows) {
72            dunce::canonicalize(&top).unwrap_or(top)
73        } else {
74            top
75        };
76        roots.push(top);
77    }
78    roots
79}
80
81fn ask(roots: &[PathBuf], line: &str) -> Option<String> {
82    roots.iter().find_map(|root| request(root, line).ok())
83}
84
85fn tell(roots: &[PathBuf], input: &Value, state: AgentState, detail: &str) {
86    let event = AgentEvent {
87        session: input["session_id"].as_str().unwrap_or("").to_string(),
88        agent: input[AGENT_KEY]
89            .as_str()
90            .unwrap_or("Claude Code")
91            .to_string(),
92        state,
93        detail: detail.to_string(),
94        folder: roots
95            .first()
96            .map(|r| r.display().to_string())
97            .unwrap_or_default(),
98    };
99    if let Ok(json) = serde_json::to_string(&event) {
100        ask(roots, &format!("event {json}"));
101    }
102}
103
104/// Comments as a message an agent can act on.
105pub fn comments_message(comments: &[Comment]) -> String {
106    let mut text = String::from("Review comments on your changes:\n");
107    // In file and line order, as they'd be read, not the order they were written.
108    let mut sorted: Vec<&Comment> = comments.iter().collect();
109    sorted.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
110    for comment in sorted {
111        text.push_str(&format!("- {}\n", comment.message()));
112    }
113    text
114}
115
116fn label(prompt: &str) -> String {
117    let line = prompt.lines().next().unwrap_or("Prompt").trim();
118    let mut label: String = line.chars().take(LABEL_LENGTH).collect();
119    if line.chars().count() > LABEL_LENGTH {
120        label.push('…');
121    }
122    label
123}
124
125fn on_prompt(roots: &[PathBuf], input: &Value) -> Option<String> {
126    if let Some(root) = roots.first() {
127        let prompt = input["prompt"].as_str().unwrap_or("Prompt");
128        checkpoint_briefly(root, &label(prompt));
129    }
130    tell(roots, input, AgentState::Working, "Working");
131    let comments: Vec<Comment> = ask(roots, "take")
132        .and_then(|reply| serde_json::from_str(&reply).ok())
133        .unwrap_or_default();
134    let threads: Vec<Thread> = ask(roots, "take-threads")
135        .and_then(|reply| serde_json::from_str(&reply).ok())
136        .unwrap_or_default();
137    let mut context = String::new();
138    if !comments.is_empty() {
139        context.push_str(&comments_message(&comments));
140    }
141    for thread in &threads {
142        context.push_str(&thread.message());
143        context.push('\n');
144    }
145    if context.is_empty() {
146        return None;
147    }
148    let output = json!({"hookSpecificOutput": {
149        "hookEventName": "UserPromptSubmit",
150        "additionalContext": context,
151    }});
152    Some(output.to_string())
153}
154
155/// Checkpoints in a process of its own, waiting at most `CHECKPOINT_WAIT` for it.
156fn checkpoint_briefly(root: &Path, label: &str) {
157    // Only the real binary has a `checkpoint` command; a test runs it here instead.
158    let exe = std::env::current_exe()
159        .ok()
160        .filter(|exe| exe.file_stem().is_some_and(|stem| stem == "cellix"));
161    let Some(exe) = exe else {
162        checkpoint(root, label);
163        return;
164    };
165    let mut command = Command::new(exe);
166    command
167        .args(["checkpoint", label])
168        .current_dir(root)
169        .stdin(Stdio::null())
170        .stdout(Stdio::null())
171        .stderr(Stdio::null());
172    // Its own group, so it isn't stopped with the hook that started it.
173    #[cfg(unix)]
174    std::os::unix::process::CommandExt::process_group(&mut command, 0);
175    let Ok(mut child) = command.spawn() else {
176        return;
177    };
178    let started = Instant::now();
179    while started.elapsed() < CHECKPOINT_WAIT {
180        if !matches!(child.try_wait(), Ok(None)) {
181            return;
182        }
183        std::thread::sleep(Duration::from_millis(10));
184    }
185}
186
187/// Holds a plan until the reviewer decides, and gives back the verdict and any text with it.
188fn review_plan(roots: &[PathBuf], input: &Value, plan: &str) -> Option<(String, Option<String>)> {
189    let socket = roots.iter().map(|r| socket_path(r)).find(|s| s.exists())?;
190    let session: String = input["session_id"]
191        .as_str()
192        .unwrap_or("session")
193        .chars()
194        .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
195        .collect();
196    // Beside the socket, because that folder is private and /tmp on a server isn't.
197    let folder = socket.with_extension("").join(session);
198    std::fs::create_dir_all(&folder).ok()?;
199    let path = keep_versions(&folder, plan).ok()?;
200    tell(roots, input, AgentState::NeedsYou, PLAN_WAITING);
201    let reply = ask(roots, &format!("plan {}", path.display()))?;
202    let (verdict, text) = reply.split_once(' ').unwrap_or((&reply, "null"));
203    // An approved plan is done with, so the next one the session sends starts at version one.
204    if verdict == "approve" {
205        let _ = put_versions_away(&folder);
206    }
207    Some((verdict.to_string(), serde_json::from_str(text).ok()?))
208}
209
210/// Moves an approved plan and its earlier versions into `Approved 1`, `Approved 2` and on, so
211/// a plan sent after it isn't taken for its next version. Cellix keeps the approved one with
212/// the project, and its comments with it.
213pub fn put_versions_away(folder: &Path) -> std::io::Result<()> {
214    let plan = folder.join("Plan.md");
215    if !plan.exists() {
216        return Ok(());
217    }
218    let mut number = 1;
219    while folder.join(format!("Approved {number}")).exists() {
220        number += 1;
221    }
222    let away = folder.join(format!("Approved {number}"));
223    std::fs::create_dir_all(&away)?;
224    let mut version = 1;
225    loop {
226        let name = format!("Plan v{version}.md");
227        if !folder.join(&name).exists() {
228            break;
229        }
230        std::fs::rename(folder.join(&name), away.join(&name))?;
231        version += 1;
232    }
233    std::fs::rename(plan, away.join("Plan.md"))
234}
235
236/// Writes the plan as `Plan.md`, keeping the one it replaces as `Plan v1.md`, `Plan v2.md` and on,
237/// so a reviewer can see what changed since they sent it back. Comments stay on `Plan.md`.
238pub fn keep_versions(folder: &Path, plan: &str) -> std::io::Result<PathBuf> {
239    let path = folder.join("Plan.md");
240    if let Ok(old) = std::fs::read_to_string(&path)
241        && old != plan
242    {
243        let mut version = 1;
244        while folder.join(format!("Plan v{version}.md")).exists() {
245            version += 1;
246        }
247        std::fs::write(folder.join(format!("Plan v{version}.md")), old)?;
248    }
249    std::fs::write(&path, plan)?;
250    Ok(path)
251}
252
253/// Claude Code's plan, from its permission request. With no Cellix, it asks as usual.
254fn on_plan(roots: &[PathBuf], input: &Value) -> Option<String> {
255    let plan = input["tool_input"]["plan"].as_str()?;
256    let (verdict, text) = review_plan(roots, input, plan)?;
257    // A PreToolUse answer wouldn't do: Claude Code still shows its own plan dialog.
258    let decision = match (verdict.as_str(), text) {
259        ("send-back", Some(message)) => json!({"behavior": "deny", "message": message}),
260        ("approve", edited) => {
261            // Claude Code only counts an approval as the user's answer if it carries the input.
262            let mut plan_input = input["tool_input"].clone();
263            if let Some(edited) = edited {
264                plan_input["plan"] = json!(edited);
265            }
266            json!({"behavior": "allow", "updatedInput": plan_input})
267        }
268        _ => return None,
269    };
270    let output = json!({"hookSpecificOutput": {
271        "hookEventName": "PermissionRequest",
272        "decision": decision,
273    }});
274    Some(output.to_string())
275}
276
277/// Gemini CLI's plan, as it goes to leave plan mode. It keeps plans in a file, so an edited
278/// one is written back there, and Gemini still asks for its own approval afterwards.
279fn on_gemini_plan(roots: &[PathBuf], input: &Value) -> Option<String> {
280    let path = PathBuf::from(input["tool_input"]["plan_path"].as_str()?);
281    let path = match input["cwd"].as_str() {
282        Some(folder) => Path::new(folder).join(path),
283        None => path,
284    };
285    let plan = std::fs::read_to_string(&path).ok()?;
286    let (verdict, text) = review_plan(roots, input, &plan)?;
287    let output = match (verdict.as_str(), text) {
288        ("send-back", Some(reason)) => json!({"decision": "deny", "reason": reason}),
289        ("approve", edited) => {
290            if let Some(edited) = edited {
291                std::fs::write(&path, edited).ok()?;
292            }
293            json!({"decision": "allow"})
294        }
295        _ => return None,
296    };
297    Some(output.to_string())
298}
299
300/// The plan in a message from Codex, which has no tool for proposing one.
301fn proposed_plan(message: &str) -> Option<&str> {
302    let (_, rest) = message.split_once("<proposed_plan>")?;
303    let (plan, _) = rest.split_once("</proposed_plan>")?;
304    Some(plan.trim())
305}
306
307/// Codex ends its turn on a plan, so that's when it's held. Sending it back starts another
308/// turn with the reviewer's words. Approving lets the turn end, and implementing it is still
309/// the user's to ask for in Codex; approving with changes or notes starts one more turn, so
310/// Codex has them before it's asked.
311fn on_codex_stop(roots: &[PathBuf], input: &Value) -> Option<String> {
312    let plan = proposed_plan(input["last_assistant_message"].as_str()?)?;
313    let (verdict, text) = review_plan(roots, input, plan)?;
314    match (verdict.as_str(), text) {
315        ("send-back", Some(reason)) => {
316            Some(json!({"decision": "block", "reason": reason}).to_string())
317        }
318        ("approve", Some(changed)) if changed.trim() != plan.trim() => {
319            let reason = format!(
320                "The reviewer approved your plan with changes. This is the plan to follow \
321                 now; implement it when asked.\n\n{changed}"
322            );
323            Some(json!({"decision": "block", "reason": reason}).to_string())
324        }
325        _ => None,
326    }
327}
328
329/// Whether a command's exit is really that of its last stage, such as `tail`, and not the
330/// tests'. With `pipefail` the shell reports the failure itself.
331fn piped(command: &str) -> bool {
332    let bare = command.replace("||", "");
333    bare.contains('|') && !command.contains("pipefail")
334}
335
336/// What failing tests print, for when the exit can't be trusted.
337fn reads_as_failed(output: &str) -> bool {
338    ["FAILED", "failures:", "test result: F", " failed", "FAIL "]
339        .iter()
340        .any(|mark| output.contains(mark))
341}
342
343fn on_tool(roots: &[PathBuf], input: &Value, passed: bool) {
344    let command = input["tool_input"]["command"].as_str().unwrap_or("");
345    if !is_test_command(command) {
346        return;
347    }
348    let response = &input["tool_response"];
349    let text = response["stdout"]
350        .as_str()
351        .or_else(|| input["error"].as_str())
352        .or_else(|| response["returnDisplay"].as_str())
353        .or_else(|| response["output"].as_str())
354        .or_else(|| response.as_str())
355        .unwrap_or("");
356    // Agents without a failure hook say so in the result.
357    let exit = response["exit_code"]
358        .as_i64()
359        .or(response["exitCode"].as_i64());
360    let passed = passed
361        && exit.unwrap_or(0) == 0
362        && response["error"].is_null()
363        && !(piped(command) && reads_as_failed(text));
364    let start = text
365        .char_indices()
366        .rev()
367        .nth(MAX_OUTPUT)
368        .map_or(0, |(at, _)| at);
369    let run = TestRun {
370        command: command.to_string(),
371        passed,
372        output: text[start..].to_string(),
373    };
374    if let Ok(json) = serde_json::to_string(&run) {
375        ask(roots, &format!("test {json}"));
376    }
377}
378
379/// Handles one hook from Claude Code.
380pub fn handle(kind: &str, stdin: &str) -> Option<String> {
381    handle_for("Claude Code", kind, stdin)
382}
383
384/// Handles one hook from a named agent, and returns what to print for it, if anything.
385pub fn handle_for(agent: &str, kind: &str, stdin: &str) -> Option<String> {
386    // Without its details this can't be told from a stray call, and nothing here should
387    // guess which project it's about, least of all from the folder it happens to run in.
388    let mut input: Value = serde_json::from_str(stdin).ok()?;
389    if !input.is_object() {
390        return None;
391    }
392    input[AGENT_KEY] = json!(agent);
393    let roots = roots(&input);
394    match kind {
395        "session-start" => tell(&roots, &input, AgentState::Idle, "Ready"),
396        "prompt" => return on_prompt(&roots, &input),
397        "plan" if agent == "Gemini" => return on_gemini_plan(&roots, &input),
398        "plan" => return on_plan(&roots, &input),
399        "notify" => {
400            let detail = input["message"].as_str().unwrap_or("Needs your attention");
401            tell(&roots, &input, AgentState::NeedsYou, detail);
402        }
403        "tool-done" => on_tool(&roots, &input, true),
404        "tool-failed" => on_tool(&roots, &input, false),
405        "stop" => {
406            tell(&roots, &input, AgentState::Idle, "Finished");
407            if agent == "Codex" {
408                return on_codex_stop(&roots, &input);
409            }
410        }
411        "session-end" => tell(&roots, &input, AgentState::Ended, "Ended"),
412        _ => {}
413    }
414    None
415}
416
417#[cfg(test)]
418mod tests {
419    use super::*;
420    use crate::{Decision, Request, SharedComments, start};
421    use std::path::Path;
422
423    #[test]
424    fn each_plan_keeps_the_one_before_it() {
425        let dir = tempfile::tempdir().unwrap();
426        keep_versions(dir.path(), "first").unwrap();
427        keep_versions(dir.path(), "first").unwrap();
428        assert!(
429            !dir.path().join("Plan v1.md").exists(),
430            "the same plan again is no version"
431        );
432        keep_versions(dir.path(), "second").unwrap();
433        let path = keep_versions(dir.path(), "third").unwrap();
434        assert_eq!(std::fs::read_to_string(path).unwrap(), "third");
435        let read = |name: &str| std::fs::read_to_string(dir.path().join(name)).unwrap();
436        assert_eq!(read("Plan v1.md"), "first");
437        assert_eq!(read("Plan v2.md"), "second");
438    }
439
440    #[test]
441    fn a_pipe_hides_a_failed_test_and_the_output_gives_it_away() {
442        assert!(piped("cargo test | tail"));
443        assert!(!piped("cargo test || true"));
444        assert!(!piped("set -o pipefail; cargo test | tail"));
445        assert!(reads_as_failed("test result: FAILED. 1 passed; 2 failed"));
446        assert!(!reads_as_failed("test result: ok. 9 passed; 0 ignored"));
447    }
448    use std::sync::Arc;
449    use std::time::Duration;
450
451    fn input(dir: &Path, extra: Value) -> String {
452        let mut value = json!({"cwd": dir, "session_id": "s1"});
453        value
454            .as_object_mut()
455            .unwrap()
456            .extend(extra.as_object().unwrap().clone());
457        value.to_string()
458    }
459
460    fn comment() -> Comment {
461        Comment {
462            file: "a.rs".into(),
463            line: 3,
464            text: "why?".into(),
465            ..Comment::default()
466        }
467    }
468
469    #[test]
470    fn comments_reach_an_agent_in_order_with_what_they_are_about() {
471        let later = Comment {
472            file: "b.rs".into(),
473            line: 9,
474            text: "wall clock is wrong here".into(),
475            quote: "now = time.time()".into(),
476            removed: true,
477        };
478        let first = Comment {
479            quote: "fn main() {".into(),
480            ..comment()
481        };
482        let message = comments_message(&[later, first]);
483        let a = message
484            .find("a.rs line 3, on \"fn main() {\": why?")
485            .expect(&message);
486        let b = message.find("b.rs line 9 (a line your change removed), on \"now = time.time()\"");
487        assert!(b.is_some_and(|b| b > a), "{message}");
488    }
489
490    #[test]
491    fn nothing_breaks_with_no_cellix_running() {
492        let dir = tempfile::tempdir().unwrap();
493        for kind in ["session-start", "prompt", "notify", "stop", "session-end"] {
494            assert_eq!(handle(kind, &input(dir.path(), json!({}))), None);
495        }
496        let plan = input(dir.path(), json!({"tool_input": {"plan": "# P"}}));
497        assert_eq!(handle("plan", &plan), None, "Claude Code asks as usual");
498        assert_eq!(handle("prompt", "not json"), None);
499    }
500
501    #[test]
502    fn a_hook_with_no_details_asks_nothing_of_a_running_cellix() {
503        for kind in ["prompt", "plan", "stop"] {
504            assert_eq!(handle(kind, "not json"), None);
505            assert_eq!(handle(kind, "[1, 2]"), None);
506        }
507    }
508
509    #[test]
510    fn the_next_prompt_carries_pending_comments() {
511        let dir = tempfile::tempdir().unwrap();
512        let root = dir.path().canonicalize().unwrap();
513        let shared: SharedComments = Arc::new(std::sync::Mutex::new(vec![comment()]));
514        let _server = start(&root, shared.clone()).unwrap();
515        let hook = input(&root, json!({"prompt": "carry on"}));
516        let output = handle("prompt", &hook).unwrap();
517        let parsed: Value = serde_json::from_str(&output).unwrap();
518        let context = parsed["hookSpecificOutput"]["additionalContext"]
519            .as_str()
520            .unwrap();
521        assert!(context.contains("a.rs line 3: why?"), "{context}");
522        assert!(shared.lock().unwrap().is_empty(), "delivered once");
523        assert_eq!(handle("prompt", &hook), None);
524    }
525
526    #[test]
527    fn plan_decision_reaches_the_hook() {
528        let dir = tempfile::tempdir().unwrap();
529        let root = dir.path().canonicalize().unwrap();
530        let server = start(&root, Arc::default()).unwrap();
531        let hook = input(&root, json!({"tool_input": {"plan": "# Plan\n"}}));
532        let waiting = std::thread::spawn(move || handle("plan", &hook));
533        loop {
534            match server
535                .requests
536                .recv_timeout(Duration::from_secs(5))
537                .unwrap()
538            {
539                Request::Plan { path, reply } => {
540                    assert_eq!(std::fs::read_to_string(path).unwrap(), "# Plan\n");
541                    reply
542                        .send(Decision::SendBack("Split step two".into()))
543                        .unwrap();
544                    break;
545                }
546                _ => continue,
547            }
548        }
549        let output = waiting.join().unwrap().unwrap();
550        let parsed: Value = serde_json::from_str(&output).unwrap();
551        let answer = &parsed["hookSpecificOutput"];
552        assert_eq!(answer["hookEventName"], "PermissionRequest");
553        assert_eq!(answer["decision"]["behavior"], "deny");
554        assert_eq!(answer["decision"]["message"], "Split step two");
555    }
556
557    #[test]
558    fn a_plan_after_an_approved_one_starts_at_version_one() {
559        let dir = tempfile::tempdir().unwrap();
560        let root = dir.path().canonicalize().unwrap();
561        let server = start(&root, Arc::default()).unwrap();
562        // Sent back once, approved, then a new plan in the same session.
563        let answers = [
564            ("# One\n", Decision::SendBack("Fewer steps".into())),
565            ("# One, shorter\n", Decision::Approve(None)),
566            ("# Two\n", Decision::SendBack("Later".into())),
567        ];
568        let mut held = Vec::new();
569        for (plan, decision) in answers {
570            let hook = input(&root, json!({"tool_input": {"plan": plan}}));
571            let waiting = std::thread::spawn(move || handle("plan", &hook));
572            loop {
573                if let Request::Plan { path, reply } = server
574                    .requests
575                    .recv_timeout(Duration::from_secs(5))
576                    .unwrap()
577                {
578                    let versions = (1..)
579                        .map(|v| path.with_file_name(format!("Plan v{v}.md")))
580                        .take_while(|p| p.exists())
581                        .count();
582                    held.push((path, versions));
583                    reply.send(decision).unwrap();
584                    break;
585                }
586            }
587            waiting.join().unwrap();
588        }
589        assert_eq!(held[1].1, 1, "sent back, so the second is version 2");
590        assert_eq!(held[2].1, 0, "after approval, a new plan is version 1");
591        let away = held[2].0.with_file_name("Approved 1");
592        let read = |name: &str| std::fs::read_to_string(away.join(name)).unwrap();
593        assert_eq!(
594            read("Plan.md"),
595            "# One, shorter\n",
596            "the approved plan is put away"
597        );
598        assert_eq!(read("Plan v1.md"), "# One\n");
599    }
600
601    /// Runs a hook on a thread, and answers the plan it holds with `decision`.
602    fn answered(
603        agent: &'static str,
604        kind: &'static str,
605        hook: String,
606        decision: Decision,
607    ) -> (Option<String>, String) {
608        let root = hook_root(&hook);
609        let server = start(&root, Arc::default()).unwrap();
610        let waiting = std::thread::spawn(move || handle_for(agent, kind, &hook));
611        loop {
612            if let Request::Plan { path, reply } = server
613                .requests
614                .recv_timeout(Duration::from_secs(5))
615                .unwrap()
616            {
617                let held = std::fs::read_to_string(path).unwrap();
618                reply.send(decision).unwrap();
619                return (waiting.join().unwrap(), held);
620            }
621        }
622    }
623
624    fn hook_root(hook: &str) -> PathBuf {
625        let parsed: Value = serde_json::from_str(hook).unwrap();
626        PathBuf::from(parsed["cwd"].as_str().unwrap())
627    }
628
629    fn gemini_plan(root: &Path, text: &str) -> String {
630        let plan = root.join("plan.md");
631        std::fs::write(&plan, text).unwrap();
632        input(root, json!({"tool_input": {"plan_path": plan}}))
633    }
634
635    #[test]
636    fn gemini_is_held_at_leaving_plan_mode_and_told_what_to_change() {
637        let dir = tempfile::tempdir().unwrap();
638        let root = dir.path().canonicalize().unwrap();
639        let hook = gemini_plan(&root, "# G\n");
640        let sent = Decision::SendBack("Fewer steps".into());
641        let (output, held) = answered("Gemini", "plan", hook, sent);
642        assert_eq!(held, "# G\n");
643        let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
644        assert_eq!(parsed["decision"], "deny");
645        assert_eq!(parsed["reason"], "Fewer steps");
646    }
647
648    #[test]
649    fn an_edit_to_geminis_plan_goes_back_in_its_file() {
650        let dir = tempfile::tempdir().unwrap();
651        let root = dir.path().canonicalize().unwrap();
652        let hook = gemini_plan(&root, "# Old\n");
653        let edited = Decision::Approve(Some("# New\n".into()));
654        let (output, _) = answered("Gemini", "plan", hook, edited);
655        let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
656        assert_eq!(parsed["decision"], "allow");
657        assert_eq!(
658            std::fs::read_to_string(root.join("plan.md")).unwrap(),
659            "# New\n"
660        );
661    }
662
663    #[test]
664    fn a_plan_from_codex_is_held_when_its_turn_ends() {
665        let dir = tempfile::tempdir().unwrap();
666        let root = dir.path().canonicalize().unwrap();
667        let message = "Here it is.\n\n<proposed_plan>\n# C\n</proposed_plan>\n";
668        let hook = input(&root, json!({"last_assistant_message": message}));
669        let sent = Decision::SendBack("Say why".into());
670        let (output, held) = answered("Codex", "stop", hook, sent);
671        assert_eq!(held, "# C");
672        let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
673        assert_eq!(parsed["decision"], "block");
674        assert_eq!(parsed["reason"], "Say why");
675    }
676
677    #[test]
678    fn approving_a_codex_plan_with_changes_hands_them_over() {
679        let dir = tempfile::tempdir().unwrap();
680        let root = dir.path().canonicalize().unwrap();
681        let message = "<proposed_plan>\n# C\n</proposed_plan>";
682        let hook = input(&root, json!({"last_assistant_message": message}));
683        let changed = "# C\n\n## Reviewer notes\n- Keep the old API.".to_string();
684        let (output, _) = answered("Codex", "stop", hook, Decision::Approve(Some(changed)));
685        let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
686        assert_eq!(parsed["decision"], "block");
687        assert!(
688            parsed["reason"]
689                .as_str()
690                .unwrap()
691                .contains("Keep the old API.")
692        );
693    }
694
695    #[test]
696    fn approving_a_codex_plan_lets_its_turn_end() {
697        let dir = tempfile::tempdir().unwrap();
698        let root = dir.path().canonicalize().unwrap();
699        let message = "<proposed_plan>\n# C\n</proposed_plan>";
700        let hook = input(&root, json!({"last_assistant_message": message}));
701        let (output, _) = answered("Codex", "stop", hook, Decision::Approve(None));
702        assert_eq!(output, None);
703    }
704
705    #[test]
706    fn an_ordinary_codex_turn_isnt_held() {
707        assert_eq!(proposed_plan("Done, the tests pass."), None);
708        assert_eq!(proposed_plan("<proposed_plan>cut off"), None);
709        let dir = tempfile::tempdir().unwrap();
710        let root = dir.path().canonicalize().unwrap();
711        let _server = start(&root, Arc::default()).unwrap();
712        let hook = input(&root, json!({"last_assistant_message": "All done."}));
713        assert_eq!(handle_for("Codex", "stop", &hook), None);
714    }
715
716    #[test]
717    fn plan_hooks_are_given_time_for_a_person_to_read() {
718        let hooks = |text: &str| serde_json::from_str::<Value>(text).unwrap();
719        let gemini = hooks(include_str!(
720            "../../cellix/integrations/gemini/hooks/hooks.json"
721        ));
722        let before = &gemini["hooks"]["BeforeTool"][0];
723        assert_eq!(before["matcher"], "exit_plan_mode");
724        assert_eq!(
725            before["hooks"][0]["timeout"], 86_400_000,
726            "Gemini counts milliseconds"
727        );
728        let codex = hooks(include_str!(
729            "../../cellix/integrations/codex/hooks/hooks.json"
730        ));
731        assert_eq!(codex["hooks"]["Stop"][0]["hooks"][0]["timeout"], 86_400);
732    }
733
734    #[test]
735    fn an_edited_plan_is_approved_as_edited() {
736        let dir = tempfile::tempdir().unwrap();
737        let root = dir.path().canonicalize().unwrap();
738        let server = start(&root, Arc::default()).unwrap();
739        let hook = input(
740            &root,
741            json!({"tool_input": {"plan": "# Old", "planFilePath": "/p.md"}}),
742        );
743        let waiting = std::thread::spawn(move || handle("plan", &hook));
744        loop {
745            if let Request::Plan { reply, .. } = server
746                .requests
747                .recv_timeout(Duration::from_secs(5))
748                .unwrap()
749            {
750                reply.send(Decision::Approve(Some("# New".into()))).unwrap();
751                break;
752            }
753        }
754        let output = waiting.join().unwrap().unwrap();
755        let parsed: Value = serde_json::from_str(&output).unwrap();
756        let answer = &parsed["hookSpecificOutput"]["decision"];
757        assert_eq!(answer["behavior"], "allow");
758        assert_eq!(answer["updatedInput"]["plan"], "# New");
759        assert_eq!(answer["updatedInput"]["planFilePath"], "/p.md");
760    }
761
762    #[test]
763    fn events_carry_the_agents_name() {
764        let dir = tempfile::tempdir().unwrap();
765        let root = dir.path().canonicalize().unwrap();
766        let server = start(&root, Arc::default()).unwrap();
767        handle_for("Codex", "session-start", &input(&root, json!({})));
768        match server
769            .requests
770            .recv_timeout(Duration::from_secs(5))
771            .unwrap()
772        {
773            Request::Agent(event) => assert_eq!(event.agent, "Codex"),
774            other => panic!("{other:?}"),
775        }
776    }
777
778    #[test]
779    fn a_failed_command_is_read_from_the_result() {
780        let dir = tempfile::tempdir().unwrap();
781        let root = dir.path().canonicalize().unwrap();
782        let server = start(&root, Arc::default()).unwrap();
783        let run = input(
784            &root,
785            json!({"tool_input": {"command": "cargo test"},
786                   "tool_response": {"returnDisplay": "boom", "error": "exit 1"}}),
787        );
788        handle_for("Gemini", "tool-done", &run);
789        match server
790            .requests
791            .recv_timeout(Duration::from_secs(5))
792            .unwrap()
793        {
794            Request::Test(run) => {
795                assert!(!run.passed);
796                assert_eq!(run.output, "boom");
797            }
798            other => panic!("{other:?}"),
799        }
800    }
801
802    #[test]
803    fn test_runs_are_reported_and_other_commands_are_not() {
804        let dir = tempfile::tempdir().unwrap();
805        let root = dir.path().canonicalize().unwrap();
806        let server = start(&root, Arc::default()).unwrap();
807        let other = input(&root, json!({"tool_input": {"command": "ls"}}));
808        handle("tool-done", &other);
809        let run = input(
810            &root,
811            json!({"tool_input": {"command": "cargo test"}, "tool_response": {"stdout": "ok"}}),
812        );
813        handle("tool-failed", &run);
814        match server
815            .requests
816            .recv_timeout(Duration::from_secs(5))
817            .unwrap()
818        {
819            Request::Test(run) => {
820                assert_eq!(run.command, "cargo test");
821                assert!(!run.passed);
822            }
823            other => panic!("{other:?}"),
824        }
825    }
826}