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::tasks::{self, Event};
9use cellix_review::{Comment, Thread, threads};
10use serde_json::{Value, json};
11
12use crate::{AgentEvent, AgentState, TestRun, request, socket_path};
13
14/// Longest test output kept, from the end, where failures are.
15const MAX_OUTPUT: usize = 20_000;
16const LABEL_LENGTH: usize = 60;
17/// Where `handle_for` leaves the agent's name in a hook's input.
18const AGENT_KEY: &str = "cellix_agent";
19/// Set by Cellix's session host to its socket, for a program it holds.
20pub const HELD_VAR: &str = "CELLIX_HELD";
21
22/// How to resume an agent held by Cellix, left by its hooks beside the host's socket so it
23/// outlives the host, as when the machine restarts.
24#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
25pub struct Resumable {
26    /// The agent, as Cellix names it: "Claude Code", "Codex".
27    pub agent: String,
28    /// The agent's own session id.
29    pub session: String,
30    /// Where the agent keeps the session's transcript, when its hook says.
31    #[serde(default, skip_serializing_if = "String::is_empty")]
32    pub transcript: String,
33}
34
35/// Leaves word beside `held`, the host's socket, of the agent session running there.
36/// Unchanged word isn't written again.
37pub fn remember(held: &Path, agent: &str, session: &str, transcript: &str) {
38    if session.is_empty() || !held.extension().is_some_and(|e| e == "sock") {
39        return;
40    }
41    let word = Resumable {
42        agent: agent.to_string(),
43        session: session.to_string(),
44        transcript: transcript.to_string(),
45    };
46    let path = held.with_extension("agent");
47    let known = std::fs::read(&path)
48        .ok()
49        .and_then(|bytes| serde_json::from_slice::<Resumable>(&bytes).ok());
50    if known.as_ref() == Some(&word) {
51        return;
52    }
53    if let Ok(json) = serde_json::to_vec(&word) {
54        let _ = std::fs::write(path, json);
55    }
56}
57/// What an agent reports while its plan is with the reviewer.
58pub const PLAN_WAITING: &str = "Plan waiting for review";
59/// How long the prompt hook waits for its checkpoint. An agent gives a hook a fixed time and
60/// drops what it says after that, comments included, and a first checkpoint of a large tree
61/// can take longer; past this it finishes on its own.
62const CHECKPOINT_WAIT: Duration = Duration::from_secs(3);
63
64/// Commands whose results belong beside the diff.
65const TEST_COMMANDS: [&str; 13] = [
66    "cargo test",
67    "cargo nextest",
68    "pytest",
69    "npm test",
70    "npm run test",
71    "pnpm test",
72    "yarn test",
73    "vitest",
74    "jest",
75    "go test",
76    "rspec",
77    "make test",
78    "harness/x",
79];
80
81pub fn is_test_command(command: &str) -> bool {
82    TEST_COMMANDS.iter().any(|c| command.contains(c))
83}
84
85/// The folders a Cellix for this session might be serving, most specific first.
86fn roots(input: &Value) -> Vec<PathBuf> {
87    let cwd = input["cwd"]
88        .as_str()
89        .map(PathBuf::from)
90        .or_else(|| std::env::current_dir().ok())
91        .unwrap_or_default();
92    workspaces(&cwd)
93}
94
95/// The folders a Cellix for `folder` might be serving: it, then its repository's root.
96pub fn workspaces(folder: &std::path::Path) -> Vec<PathBuf> {
97    let cwd = dunce::canonicalize(folder).unwrap_or_else(|_| folder.to_path_buf());
98    let mut roots = vec![cwd.clone()];
99    let top = Command::new("git")
100        .arg("-C")
101        .arg(&cwd)
102        .args(["rev-parse", "--show-toplevel"])
103        .output();
104    if let Ok(output) = top
105        && output.status.success()
106    {
107        let text = String::from_utf8_lossy(&output.stdout);
108        let top = PathBuf::from(text.trim());
109        // git on Windows writes `C:/x`, and the socket is found by the path as Cellix has it.
110        let top = if cfg!(windows) {
111            dunce::canonicalize(&top).unwrap_or(top)
112        } else {
113            top
114        };
115        roots.push(top);
116    }
117    roots
118}
119
120fn ask(roots: &[PathBuf], line: &str) -> Option<String> {
121    roots.iter().find_map(|root| request(root, line).ok())
122}
123
124/// The agent's own id for the session a hook is about.
125fn session_of(input: &Value) -> String {
126    input["session_id"].as_str().unwrap_or("").to_string()
127}
128
129/// The agent a hook came from, as Cellix names it.
130fn agent_of(input: &Value) -> String {
131    input[AGENT_KEY]
132        .as_str()
133        .unwrap_or("Claude Code")
134        .to_string()
135}
136
137/// Where the project's task log is: with the Cellix serving it, or else at the top of its
138/// repository. Outside both, as in a home folder, nothing is logged.
139fn task_root(roots: &[PathBuf]) -> Option<PathBuf> {
140    roots
141        .iter()
142        .find(|r| socket_path(r).exists())
143        .or_else(|| roots.get(1))
144        .or_else(|| roots.first().filter(|r| r.join(".git").exists()))
145        .cloned()
146}
147
148/// Adds to the task log of the project the hook is about. Never in the agent's way.
149fn log(roots: &[PathBuf], event: &Event) {
150    if let Some(root) = task_root(roots) {
151        let _ = tasks::record(&root, event);
152    }
153}
154
155fn tell(roots: &[PathBuf], input: &Value, state: AgentState, detail: &str) {
156    let event = AgentEvent {
157        session: session_of(input),
158        agent: agent_of(input),
159        state,
160        detail: detail.to_string(),
161        folder: roots
162            .first()
163            .map(|r| r.display().to_string())
164            .unwrap_or_default(),
165        pid: agent_pid(),
166        transcript: input["transcript_path"].as_str().unwrap_or("").to_string(),
167    };
168    if let Ok(json) = serde_json::to_string(&event) {
169        ask(roots, &format!("event {json}"));
170    }
171}
172
173/// The agent this hook runs for. An agent runs a hook's command through a shell, which waits
174/// while `cellix` runs, so the agent is the shell's parent; run directly, it's this one's.
175#[cfg(unix)]
176fn agent_pid() -> Option<u32> {
177    let parent = std::os::unix::process::parent_id();
178    let (above, name) = process_of(parent)?;
179    let shell = ["sh", "bash", "zsh", "dash", "fish", "ksh"];
180    let name = name
181        .rsplit('/')
182        .next()
183        .unwrap_or(&name)
184        .trim_start_matches('-');
185    Some(if shell.contains(&name) { above } else { parent })
186}
187
188#[cfg(not(unix))]
189fn agent_pid() -> Option<u32> {
190    None
191}
192
193/// Whether this hook's agent is the program held at `held`, and not an agent that program
194/// ran, as Claude Code running `codex exec` or `claude -p` through its shell: that one inherits
195/// where it's held too, and would leave its own session to resume in place of the tab's.
196fn is_held_program(held: &Path) -> bool {
197    let child = std::fs::read_to_string(held.with_extension("pid"))
198        .ok()
199        .and_then(|text| text.trim().parse().ok());
200    #[cfg(unix)]
201    let parent_of = |pid| process_of(pid).map(|(parent, _)| parent);
202    #[cfg(not(unix))]
203    let parent_of = |_| None;
204    held_program(child, agent_pid(), parent_of)
205}
206
207/// `is_held_program`, given the held program's process, the hook's agent's, and how to find a
208/// process's parent. The agent is the program, or run by it directly, as through a login
209/// shell; one with a shell between them was started by the program's own agent. Without the
210/// numbers to tell, as from an older host, it's taken to be the program.
211fn held_program(
212    child: Option<u32>,
213    agent: Option<u32>,
214    parent_of: impl Fn(u32) -> Option<u32>,
215) -> bool {
216    let (Some(child), Some(agent)) = (child, agent) else {
217        return true;
218    };
219    agent == child || parent_of(agent) == Some(child)
220}
221
222/// A process's parent and its command's name: from `/proc` where there is one, else `ps`.
223#[cfg(unix)]
224fn process_of(pid: u32) -> Option<(u32, String)> {
225    if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) {
226        // `pid (name) state ppid ...`, and the name can hold spaces and brackets.
227        let (head, rest) = stat.rsplit_once(')')?;
228        let name = head.split_once('(')?.1.to_string();
229        let ppid = rest.split_whitespace().nth(1)?.parse().ok()?;
230        return Some((ppid, name));
231    }
232    let output = Command::new("ps")
233        .args(["-o", "ppid=,comm=", "-p", &pid.to_string()])
234        .output()
235        .ok()?;
236    let text = String::from_utf8_lossy(&output.stdout);
237    let (ppid, name) = text.trim().split_once(char::is_whitespace)?;
238    Some((ppid.trim().parse().ok()?, name.trim().to_string()))
239}
240
241/// Whether a notification asks the person for something. Claude Code also sends one when it
242/// has sat idle after a turn ("waiting for your input"), on signing in, and when a question
243/// was answered (`elicitation_complete`, `elicitation_response`), and those ask for nothing.
244/// Its `notification_type` says which, as Gemini's does; without it, from older versions, the
245/// words do.
246fn asks(input: &Value) -> bool {
247    match input["notification_type"].as_str() {
248        Some(kind) => {
249            let kind = kind.to_lowercase();
250            kind.contains("permission")
251                || kind == "agent_needs_input"
252                || (kind.starts_with("elicitation") && kind.ends_with("dialog"))
253        }
254        None => {
255            let message = input["message"].as_str().unwrap_or("").to_lowercase();
256            !message.contains("waiting for your input")
257        }
258    }
259}
260
261/// Whether a notification says the agent is waiting with nothing to do: after a turn, and
262/// after one was interrupted, when no Stop comes.
263fn idles(input: &Value) -> bool {
264    matches!(
265        input["notification_type"].as_str(),
266        Some("idle_prompt" | "agent_completed")
267    )
268}
269
270/// Why a turn stopped on an error, in a word for the agent's tile.
271fn failure_words(input: &Value) -> String {
272    let reason = ["error_type", "error", "reason", "message"]
273        .iter()
274        .find_map(|field| input[*field].as_str().filter(|s| !s.is_empty()));
275    match reason {
276        Some(reason) => format!("Stopped: {}", reason.replace('_', " ")),
277        None => "Stopped on an error".to_string(),
278    }
279}
280
281/// What a request says: its own words, or for Codex, which asks through a permission hook
282/// with none, the command it wants to run.
283fn request_words(input: &Value, agent: &str) -> String {
284    if let Some(message) = input["message"].as_str().filter(|m| !m.is_empty()) {
285        return message.to_string();
286    }
287    match input["tool_input"]["command"].as_str() {
288        Some(command) => format!("{agent} asks to run {command}"),
289        None => "Needs your attention".to_string(),
290    }
291}
292
293/// Comments as a message an agent can act on.
294pub fn comments_message(comments: &[Comment]) -> String {
295    let mut text = String::from("Review comments on your changes:\n");
296    // In file and line order, as they'd be read, not the order they were written.
297    let mut sorted: Vec<&Comment> = comments.iter().collect();
298    sorted.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
299    for comment in sorted {
300        text.push_str(&format!("- {}\n", comment.message()));
301    }
302    text
303}
304
305fn label(prompt: &str) -> String {
306    let line = prompt.lines().next().unwrap_or("Prompt").trim();
307    let mut label: String = line.chars().take(LABEL_LENGTH).collect();
308    if line.chars().count() > LABEL_LENGTH {
309        label.push('…');
310    }
311    label
312}
313
314fn on_prompt(roots: &[PathBuf], input: &Value) -> Option<String> {
315    if let Some(root) = roots.first() {
316        let prompt = input["prompt"].as_str().unwrap_or("Prompt");
317        // The newest thread now, so the task view can tell which were made during this turn.
318        let event = task_root(roots).map(|log| {
319            let threads = threads::load(&log)
320                .map(|t| threads::next_id(&t) - 1)
321                .unwrap_or(0);
322            let event = Event::Prompt {
323                at: tasks::now(),
324                session: session_of(input),
325                agent: agent_of(input),
326                text: tasks::clip_prompt(prompt),
327                commit: None,
328                threads,
329            };
330            (log, event)
331        });
332        checkpoint_briefly(root, &label(prompt), event);
333    }
334    tell(roots, input, AgentState::Working, "Working");
335    let comments: Vec<Comment> = ask(roots, "take")
336        .and_then(|reply| serde_json::from_str(&reply).ok())
337        .unwrap_or_default();
338    let threads: Vec<Thread> = ask(roots, "take-threads")
339        .and_then(|reply| serde_json::from_str(&reply).ok())
340        .unwrap_or_default();
341    let mut context = String::new();
342    if !comments.is_empty() {
343        context.push_str(&comments_message(&comments));
344    }
345    for thread in &threads {
346        context.push_str(&thread.message());
347        context.push('\n');
348    }
349    if context.is_empty() {
350        return None;
351    }
352    let output = json!({"hookSpecificOutput": {
353        "hookEventName": "UserPromptSubmit",
354        "additionalContext": context,
355    }});
356    Some(output.to_string())
357}
358
359/// Checkpoints in a process of its own, waiting at most `CHECKPOINT_WAIT` for it. That process
360/// also logs the prompt for the task view, with the checkpoint it took.
361fn checkpoint_briefly(root: &Path, label: &str, prompt: Option<(PathBuf, Event)>) {
362    // Only the real binary has a `checkpoint` command; a test runs it here instead.
363    let exe = std::env::current_exe()
364        .ok()
365        .filter(|exe| exe.file_stem().is_some_and(|stem| stem == "cellix"));
366    let Some(exe) = exe else {
367        let prompt = prompt.as_ref().map(|(log, e)| (log.as_path(), e.clone()));
368        tasks::checkpoint_prompt(root, label, prompt);
369        return;
370    };
371    let mut command = Command::new(exe);
372    command.args(["checkpoint", label]);
373    if let Some((log, event)) = &prompt {
374        command.env(tasks::ROOT_VAR, log).env(
375            tasks::EVENT_VAR,
376            serde_json::to_string(event).unwrap_or_default(),
377        );
378    }
379    command
380        .current_dir(root)
381        .stdin(Stdio::null())
382        .stdout(Stdio::null())
383        .stderr(Stdio::null());
384    // Its own group, so it isn't stopped with the hook that started it.
385    #[cfg(unix)]
386    std::os::unix::process::CommandExt::process_group(&mut command, 0);
387    let Ok(mut child) = command.spawn() else {
388        return;
389    };
390    let started = Instant::now();
391    while started.elapsed() < CHECKPOINT_WAIT {
392        if !matches!(child.try_wait(), Ok(None)) {
393            return;
394        }
395        std::thread::sleep(Duration::from_millis(10));
396    }
397}
398
399/// Holds a plan until the reviewer decides, and gives back the verdict and any text with it.
400fn review_plan(roots: &[PathBuf], input: &Value, plan: &str) -> Option<(String, Option<String>)> {
401    let socket = roots.iter().map(|r| socket_path(r)).find(|s| s.exists())?;
402    let session: String = input["session_id"]
403        .as_str()
404        .unwrap_or("session")
405        .chars()
406        .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
407        .collect();
408    // Beside the socket, because that folder is private and /tmp on a server isn't.
409    let folder = socket.with_extension("").join(session);
410    std::fs::create_dir_all(&folder).ok()?;
411    let path = keep_versions(&folder, plan).ok()?;
412    tell(roots, input, AgentState::NeedsYou, PLAN_WAITING);
413    let file = path.display().to_string();
414    log(
415        roots,
416        &Event::Plan {
417            at: tasks::now(),
418            session: session_of(input),
419            agent: agent_of(input),
420            file: file.clone(),
421        },
422    );
423    let reply = ask(roots, &format!("plan {file}"))?;
424    let (verdict, text) = reply.split_once(' ').unwrap_or((&reply, "null"));
425    let text: Option<String> = serde_json::from_str(text).ok()?;
426    // An approved plan is done with, so the next one the session sends starts at version one.
427    let kept = if verdict == "approve" {
428        put_versions_away(&folder).ok().flatten()
429    } else {
430        None
431    };
432    if matches!(verdict, "approve" | "send-back") {
433        log(
434            roots,
435            &Event::Answer {
436                at: tasks::now(),
437                file,
438                approved: verdict == "approve",
439                note: if verdict == "approve" {
440                    String::new()
441                } else {
442                    text.clone().unwrap_or_default()
443                },
444                kept: kept.map(|k| k.display().to_string()),
445            },
446        );
447    }
448    Some((verdict.to_string(), text))
449}
450
451/// Moves an approved plan and its earlier versions into `Approved 1`, `Approved 2` and on, so
452/// a plan sent after it isn't taken for its next version. Cellix keeps the approved one with
453/// the project, and its comments with it. Gives the folder they went to.
454pub fn put_versions_away(folder: &Path) -> std::io::Result<Option<PathBuf>> {
455    let plan = folder.join("Plan.md");
456    if !plan.exists() {
457        return Ok(None);
458    }
459    let mut number = 1;
460    while folder.join(format!("Approved {number}")).exists() {
461        number += 1;
462    }
463    let away = folder.join(format!("Approved {number}"));
464    std::fs::create_dir_all(&away)?;
465    let mut version = 1;
466    loop {
467        let name = format!("Plan v{version}.md");
468        if !folder.join(&name).exists() {
469            break;
470        }
471        std::fs::rename(folder.join(&name), away.join(&name))?;
472        version += 1;
473    }
474    std::fs::rename(plan, away.join("Plan.md"))?;
475    Ok(Some(away))
476}
477
478/// Writes the plan as `Plan.md`, keeping the one it replaces as `Plan v1.md`, `Plan v2.md` and on,
479/// so a reviewer can see what changed since they sent it back. Comments stay on `Plan.md`.
480pub fn keep_versions(folder: &Path, plan: &str) -> std::io::Result<PathBuf> {
481    let path = folder.join("Plan.md");
482    if let Ok(old) = std::fs::read_to_string(&path)
483        && old != plan
484    {
485        let mut version = 1;
486        while folder.join(format!("Plan v{version}.md")).exists() {
487            version += 1;
488        }
489        std::fs::write(folder.join(format!("Plan v{version}.md")), old)?;
490    }
491    std::fs::write(&path, plan)?;
492    Ok(path)
493}
494
495/// Claude Code's plan, from its permission request. With no Cellix, it asks as usual.
496fn on_plan(roots: &[PathBuf], input: &Value) -> Option<String> {
497    let plan = input["tool_input"]["plan"].as_str()?;
498    let (verdict, text) = review_plan(roots, input, plan)?;
499    // A PreToolUse answer wouldn't do: Claude Code still shows its own plan dialog.
500    let decision = match (verdict.as_str(), text) {
501        ("send-back", Some(message)) => json!({"behavior": "deny", "message": message}),
502        ("approve", edited) => {
503            // Claude Code only counts an approval as the user's answer if it carries the input.
504            let mut plan_input = input["tool_input"].clone();
505            if let Some(edited) = edited {
506                // It also keeps the plan in a file, which it may work from: the edit goes
507                // there too, if that's one of its own plan files.
508                if let (Some(file), Some(config)) = (
509                    input["tool_input"]["planFilePath"].as_str(),
510                    claude_config(),
511                ) {
512                    write_plan_file(Path::new(file), &edited, &config.join("plans"));
513                }
514                plan_input["plan"] = json!(edited);
515            }
516            json!({"behavior": "allow", "updatedInput": plan_input})
517        }
518        _ => return None,
519    };
520    let output = json!({"hookSpecificOutput": {
521        "hookEventName": "PermissionRequest",
522        "decision": decision,
523    }});
524    Some(output.to_string())
525}
526
527/// Gemini CLI's plan, as it goes to leave plan mode. It keeps plans in a file, so an edited
528/// one is written back there, and Gemini still asks for its own approval afterwards.
529fn on_gemini_plan(roots: &[PathBuf], input: &Value) -> Option<String> {
530    let path = PathBuf::from(input["tool_input"]["plan_path"].as_str()?);
531    let path = match input["cwd"].as_str() {
532        Some(folder) => Path::new(folder).join(path),
533        None => path,
534    };
535    // The path is in what the model sent, so only a Markdown file that is really there, not
536    // a link, is read and written as its plan. Anything else is left to Gemini's own dialog.
537    if !is_plain_markdown(&path) {
538        return None;
539    }
540    let plan = std::fs::read_to_string(&path).ok()?;
541    let (verdict, text) = review_plan(roots, input, &plan)?;
542    let output = match (verdict.as_str(), text) {
543        ("send-back", Some(reason)) => json!({"decision": "deny", "reason": reason}),
544        ("approve", edited) => {
545            if let Some(edited) = edited {
546                std::fs::write(&path, edited).ok()?;
547            }
548            json!({"decision": "allow"})
549        }
550        _ => return None,
551    };
552    Some(output.to_string())
553}
554
555/// Claude Code's own folder: `CLAUDE_CONFIG_DIR`, or `~/.claude`.
556fn claude_config() -> Option<PathBuf> {
557    std::env::var_os("CLAUDE_CONFIG_DIR")
558        .map(PathBuf::from)
559        .or_else(|| {
560            let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
561            Some(PathBuf::from(home).join(".claude"))
562        })
563}
564
565/// A Markdown file that's there and is no link.
566fn is_plain_markdown(path: &Path) -> bool {
567    path.extension().is_some_and(|e| e == "md")
568        && std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_file())
569}
570
571/// Writes an edited plan to `file` if it's a plan file of Claude Code's in `plans`, already
572/// there: the path came with the tool's input, so nothing else is ever written.
573fn write_plan_file(file: &Path, edited: &str, plans: &Path) -> bool {
574    let (Ok(folder), Some(parent)) = (dunce::canonicalize(plans), file.parent()) else {
575        return false;
576    };
577    let inside = dunce::canonicalize(parent).is_ok_and(|parent| parent == folder);
578    inside && is_plain_markdown(file) && std::fs::write(file, edited).is_ok()
579}
580
581/// The plan in a message from Codex, which has no tool for proposing one.
582fn proposed_plan(message: &str) -> Option<&str> {
583    let (_, rest) = message.split_once("<proposed_plan>")?;
584    let (plan, _) = rest.split_once("</proposed_plan>")?;
585    Some(plan.trim())
586}
587
588/// Codex ends its turn on a plan, so that's when it's held. Sending it back starts another
589/// turn with the reviewer's words. Approving lets the turn end, and implementing it is still
590/// the user's to ask for in Codex; approving with changes or notes starts one more turn, so
591/// Codex has them before it's asked.
592fn on_codex_stop(roots: &[PathBuf], input: &Value) -> Option<String> {
593    let plan = proposed_plan(input["last_assistant_message"].as_str()?)?;
594    let (verdict, text) = review_plan(roots, input, plan)?;
595    match (verdict.as_str(), text) {
596        ("send-back", Some(reason)) => {
597            Some(json!({"decision": "block", "reason": reason}).to_string())
598        }
599        ("approve", Some(changed)) if changed.trim() != plan.trim() => {
600            let reason = format!(
601                "The reviewer approved your plan with changes. This is the plan to follow \
602                 now; implement it when asked.\n\n{changed}"
603            );
604            Some(json!({"decision": "block", "reason": reason}).to_string())
605        }
606        _ => None,
607    }
608}
609
610/// Whether a command's exit is really that of its last stage, such as `tail`, and not the
611/// tests'. With `pipefail` the shell reports the failure itself.
612fn piped(command: &str) -> bool {
613    let bare = command.replace("||", "");
614    bare.contains('|') && !command.contains("pipefail")
615}
616
617/// What failing tests print, for when the exit can't be trusted or isn't said: a mark, or a
618/// count of failures that isn't nought ("2 failed", not cargo's "0 failed").
619fn reads_as_failed(output: &str) -> bool {
620    let marked = ["FAILED", "failures:", "test result: F", "FAIL "]
621        .iter()
622        .any(|mark| output.contains(mark));
623    marked
624        || output.match_indices(" failed").any(|(at, _)| {
625            let count = output[..at].split_whitespace().next_back().unwrap_or("");
626            count.parse::<u64>().is_ok_and(|n| n > 0)
627        })
628}
629
630/// The exit code a result says in its words, as Gemini CLI's does ("Exit Code: 1").
631fn said_exit(text: &str) -> Option<i64> {
632    let lower = text.to_lowercase();
633    ["exit code: ", "exit code ", "exited with code "]
634        .iter()
635        .find_map(|mark| {
636            let at = lower.find(mark)? + mark.len();
637            let digits: String = lower[at..]
638                .chars()
639                .take_while(|c| c.is_ascii_digit() || *c == '-')
640                .collect();
641            digits.parse().ok()
642        })
643}
644
645fn on_tool(roots: &[PathBuf], input: &Value, passed: bool) {
646    // A tool ran, so whatever the agent asked leave for has been answered.
647    tell(roots, input, AgentState::Working, "Working");
648    let command = input["tool_input"]["command"].as_str().unwrap_or("");
649    if !is_test_command(command) {
650        return;
651    }
652    // Codex may send its result as JSON inside a string.
653    let unpacked: Option<Value> = input["tool_response"]
654        .as_str()
655        .and_then(|text| serde_json::from_str(text).ok())
656        .filter(Value::is_object);
657    let response = unpacked.as_ref().unwrap_or(&input["tool_response"]);
658    let text = response["stdout"]
659        .as_str()
660        .or_else(|| input["error"].as_str())
661        .or_else(|| response["returnDisplay"].as_str())
662        .or_else(|| response["output"].as_str())
663        .or_else(|| response["llmContent"].as_str())
664        .or_else(|| response.as_str())
665        .unwrap_or("");
666    // Agents without a failure hook say so in the result: as a field, or in its words.
667    let exit = response["exit_code"]
668        .as_i64()
669        .or(response["exitCode"].as_i64())
670        .or_else(|| response["llmContent"].as_str().and_then(said_exit))
671        .or_else(|| said_exit(text));
672    // Claude Code has a hook of its own for a failed run. The others, when the result doesn't
673    // say how it exited, are judged by what the run printed, never taken to have passed.
674    let unsaid = exit.is_none() && agent_of(input) != "Claude Code";
675    let passed = passed
676        && exit.unwrap_or(0) == 0
677        && response["error"].is_null()
678        && !((piped(command) || unsaid) && reads_as_failed(text));
679    let start = text
680        .char_indices()
681        .rev()
682        .nth(MAX_OUTPUT)
683        .map_or(0, |(at, _)| at);
684    log(
685        roots,
686        &Event::Test {
687            at: tasks::now(),
688            session: session_of(input),
689            command: command.to_string(),
690            passed,
691            output: tasks::clip_output(text),
692        },
693    );
694    let run = TestRun {
695        command: command.to_string(),
696        passed,
697        output: text[start..].to_string(),
698    };
699    if let Ok(json) = serde_json::to_string(&run) {
700        ask(roots, &format!("test {json}"));
701    }
702}
703
704/// Handles one hook from Claude Code.
705pub fn handle(kind: &str, stdin: &str) -> Option<String> {
706    handle_for("Claude Code", kind, stdin)
707}
708
709/// Handles one hook from a named agent, and returns what to print for it, if anything.
710pub fn handle_for(agent: &str, kind: &str, stdin: &str) -> Option<String> {
711    // Without its details this can't be told from a stray call, and nothing here should
712    // guess which project it's about, least of all from the folder it happens to run in.
713    let mut input: Value = serde_json::from_str(stdin).ok()?;
714    if !input.is_object() {
715        return None;
716    }
717    input[AGENT_KEY] = json!(agent);
718    let roots = roots(&input);
719    if matches!(kind, "session-start" | "prompt")
720        && let Some(held) = std::env::var_os(HELD_VAR)
721        && is_held_program(Path::new(&held))
722    {
723        remember(
724            Path::new(&held),
725            agent,
726            input["session_id"].as_str().unwrap_or(""),
727            input["transcript_path"].as_str().unwrap_or(""),
728        );
729    }
730    match kind {
731        "session-start" => tell(&roots, &input, AgentState::Idle, "Ready"),
732        "prompt" => return on_prompt(&roots, &input),
733        "plan" if agent == "Gemini" => return on_gemini_plan(&roots, &input),
734        "plan" => return on_plan(&roots, &input),
735        "notify" if asks(&input) => {
736            let detail = request_words(&input, agent);
737            tell(&roots, &input, AgentState::NeedsYou, &detail);
738        }
739        // Waiting after a turn, which after an interrupt is the only word that it stopped.
740        "notify" if idles(&input) => tell(&roots, &input, AgentState::Idle, "Waiting for you"),
741        // A sign-in or an answered question: nothing to answer, so the state stays as it was.
742        "notify" => {}
743        "tool-done" => on_tool(&roots, &input, true),
744        "tool-failed" => on_tool(&roots, &input, false),
745        "stop" => {
746            tell(&roots, &input, AgentState::Idle, "Finished");
747            if agent == "Codex" {
748                return on_codex_stop(&roots, &input);
749            }
750        }
751        // A turn cut short by the API: a limit, an outage, a sign-in. It isn't working.
752        "stop-failed" => tell(&roots, &input, AgentState::Idle, &failure_words(&input)),
753        "session-end" => tell(&roots, &input, AgentState::Ended, "Ended"),
754        _ => {}
755    }
756    None
757}
758
759#[cfg(test)]
760mod tests {
761    #[test]
762    fn a_held_agent_leaves_word_of_how_to_resume_it() {
763        let dir = tempfile::tempdir().unwrap();
764        let socket = dir.path().join("1-2.sock");
765        super::remember(&socket, "Claude Code", "abc-123", "/t/abc-123.jsonl");
766        let word: super::Resumable =
767            serde_json::from_slice(&std::fs::read(dir.path().join("1-2.agent")).unwrap()).unwrap();
768        assert_eq!(word.agent, "Claude Code");
769        assert_eq!(word.session, "abc-123");
770        assert_eq!(word.transcript, "/t/abc-123.jsonl");
771        // A /clear starts a new session, which replaces it.
772        super::remember(&socket, "Claude Code", "def-456", "");
773        let text = std::fs::read_to_string(dir.path().join("1-2.agent")).unwrap();
774        assert!(text.contains("def-456"), "{text}");
775        // Nothing without an id, and nothing beside what isn't a host's socket.
776        super::remember(&socket, "Claude Code", "", "");
777        assert!(
778            std::fs::read_to_string(dir.path().join("1-2.agent"))
779                .unwrap()
780                .contains("def-456")
781        );
782        super::remember(&dir.path().join("notes.txt"), "Claude Code", "x", "");
783        assert!(!dir.path().join("notes.agent").exists());
784    }
785
786    use super::*;
787    use crate::{Decision, Request, Server, SharedComments, start};
788    use std::path::Path;
789
790    #[test]
791    fn each_plan_keeps_the_one_before_it() {
792        let dir = tempfile::tempdir().unwrap();
793        keep_versions(dir.path(), "first").unwrap();
794        keep_versions(dir.path(), "first").unwrap();
795        assert!(
796            !dir.path().join("Plan v1.md").exists(),
797            "the same plan again is no version"
798        );
799        keep_versions(dir.path(), "second").unwrap();
800        let path = keep_versions(dir.path(), "third").unwrap();
801        assert_eq!(std::fs::read_to_string(path).unwrap(), "third");
802        let read = |name: &str| std::fs::read_to_string(dir.path().join(name)).unwrap();
803        assert_eq!(read("Plan v1.md"), "first");
804        assert_eq!(read("Plan v2.md"), "second");
805    }
806
807    #[test]
808    fn an_agent_run_by_the_held_agent_leaves_its_resume_alone() {
809        // Cellix holds Claude Code as 100, here started from a login shell as 150.
810        let parents = |pid| match pid {
811            150 => Some(100),
812            300 => Some(250), // `claude -p` run by the agent's Bash tool, 250
813            250 => Some(150),
814            _ => None,
815        };
816        assert!(held_program(Some(100), Some(100), parents), "the program");
817        assert!(
818            held_program(Some(100), Some(150), parents),
819            "under its shell"
820        );
821        assert!(!held_program(Some(100), Some(300), parents), "one it ran");
822        assert!(
823            held_program(None, Some(300), parents),
824            "an older host says nothing"
825        );
826        // And end to end, where processes' parents can be read: a hook for another process
827        // doesn't touch the record.
828        if cfg!(not(unix)) {
829            return;
830        }
831        let dir = tempfile::tempdir().unwrap();
832        let held = dir.path().join("1-2.sock");
833        std::fs::write(held.with_extension("pid"), "1").unwrap();
834        assert!(!is_held_program(&held), "this test isn't pid 1's agent");
835    }
836
837    #[test]
838    fn a_pipe_hides_a_failed_test_and_the_output_gives_it_away() {
839        assert!(piped("cargo test | tail"));
840        assert!(!piped("cargo test || true"));
841        assert!(!piped("set -o pipefail; cargo test | tail"));
842        assert!(reads_as_failed("test result: FAILED. 1 passed; 2 failed"));
843        assert!(!reads_as_failed("test result: ok. 9 passed; 0 ignored"));
844        assert!(!reads_as_failed(
845            "test result: ok. 9 passed; 0 failed; 0 ignored"
846        ));
847        assert!(reads_as_failed("Tests: 1 failed, 5 passed, 6 total"));
848    }
849
850    #[test]
851    fn a_failed_run_in_codex_or_gemini_is_not_taken_for_a_pass() {
852        let dir = tempfile::tempdir().unwrap();
853        let root = dir.path().canonicalize().unwrap();
854        let server = start(&root, Arc::default()).unwrap();
855        let run = |response: Value| {
856            input(
857                &root,
858                json!({"tool_input": {"command": "cargo test"}, "tool_response": response}),
859            )
860        };
861        // Codex's result as JSON in a string, with its exit code.
862        let codex = json!({"exit_code": 101, "stdout": "error: test failed"}).to_string();
863        handle_for("Codex", "tool-done", &run(Value::String(codex)));
864        assert!(!next_test(&server).passed, "Codex's exit code");
865        // Gemini CLI says the exit code in its words.
866        let gemini =
867            json!({"llmContent": "Command: cargo test\nExit Code: 101", "returnDisplay": "…"});
868        handle_for("Gemini", "tool-done", &run(gemini));
869        assert!(!next_test(&server).passed, "Gemini's words");
870        // With no exit code at all, what the run printed decides.
871        let failing = json!({"output": "test result: FAILED. 3 passed; 1 failed"});
872        handle_for("Codex", "tool-done", &run(failing));
873        assert!(!next_test(&server).passed, "the output");
874        let passing = json!({"output": "test result: ok. 3 passed; 0 failed"});
875        handle_for("Codex", "tool-done", &run(passing));
876        assert!(next_test(&server).passed, "a pass still passes");
877    }
878    use std::sync::Arc;
879    use std::time::Duration;
880
881    fn input(dir: &Path, extra: Value) -> String {
882        let mut value = json!({"cwd": dir, "session_id": "s1"});
883        value
884            .as_object_mut()
885            .unwrap()
886            .extend(extra.as_object().unwrap().clone());
887        value.to_string()
888    }
889
890    fn comment() -> Comment {
891        Comment {
892            file: "a.rs".into(),
893            line: 3,
894            text: "why?".into(),
895            ..Comment::default()
896        }
897    }
898
899    #[test]
900    fn comments_reach_an_agent_in_order_with_what_they_are_about() {
901        let later = Comment {
902            file: "b.rs".into(),
903            line: 9,
904            text: "wall clock is wrong here".into(),
905            quote: "now = time.time()".into(),
906            removed: true,
907        };
908        let first = Comment {
909            quote: "fn main() {".into(),
910            ..comment()
911        };
912        let message = comments_message(&[later, first]);
913        let a = message
914            .find("a.rs line 3, on \"fn main() {\": why?")
915            .expect(&message);
916        let b = message.find("b.rs line 9 (a line your change removed), on \"now = time.time()\"");
917        assert!(b.is_some_and(|b| b > a), "{message}");
918    }
919
920    #[test]
921    fn nothing_breaks_with_no_cellix_running() {
922        let dir = tempfile::tempdir().unwrap();
923        for kind in ["session-start", "prompt", "notify", "stop", "session-end"] {
924            assert_eq!(handle(kind, &input(dir.path(), json!({}))), None);
925        }
926        let plan = input(dir.path(), json!({"tool_input": {"plan": "# P"}}));
927        assert_eq!(handle("plan", &plan), None, "Claude Code asks as usual");
928        assert_eq!(handle("prompt", "not json"), None);
929    }
930
931    #[test]
932    fn a_hook_with_no_details_asks_nothing_of_a_running_cellix() {
933        for kind in ["prompt", "plan", "stop"] {
934            assert_eq!(handle(kind, "not json"), None);
935            assert_eq!(handle(kind, "[1, 2]"), None);
936        }
937    }
938
939    #[test]
940    fn the_next_prompt_carries_pending_comments() {
941        let dir = tempfile::tempdir().unwrap();
942        let root = dir.path().canonicalize().unwrap();
943        let shared: SharedComments = Arc::new(std::sync::Mutex::new(vec![comment()]));
944        let _server = start(&root, shared.clone()).unwrap();
945        let hook = input(&root, json!({"prompt": "carry on"}));
946        let output = handle("prompt", &hook).unwrap();
947        let parsed: Value = serde_json::from_str(&output).unwrap();
948        let context = parsed["hookSpecificOutput"]["additionalContext"]
949            .as_str()
950            .unwrap();
951        assert!(context.contains("a.rs line 3: why?"), "{context}");
952        assert!(shared.lock().unwrap().is_empty(), "delivered once");
953        assert_eq!(handle("prompt", &hook), None);
954    }
955
956    #[test]
957    fn plan_decision_reaches_the_hook() {
958        let dir = tempfile::tempdir().unwrap();
959        let root = dir.path().canonicalize().unwrap();
960        let server = start(&root, Arc::default()).unwrap();
961        let hook = input(&root, json!({"tool_input": {"plan": "# Plan\n"}}));
962        let waiting = std::thread::spawn(move || handle("plan", &hook));
963        loop {
964            match server
965                .requests
966                .recv_timeout(Duration::from_secs(5))
967                .unwrap()
968            {
969                Request::Plan { path, reply } => {
970                    assert_eq!(std::fs::read_to_string(path).unwrap(), "# Plan\n");
971                    reply
972                        .send(Decision::SendBack("Split step two".into()))
973                        .unwrap();
974                    break;
975                }
976                _ => continue,
977            }
978        }
979        let output = waiting.join().unwrap().unwrap();
980        let parsed: Value = serde_json::from_str(&output).unwrap();
981        let answer = &parsed["hookSpecificOutput"];
982        assert_eq!(answer["hookEventName"], "PermissionRequest");
983        assert_eq!(answer["decision"]["behavior"], "deny");
984        assert_eq!(answer["decision"]["message"], "Split step two");
985    }
986
987    #[test]
988    fn a_plan_after_an_approved_one_starts_at_version_one() {
989        let dir = tempfile::tempdir().unwrap();
990        let root = dir.path().canonicalize().unwrap();
991        let server = start(&root, Arc::default()).unwrap();
992        // Sent back once, approved, then a new plan in the same session.
993        let answers = [
994            ("# One\n", Decision::SendBack("Fewer steps".into())),
995            ("# One, shorter\n", Decision::Approve(None)),
996            ("# Two\n", Decision::SendBack("Later".into())),
997        ];
998        let mut held = Vec::new();
999        for (plan, decision) in answers {
1000            let hook = input(&root, json!({"tool_input": {"plan": plan}}));
1001            let waiting = std::thread::spawn(move || handle("plan", &hook));
1002            loop {
1003                if let Request::Plan { path, reply } = server
1004                    .requests
1005                    .recv_timeout(Duration::from_secs(5))
1006                    .unwrap()
1007                {
1008                    let versions = (1..)
1009                        .map(|v| path.with_file_name(format!("Plan v{v}.md")))
1010                        .take_while(|p| p.exists())
1011                        .count();
1012                    held.push((path, versions));
1013                    reply.send(decision).unwrap();
1014                    break;
1015                }
1016            }
1017            waiting.join().unwrap();
1018        }
1019        assert_eq!(held[1].1, 1, "sent back, so the second is version 2");
1020        assert_eq!(held[2].1, 0, "after approval, a new plan is version 1");
1021        let away = held[2].0.with_file_name("Approved 1");
1022        let read = |name: &str| std::fs::read_to_string(away.join(name)).unwrap();
1023        assert_eq!(
1024            read("Plan.md"),
1025            "# One, shorter\n",
1026            "the approved plan is put away"
1027        );
1028        assert_eq!(read("Plan v1.md"), "# One\n");
1029    }
1030
1031    /// Runs a hook on a thread, and answers the plan it holds with `decision`.
1032    fn answered(
1033        agent: &'static str,
1034        kind: &'static str,
1035        hook: String,
1036        decision: Decision,
1037    ) -> (Option<String>, String) {
1038        let root = hook_root(&hook);
1039        let server = start(&root, Arc::default()).unwrap();
1040        let waiting = std::thread::spawn(move || handle_for(agent, kind, &hook));
1041        loop {
1042            if let Request::Plan { path, reply } = server
1043                .requests
1044                .recv_timeout(Duration::from_secs(5))
1045                .unwrap()
1046            {
1047                let held = std::fs::read_to_string(path).unwrap();
1048                reply.send(decision).unwrap();
1049                return (waiting.join().unwrap(), held);
1050            }
1051        }
1052    }
1053
1054    fn hook_root(hook: &str) -> PathBuf {
1055        let parsed: Value = serde_json::from_str(hook).unwrap();
1056        PathBuf::from(parsed["cwd"].as_str().unwrap())
1057    }
1058
1059    fn gemini_plan(root: &Path, text: &str) -> String {
1060        let plan = root.join("plan.md");
1061        std::fs::write(&plan, text).unwrap();
1062        input(root, json!({"tool_input": {"plan_path": plan}}))
1063    }
1064
1065    #[test]
1066    fn gemini_is_held_at_leaving_plan_mode_and_told_what_to_change() {
1067        let dir = tempfile::tempdir().unwrap();
1068        let root = dir.path().canonicalize().unwrap();
1069        let hook = gemini_plan(&root, "# G\n");
1070        let sent = Decision::SendBack("Fewer steps".into());
1071        let (output, held) = answered("Gemini", "plan", hook, sent);
1072        assert_eq!(held, "# G\n");
1073        let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
1074        assert_eq!(parsed["decision"], "deny");
1075        assert_eq!(parsed["reason"], "Fewer steps");
1076    }
1077
1078    #[test]
1079    fn an_edit_to_geminis_plan_goes_back_in_its_file() {
1080        let dir = tempfile::tempdir().unwrap();
1081        let root = dir.path().canonicalize().unwrap();
1082        let hook = gemini_plan(&root, "# Old\n");
1083        let edited = Decision::Approve(Some("# New\n".into()));
1084        let (output, _) = answered("Gemini", "plan", hook, edited);
1085        let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
1086        assert_eq!(parsed["decision"], "allow");
1087        assert_eq!(
1088            std::fs::read_to_string(root.join("plan.md")).unwrap(),
1089            "# New\n"
1090        );
1091    }
1092
1093    #[test]
1094    fn a_plan_from_codex_is_held_when_its_turn_ends() {
1095        let dir = tempfile::tempdir().unwrap();
1096        let root = dir.path().canonicalize().unwrap();
1097        let message = "Here it is.\n\n<proposed_plan>\n# C\n</proposed_plan>\n";
1098        let hook = input(&root, json!({"last_assistant_message": message}));
1099        let sent = Decision::SendBack("Say why".into());
1100        let (output, held) = answered("Codex", "stop", hook, sent);
1101        assert_eq!(held, "# C");
1102        let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
1103        assert_eq!(parsed["decision"], "block");
1104        assert_eq!(parsed["reason"], "Say why");
1105    }
1106
1107    #[test]
1108    fn approving_a_codex_plan_with_changes_hands_them_over() {
1109        let dir = tempfile::tempdir().unwrap();
1110        let root = dir.path().canonicalize().unwrap();
1111        let message = "<proposed_plan>\n# C\n</proposed_plan>";
1112        let hook = input(&root, json!({"last_assistant_message": message}));
1113        let changed = "# C\n\n## Reviewer notes\n- Keep the old API.".to_string();
1114        let (output, _) = answered("Codex", "stop", hook, Decision::Approve(Some(changed)));
1115        let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
1116        assert_eq!(parsed["decision"], "block");
1117        assert!(
1118            parsed["reason"]
1119                .as_str()
1120                .unwrap()
1121                .contains("Keep the old API.")
1122        );
1123    }
1124
1125    #[test]
1126    fn approving_a_codex_plan_lets_its_turn_end() {
1127        let dir = tempfile::tempdir().unwrap();
1128        let root = dir.path().canonicalize().unwrap();
1129        let message = "<proposed_plan>\n# C\n</proposed_plan>";
1130        let hook = input(&root, json!({"last_assistant_message": message}));
1131        let (output, _) = answered("Codex", "stop", hook, Decision::Approve(None));
1132        assert_eq!(output, None);
1133    }
1134
1135    #[test]
1136    fn an_ordinary_codex_turn_isnt_held() {
1137        assert_eq!(proposed_plan("Done, the tests pass."), None);
1138        assert_eq!(proposed_plan("<proposed_plan>cut off"), None);
1139        let dir = tempfile::tempdir().unwrap();
1140        let root = dir.path().canonicalize().unwrap();
1141        let _server = start(&root, Arc::default()).unwrap();
1142        let hook = input(&root, json!({"last_assistant_message": "All done."}));
1143        assert_eq!(handle_for("Codex", "stop", &hook), None);
1144    }
1145
1146    #[test]
1147    fn plan_hooks_are_given_time_for_a_person_to_read() {
1148        let hooks = |text: &str| serde_json::from_str::<Value>(text).unwrap();
1149        let gemini = hooks(include_str!(
1150            "../../cellix/integrations/gemini/hooks/hooks.json"
1151        ));
1152        let before = &gemini["hooks"]["BeforeTool"][0];
1153        assert_eq!(before["matcher"], "exit_plan_mode");
1154        assert_eq!(
1155            before["hooks"][0]["timeout"], 86_400_000,
1156            "Gemini counts milliseconds"
1157        );
1158        let codex = hooks(include_str!(
1159            "../../cellix/integrations/codex/hooks/hooks.json"
1160        ));
1161        assert_eq!(codex["hooks"]["Stop"][0]["hooks"][0]["timeout"], 86_400);
1162    }
1163
1164    #[test]
1165    fn an_edited_plan_is_written_only_to_claude_codes_own_plan_file() {
1166        let dir = tempfile::tempdir().unwrap();
1167        let plans = dir.path().join(".claude/plans");
1168        std::fs::create_dir_all(&plans).unwrap();
1169        let plan = plans.join("refunds.md");
1170        std::fs::write(&plan, "# Old").unwrap();
1171        assert!(write_plan_file(&plan, "# New", &plans));
1172        assert_eq!(std::fs::read_to_string(&plan).unwrap(), "# New");
1173        // Nothing outside its plans folder, nothing that isn't there yet, and no other kind.
1174        let settings = dir.path().join(".claude/settings.json");
1175        std::fs::write(&settings, "{}").unwrap();
1176        assert!(!write_plan_file(&settings, "# New", &plans));
1177        assert!(!write_plan_file(
1178            &plans.join("../settings.json"),
1179            "x",
1180            &plans
1181        ));
1182        assert!(!write_plan_file(&plans.join("new.md"), "x", &plans));
1183        assert!(!plans.join("new.md").exists());
1184        assert_eq!(std::fs::read_to_string(&settings).unwrap(), "{}");
1185        // A Gemini plan path must be a Markdown file that's really there.
1186        assert!(is_plain_markdown(&plan));
1187        assert!(!is_plain_markdown(&settings));
1188        #[cfg(unix)]
1189        {
1190            let link = plans.join("link.md");
1191            std::os::unix::fs::symlink(&settings, &link).unwrap();
1192            assert!(!is_plain_markdown(&link));
1193            assert!(!write_plan_file(&link, "x", &plans));
1194        }
1195    }
1196
1197    #[test]
1198    fn an_edited_plan_is_approved_as_edited() {
1199        let dir = tempfile::tempdir().unwrap();
1200        let root = dir.path().canonicalize().unwrap();
1201        let server = start(&root, Arc::default()).unwrap();
1202        let hook = input(
1203            &root,
1204            json!({"tool_input": {"plan": "# Old", "planFilePath": "/p.md"}}),
1205        );
1206        let waiting = std::thread::spawn(move || handle("plan", &hook));
1207        loop {
1208            if let Request::Plan { reply, .. } = server
1209                .requests
1210                .recv_timeout(Duration::from_secs(5))
1211                .unwrap()
1212            {
1213                reply.send(Decision::Approve(Some("# New".into()))).unwrap();
1214                break;
1215            }
1216        }
1217        let output = waiting.join().unwrap().unwrap();
1218        let parsed: Value = serde_json::from_str(&output).unwrap();
1219        let answer = &parsed["hookSpecificOutput"]["decision"];
1220        assert_eq!(answer["behavior"], "allow");
1221        assert_eq!(answer["updatedInput"]["plan"], "# New");
1222        assert_eq!(answer["updatedInput"]["planFilePath"], "/p.md");
1223    }
1224
1225    #[test]
1226    fn events_carry_the_agents_name() {
1227        let dir = tempfile::tempdir().unwrap();
1228        let root = dir.path().canonicalize().unwrap();
1229        let server = start(&root, Arc::default()).unwrap();
1230        handle_for("Codex", "session-start", &input(&root, json!({})));
1231        match server
1232            .requests
1233            .recv_timeout(Duration::from_secs(5))
1234            .unwrap()
1235        {
1236            Request::Agent(event) => assert_eq!(event.agent, "Codex"),
1237            other => panic!("{other:?}"),
1238        }
1239    }
1240
1241    #[test]
1242    fn a_failed_command_is_read_from_the_result() {
1243        let dir = tempfile::tempdir().unwrap();
1244        let root = dir.path().canonicalize().unwrap();
1245        let server = start(&root, Arc::default()).unwrap();
1246        let run = input(
1247            &root,
1248            json!({"tool_input": {"command": "cargo test"},
1249                   "tool_response": {"returnDisplay": "boom", "error": "exit 1"}}),
1250        );
1251        handle_for("Gemini", "tool-done", &run);
1252        let run = next_test(&server);
1253        assert!(!run.passed);
1254        assert_eq!(run.output, "boom");
1255    }
1256
1257    #[test]
1258    fn test_runs_are_reported_and_other_commands_are_not() {
1259        let dir = tempfile::tempdir().unwrap();
1260        let root = dir.path().canonicalize().unwrap();
1261        let server = start(&root, Arc::default()).unwrap();
1262        let other = input(&root, json!({"tool_input": {"command": "ls"}}));
1263        handle("tool-done", &other);
1264        let run = input(
1265            &root,
1266            json!({"tool_input": {"command": "cargo test"}, "tool_response": {"stdout": "ok"}}),
1267        );
1268        handle("tool-failed", &run);
1269        // The first test run to arrive is the second command's: `ls` only says it's working.
1270        let run = next_test(&server);
1271        assert_eq!(run.command, "cargo test");
1272        assert!(!run.passed);
1273    }
1274
1275    /// The next test run reported, past news of the agent working, which every tool sends.
1276    fn next_test(server: &Server) -> TestRun {
1277        loop {
1278            match server
1279                .requests
1280                .recv_timeout(Duration::from_secs(5))
1281                .unwrap()
1282            {
1283                Request::Test(run) => return run,
1284                Request::Agent(event) => assert_eq!(event.state, AgentState::Working),
1285                other => panic!("{other:?}"),
1286            }
1287        }
1288    }
1289
1290    /// The next news of an agent, or None if nothing comes for a while.
1291    fn next_event(server: &Server, wait: Duration) -> Option<AgentEvent> {
1292        match server.requests.recv_timeout(wait) {
1293            Ok(Request::Agent(event)) => Some(event),
1294            Ok(other) => panic!("{other:?}"),
1295            Err(_) => None,
1296        }
1297    }
1298
1299    #[test]
1300    fn only_a_request_counts_as_needing_you() {
1301        let dir = tempfile::tempdir().unwrap();
1302        let root = dir.path().canonicalize().unwrap();
1303        let server = start(&root, Arc::default()).unwrap();
1304        // Claude Code's reminder after an idle turn asks for nothing: it says the agent is
1305        // waiting, which after an interrupt nothing else does.
1306        let idle = "Claude is waiting for your input";
1307        handle(
1308            "notify",
1309            &input(
1310                &root,
1311                json!({"notification_type": "idle_prompt", "message": idle}),
1312            ),
1313        );
1314        let event = next_event(&server, Duration::from_secs(5)).unwrap();
1315        assert_eq!(
1316            (event.state, event.detail.as_str()),
1317            (AgentState::Idle, "Waiting for you")
1318        );
1319        // Nor does the reminder without its type, a sign-in, or a question already answered,
1320        // and none is told.
1321        handle("notify", &input(&root, json!({"message": idle})));
1322        for kind in [
1323            "auth_success",
1324            "elicitation_complete",
1325            "elicitation_response",
1326        ] {
1327            handle(
1328                "notify",
1329                &input(&root, json!({"notification_type": kind, "message": "Done"})),
1330            );
1331        }
1332        // A permission prompt is, and comes first.
1333        let asking = "Claude needs your permission to use Bash";
1334        handle(
1335            "notify",
1336            &input(
1337                &root,
1338                json!({"notification_type": "permission_prompt", "message": asking}),
1339            ),
1340        );
1341        let event = next_event(&server, Duration::from_secs(5)).unwrap();
1342        assert_eq!(
1343            (event.state, event.detail.as_str()),
1344            (AgentState::NeedsYou, asking)
1345        );
1346        // Codex asks through its permission hook, with the command and no words of its own.
1347        let codex = input(
1348            &root,
1349            json!({"tool_name": "Bash", "tool_input": {"command": "cargo publish"}}),
1350        );
1351        handle_for("Codex", "notify", &codex);
1352        let event = next_event(&server, Duration::from_secs(5)).unwrap();
1353        assert_eq!(event.state, AgentState::NeedsYou);
1354        assert_eq!(event.detail, "Codex asks to run cargo publish");
1355        // Gemini says what kind of notification it sends.
1356        let gemini = input(
1357            &root,
1358            json!({"notification_type": "ToolPermission", "message": "Allow rm?"}),
1359        );
1360        handle_for("Gemini", "notify", &gemini);
1361        assert_eq!(
1362            next_event(&server, Duration::from_secs(5)).unwrap().state,
1363            AgentState::NeedsYou
1364        );
1365        assert_eq!(next_event(&server, Duration::from_millis(300)), None);
1366    }
1367
1368    #[test]
1369    fn a_turn_the_api_cut_short_is_not_left_working() {
1370        let dir = tempfile::tempdir().unwrap();
1371        let root = dir.path().canonicalize().unwrap();
1372        let server = start(&root, Arc::default()).unwrap();
1373        // Claude Code's StopFailure, where a Stop would have come.
1374        handle(
1375            "stop-failed",
1376            &input(&root, json!({"error_type": "rate_limit"})),
1377        );
1378        let event = next_event(&server, Duration::from_secs(5)).unwrap();
1379        assert_eq!(
1380            (event.state, event.detail.as_str()),
1381            (AgentState::Idle, "Stopped: rate limit")
1382        );
1383        // And an elicitation is a question, as a permission prompt is.
1384        let asking = json!({"notification_type": "elicitation_dialog", "message": "Which port?"});
1385        handle("notify", &input(&root, asking));
1386        let event = next_event(&server, Duration::from_secs(5)).unwrap();
1387        assert_eq!(event.state, AgentState::NeedsYou);
1388    }
1389
1390    #[test]
1391    fn a_tool_that_ran_means_the_request_was_answered() {
1392        let dir = tempfile::tempdir().unwrap();
1393        let root = dir.path().canonicalize().unwrap();
1394        let server = start(&root, Arc::default()).unwrap();
1395        let asking = json!({"notification_type": "permission_prompt", "message": "Claude needs your permission to use Edit"});
1396        handle("notify", &input(&root, asking));
1397        let event = next_event(&server, Duration::from_secs(5)).unwrap();
1398        assert_eq!(event.state, AgentState::NeedsYou);
1399        // On Unix, it says which process it is, so one that's gone can be let go.
1400        assert_eq!(event.pid.is_some(), cfg!(unix));
1401        // Approved in the agent, the tool runs, and its hook says the agent is working.
1402        let edited = json!({"tool_name": "Edit", "tool_input": {"file_path": "notes.txt"}});
1403        handle("tool-done", &input(&root, edited));
1404        let event = next_event(&server, Duration::from_secs(5)).unwrap();
1405        assert_eq!(event.state, AgentState::Working);
1406    }
1407
1408    #[test]
1409    fn an_agents_work_is_logged_for_the_task_view() {
1410        let dir = tempfile::tempdir().unwrap();
1411        let root = dir.path().canonicalize().unwrap();
1412        let git = |args: &[&str]| {
1413            let status = Command::new("git").arg("-C").arg(&root).args(args).status();
1414            assert!(status.unwrap().success());
1415        };
1416        git(&["init", "-q"]);
1417        std::fs::write(root.join("a.rs"), "fn a() {}\n").unwrap();
1418        git(&["add", "."]);
1419        git(&[
1420            "-c",
1421            "user.name=T",
1422            "-c",
1423            "user.email=t@example.com",
1424            "commit",
1425            "-qm",
1426            "a",
1427        ]);
1428        let server = start(&root, Arc::default()).unwrap();
1429        handle(
1430            "prompt",
1431            &input(&root, json!({"prompt": "Add a refund route"})),
1432        );
1433        // Plans sent back once and then approved, as the reviewer answers them.
1434        for decision in [
1435            Decision::SendBack("Only paid orders".into()),
1436            Decision::Approve(None),
1437        ] {
1438            let hook = input(&root, json!({"tool_input": {"plan": "# Refunds\n"}}));
1439            let waiting = std::thread::spawn(move || handle("plan", &hook));
1440            loop {
1441                let request = server
1442                    .requests
1443                    .recv_timeout(Duration::from_secs(5))
1444                    .unwrap();
1445                if let Request::Plan { reply, .. } = request {
1446                    reply.send(decision).unwrap();
1447                    break;
1448                }
1449            }
1450            waiting.join().unwrap();
1451        }
1452        let run = input(
1453            &root,
1454            json!({"tool_input": {"command": "cargo test"}, "tool_response": {"stdout": "FAILED"}}),
1455        );
1456        handle("tool-failed", &run);
1457
1458        let events = tasks::load(&root);
1459        let found = tasks::tasks(&events, |_| None);
1460        assert_eq!(found.len(), 1, "{events:?}");
1461        let task = &found[0];
1462        assert_eq!(
1463            (task.name.as_str(), task.agent.as_str()),
1464            ("Add a refund route", "Claude Code")
1465        );
1466        let turn = task.turns().next().unwrap();
1467        assert!(
1468            turn.commit.is_some(),
1469            "the prompt is logged with its checkpoint"
1470        );
1471        assert_eq!(turn.tests.len(), 1);
1472        assert!(!turn.tests[0].passed);
1473        let outcomes: Vec<&tasks::Outcome> = task.plans().map(|p| &p.outcome).collect();
1474        assert_eq!(
1475            outcomes[0],
1476            &tasks::Outcome::SentBack("Only paid orders".into())
1477        );
1478        assert!(matches!(outcomes[1], tasks::Outcome::Approved(Some(_))));
1479        // The log stays out of the project's changes.
1480        let ignore = std::fs::read_to_string(root.join(".cellix/.gitignore")).unwrap();
1481        assert!(ignore.contains("tasks.jsonl"));
1482    }
1483}