cellix-agent 0.5.4

Local socket and CLI adapters for Cellix
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! `cellix hook <kind>`: what Claude Code's hooks call. Nothing here may disturb the agent,
//! so with no Cellix running every kind quietly does nothing but keep its checkpoints.

use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use cellix_review::{Comment, Thread, checkpoint};
use serde_json::{Value, json};

use crate::{AgentEvent, AgentState, TestRun, request, socket_path};

/// Longest test output kept, from the end, where failures are.
const MAX_OUTPUT: usize = 20_000;
const LABEL_LENGTH: usize = 60;
/// Where `handle_for` leaves the agent's name in a hook's input.
const AGENT_KEY: &str = "cellix_agent";
/// Set by Cellix's session host to its socket, for a program it holds.
pub const HELD_VAR: &str = "CELLIX_HELD";

/// How to resume an agent held by Cellix, left by its hooks beside the host's socket so it
/// outlives the host, as when the machine restarts.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Resumable {
    /// The agent, as Cellix names it: "Claude Code", "Codex".
    pub agent: String,
    /// The agent's own session id.
    pub session: String,
}

/// Leaves word beside `held`, the host's socket, of the agent session running there.
/// Unchanged word isn't written again.
pub fn remember(held: &Path, agent: &str, session: &str) {
    if session.is_empty() || !held.extension().is_some_and(|e| e == "sock") {
        return;
    }
    let word = Resumable {
        agent: agent.to_string(),
        session: session.to_string(),
    };
    let path = held.with_extension("agent");
    let known = std::fs::read(&path)
        .ok()
        .and_then(|bytes| serde_json::from_slice::<Resumable>(&bytes).ok());
    if known.as_ref() == Some(&word) {
        return;
    }
    if let Ok(json) = serde_json::to_vec(&word) {
        let _ = std::fs::write(path, json);
    }
}
/// What an agent reports while its plan is with the reviewer.
pub const PLAN_WAITING: &str = "Plan waiting for review";
/// How long the prompt hook waits for its checkpoint. An agent gives a hook a fixed time and
/// drops what it says after that, comments included, and a first checkpoint of a large tree
/// can take longer; past this it finishes on its own.
const CHECKPOINT_WAIT: Duration = Duration::from_secs(3);

/// Commands whose results belong beside the diff.
const TEST_COMMANDS: [&str; 13] = [
    "cargo test",
    "cargo nextest",
    "pytest",
    "npm test",
    "npm run test",
    "pnpm test",
    "yarn test",
    "vitest",
    "jest",
    "go test",
    "rspec",
    "make test",
    "harness/x",
];

pub fn is_test_command(command: &str) -> bool {
    TEST_COMMANDS.iter().any(|c| command.contains(c))
}

/// The folders a Cellix for this session might be serving, most specific first.
fn roots(input: &Value) -> Vec<PathBuf> {
    let cwd = input["cwd"]
        .as_str()
        .map(PathBuf::from)
        .or_else(|| std::env::current_dir().ok())
        .unwrap_or_default();
    workspaces(&cwd)
}

/// The folders a Cellix for `folder` might be serving: it, then its repository's root.
pub fn workspaces(folder: &std::path::Path) -> Vec<PathBuf> {
    let cwd = dunce::canonicalize(folder).unwrap_or_else(|_| folder.to_path_buf());
    let mut roots = vec![cwd.clone()];
    let top = Command::new("git")
        .arg("-C")
        .arg(&cwd)
        .args(["rev-parse", "--show-toplevel"])
        .output();
    if let Ok(output) = top
        && output.status.success()
    {
        let text = String::from_utf8_lossy(&output.stdout);
        let top = PathBuf::from(text.trim());
        // git on Windows writes `C:/x`, and the socket is found by the path as Cellix has it.
        let top = if cfg!(windows) {
            dunce::canonicalize(&top).unwrap_or(top)
        } else {
            top
        };
        roots.push(top);
    }
    roots
}

fn ask(roots: &[PathBuf], line: &str) -> Option<String> {
    roots.iter().find_map(|root| request(root, line).ok())
}

fn tell(roots: &[PathBuf], input: &Value, state: AgentState, detail: &str) {
    let event = AgentEvent {
        session: input["session_id"].as_str().unwrap_or("").to_string(),
        agent: input[AGENT_KEY]
            .as_str()
            .unwrap_or("Claude Code")
            .to_string(),
        state,
        detail: detail.to_string(),
        folder: roots
            .first()
            .map(|r| r.display().to_string())
            .unwrap_or_default(),
    };
    if let Ok(json) = serde_json::to_string(&event) {
        ask(roots, &format!("event {json}"));
    }
}

/// Comments as a message an agent can act on.
pub fn comments_message(comments: &[Comment]) -> String {
    let mut text = String::from("Review comments on your changes:\n");
    // In file and line order, as they'd be read, not the order they were written.
    let mut sorted: Vec<&Comment> = comments.iter().collect();
    sorted.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
    for comment in sorted {
        text.push_str(&format!("- {}\n", comment.message()));
    }
    text
}

fn label(prompt: &str) -> String {
    let line = prompt.lines().next().unwrap_or("Prompt").trim();
    let mut label: String = line.chars().take(LABEL_LENGTH).collect();
    if line.chars().count() > LABEL_LENGTH {
        label.push('…');
    }
    label
}

fn on_prompt(roots: &[PathBuf], input: &Value) -> Option<String> {
    if let Some(root) = roots.first() {
        let prompt = input["prompt"].as_str().unwrap_or("Prompt");
        checkpoint_briefly(root, &label(prompt));
    }
    tell(roots, input, AgentState::Working, "Working");
    let comments: Vec<Comment> = ask(roots, "take")
        .and_then(|reply| serde_json::from_str(&reply).ok())
        .unwrap_or_default();
    let threads: Vec<Thread> = ask(roots, "take-threads")
        .and_then(|reply| serde_json::from_str(&reply).ok())
        .unwrap_or_default();
    let mut context = String::new();
    if !comments.is_empty() {
        context.push_str(&comments_message(&comments));
    }
    for thread in &threads {
        context.push_str(&thread.message());
        context.push('\n');
    }
    if context.is_empty() {
        return None;
    }
    let output = json!({"hookSpecificOutput": {
        "hookEventName": "UserPromptSubmit",
        "additionalContext": context,
    }});
    Some(output.to_string())
}

/// Checkpoints in a process of its own, waiting at most `CHECKPOINT_WAIT` for it.
fn checkpoint_briefly(root: &Path, label: &str) {
    // Only the real binary has a `checkpoint` command; a test runs it here instead.
    let exe = std::env::current_exe()
        .ok()
        .filter(|exe| exe.file_stem().is_some_and(|stem| stem == "cellix"));
    let Some(exe) = exe else {
        checkpoint(root, label);
        return;
    };
    let mut command = Command::new(exe);
    command
        .args(["checkpoint", label])
        .current_dir(root)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    // Its own group, so it isn't stopped with the hook that started it.
    #[cfg(unix)]
    std::os::unix::process::CommandExt::process_group(&mut command, 0);
    let Ok(mut child) = command.spawn() else {
        return;
    };
    let started = Instant::now();
    while started.elapsed() < CHECKPOINT_WAIT {
        if !matches!(child.try_wait(), Ok(None)) {
            return;
        }
        std::thread::sleep(Duration::from_millis(10));
    }
}

/// Holds a plan until the reviewer decides, and gives back the verdict and any text with it.
fn review_plan(roots: &[PathBuf], input: &Value, plan: &str) -> Option<(String, Option<String>)> {
    let socket = roots.iter().map(|r| socket_path(r)).find(|s| s.exists())?;
    let session: String = input["session_id"]
        .as_str()
        .unwrap_or("session")
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
        .collect();
    // Beside the socket, because that folder is private and /tmp on a server isn't.
    let folder = socket.with_extension("").join(session);
    std::fs::create_dir_all(&folder).ok()?;
    let path = keep_versions(&folder, plan).ok()?;
    tell(roots, input, AgentState::NeedsYou, PLAN_WAITING);
    let reply = ask(roots, &format!("plan {}", path.display()))?;
    let (verdict, text) = reply.split_once(' ').unwrap_or((&reply, "null"));
    // An approved plan is done with, so the next one the session sends starts at version one.
    if verdict == "approve" {
        let _ = put_versions_away(&folder);
    }
    Some((verdict.to_string(), serde_json::from_str(text).ok()?))
}

/// Moves an approved plan and its earlier versions into `Approved 1`, `Approved 2` and on, so
/// a plan sent after it isn't taken for its next version. Cellix keeps the approved one with
/// the project, and its comments with it.
pub fn put_versions_away(folder: &Path) -> std::io::Result<()> {
    let plan = folder.join("Plan.md");
    if !plan.exists() {
        return Ok(());
    }
    let mut number = 1;
    while folder.join(format!("Approved {number}")).exists() {
        number += 1;
    }
    let away = folder.join(format!("Approved {number}"));
    std::fs::create_dir_all(&away)?;
    let mut version = 1;
    loop {
        let name = format!("Plan v{version}.md");
        if !folder.join(&name).exists() {
            break;
        }
        std::fs::rename(folder.join(&name), away.join(&name))?;
        version += 1;
    }
    std::fs::rename(plan, away.join("Plan.md"))
}

/// Writes the plan as `Plan.md`, keeping the one it replaces as `Plan v1.md`, `Plan v2.md` and on,
/// so a reviewer can see what changed since they sent it back. Comments stay on `Plan.md`.
pub fn keep_versions(folder: &Path, plan: &str) -> std::io::Result<PathBuf> {
    let path = folder.join("Plan.md");
    if let Ok(old) = std::fs::read_to_string(&path)
        && old != plan
    {
        let mut version = 1;
        while folder.join(format!("Plan v{version}.md")).exists() {
            version += 1;
        }
        std::fs::write(folder.join(format!("Plan v{version}.md")), old)?;
    }
    std::fs::write(&path, plan)?;
    Ok(path)
}

/// Claude Code's plan, from its permission request. With no Cellix, it asks as usual.
fn on_plan(roots: &[PathBuf], input: &Value) -> Option<String> {
    let plan = input["tool_input"]["plan"].as_str()?;
    let (verdict, text) = review_plan(roots, input, plan)?;
    // A PreToolUse answer wouldn't do: Claude Code still shows its own plan dialog.
    let decision = match (verdict.as_str(), text) {
        ("send-back", Some(message)) => json!({"behavior": "deny", "message": message}),
        ("approve", edited) => {
            // Claude Code only counts an approval as the user's answer if it carries the input.
            let mut plan_input = input["tool_input"].clone();
            if let Some(edited) = edited {
                plan_input["plan"] = json!(edited);
            }
            json!({"behavior": "allow", "updatedInput": plan_input})
        }
        _ => return None,
    };
    let output = json!({"hookSpecificOutput": {
        "hookEventName": "PermissionRequest",
        "decision": decision,
    }});
    Some(output.to_string())
}

/// Gemini CLI's plan, as it goes to leave plan mode. It keeps plans in a file, so an edited
/// one is written back there, and Gemini still asks for its own approval afterwards.
fn on_gemini_plan(roots: &[PathBuf], input: &Value) -> Option<String> {
    let path = PathBuf::from(input["tool_input"]["plan_path"].as_str()?);
    let path = match input["cwd"].as_str() {
        Some(folder) => Path::new(folder).join(path),
        None => path,
    };
    let plan = std::fs::read_to_string(&path).ok()?;
    let (verdict, text) = review_plan(roots, input, &plan)?;
    let output = match (verdict.as_str(), text) {
        ("send-back", Some(reason)) => json!({"decision": "deny", "reason": reason}),
        ("approve", edited) => {
            if let Some(edited) = edited {
                std::fs::write(&path, edited).ok()?;
            }
            json!({"decision": "allow"})
        }
        _ => return None,
    };
    Some(output.to_string())
}

/// The plan in a message from Codex, which has no tool for proposing one.
fn proposed_plan(message: &str) -> Option<&str> {
    let (_, rest) = message.split_once("<proposed_plan>")?;
    let (plan, _) = rest.split_once("</proposed_plan>")?;
    Some(plan.trim())
}

/// Codex ends its turn on a plan, so that's when it's held. Sending it back starts another
/// turn with the reviewer's words. Approving lets the turn end, and implementing it is still
/// the user's to ask for in Codex; approving with changes or notes starts one more turn, so
/// Codex has them before it's asked.
fn on_codex_stop(roots: &[PathBuf], input: &Value) -> Option<String> {
    let plan = proposed_plan(input["last_assistant_message"].as_str()?)?;
    let (verdict, text) = review_plan(roots, input, plan)?;
    match (verdict.as_str(), text) {
        ("send-back", Some(reason)) => {
            Some(json!({"decision": "block", "reason": reason}).to_string())
        }
        ("approve", Some(changed)) if changed.trim() != plan.trim() => {
            let reason = format!(
                "The reviewer approved your plan with changes. This is the plan to follow \
                 now; implement it when asked.\n\n{changed}"
            );
            Some(json!({"decision": "block", "reason": reason}).to_string())
        }
        _ => None,
    }
}

/// Whether a command's exit is really that of its last stage, such as `tail`, and not the
/// tests'. With `pipefail` the shell reports the failure itself.
fn piped(command: &str) -> bool {
    let bare = command.replace("||", "");
    bare.contains('|') && !command.contains("pipefail")
}

/// What failing tests print, for when the exit can't be trusted.
fn reads_as_failed(output: &str) -> bool {
    ["FAILED", "failures:", "test result: F", " failed", "FAIL "]
        .iter()
        .any(|mark| output.contains(mark))
}

fn on_tool(roots: &[PathBuf], input: &Value, passed: bool) {
    let command = input["tool_input"]["command"].as_str().unwrap_or("");
    if !is_test_command(command) {
        return;
    }
    let response = &input["tool_response"];
    let text = response["stdout"]
        .as_str()
        .or_else(|| input["error"].as_str())
        .or_else(|| response["returnDisplay"].as_str())
        .or_else(|| response["output"].as_str())
        .or_else(|| response.as_str())
        .unwrap_or("");
    // Agents without a failure hook say so in the result.
    let exit = response["exit_code"]
        .as_i64()
        .or(response["exitCode"].as_i64());
    let passed = passed
        && exit.unwrap_or(0) == 0
        && response["error"].is_null()
        && !(piped(command) && reads_as_failed(text));
    let start = text
        .char_indices()
        .rev()
        .nth(MAX_OUTPUT)
        .map_or(0, |(at, _)| at);
    let run = TestRun {
        command: command.to_string(),
        passed,
        output: text[start..].to_string(),
    };
    if let Ok(json) = serde_json::to_string(&run) {
        ask(roots, &format!("test {json}"));
    }
}

/// Handles one hook from Claude Code.
pub fn handle(kind: &str, stdin: &str) -> Option<String> {
    handle_for("Claude Code", kind, stdin)
}

/// Handles one hook from a named agent, and returns what to print for it, if anything.
pub fn handle_for(agent: &str, kind: &str, stdin: &str) -> Option<String> {
    // Without its details this can't be told from a stray call, and nothing here should
    // guess which project it's about, least of all from the folder it happens to run in.
    let mut input: Value = serde_json::from_str(stdin).ok()?;
    if !input.is_object() {
        return None;
    }
    input[AGENT_KEY] = json!(agent);
    let roots = roots(&input);
    if matches!(kind, "session-start" | "prompt")
        && let Some(held) = std::env::var_os(HELD_VAR)
    {
        remember(
            Path::new(&held),
            agent,
            input["session_id"].as_str().unwrap_or(""),
        );
    }
    match kind {
        "session-start" => tell(&roots, &input, AgentState::Idle, "Ready"),
        "prompt" => return on_prompt(&roots, &input),
        "plan" if agent == "Gemini" => return on_gemini_plan(&roots, &input),
        "plan" => return on_plan(&roots, &input),
        "notify" => {
            let detail = input["message"].as_str().unwrap_or("Needs your attention");
            tell(&roots, &input, AgentState::NeedsYou, detail);
        }
        "tool-done" => on_tool(&roots, &input, true),
        "tool-failed" => on_tool(&roots, &input, false),
        "stop" => {
            tell(&roots, &input, AgentState::Idle, "Finished");
            if agent == "Codex" {
                return on_codex_stop(&roots, &input);
            }
        }
        "session-end" => tell(&roots, &input, AgentState::Ended, "Ended"),
        _ => {}
    }
    None
}

#[cfg(test)]
mod tests {
    #[test]
    fn a_held_agent_leaves_word_of_how_to_resume_it() {
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("1-2.sock");
        super::remember(&socket, "Claude Code", "abc-123");
        let word: super::Resumable =
            serde_json::from_slice(&std::fs::read(dir.path().join("1-2.agent")).unwrap()).unwrap();
        assert_eq!(word.agent, "Claude Code");
        assert_eq!(word.session, "abc-123");
        // A /clear starts a new session, which replaces it.
        super::remember(&socket, "Claude Code", "def-456");
        let text = std::fs::read_to_string(dir.path().join("1-2.agent")).unwrap();
        assert!(text.contains("def-456"), "{text}");
        // Nothing without an id, and nothing beside what isn't a host's socket.
        super::remember(&socket, "Claude Code", "");
        assert!(
            std::fs::read_to_string(dir.path().join("1-2.agent"))
                .unwrap()
                .contains("def-456")
        );
        super::remember(&dir.path().join("notes.txt"), "Claude Code", "x");
        assert!(!dir.path().join("notes.agent").exists());
    }

    use super::*;
    use crate::{Decision, Request, SharedComments, start};
    use std::path::Path;

    #[test]
    fn each_plan_keeps_the_one_before_it() {
        let dir = tempfile::tempdir().unwrap();
        keep_versions(dir.path(), "first").unwrap();
        keep_versions(dir.path(), "first").unwrap();
        assert!(
            !dir.path().join("Plan v1.md").exists(),
            "the same plan again is no version"
        );
        keep_versions(dir.path(), "second").unwrap();
        let path = keep_versions(dir.path(), "third").unwrap();
        assert_eq!(std::fs::read_to_string(path).unwrap(), "third");
        let read = |name: &str| std::fs::read_to_string(dir.path().join(name)).unwrap();
        assert_eq!(read("Plan v1.md"), "first");
        assert_eq!(read("Plan v2.md"), "second");
    }

    #[test]
    fn a_pipe_hides_a_failed_test_and_the_output_gives_it_away() {
        assert!(piped("cargo test | tail"));
        assert!(!piped("cargo test || true"));
        assert!(!piped("set -o pipefail; cargo test | tail"));
        assert!(reads_as_failed("test result: FAILED. 1 passed; 2 failed"));
        assert!(!reads_as_failed("test result: ok. 9 passed; 0 ignored"));
    }
    use std::sync::Arc;
    use std::time::Duration;

    fn input(dir: &Path, extra: Value) -> String {
        let mut value = json!({"cwd": dir, "session_id": "s1"});
        value
            .as_object_mut()
            .unwrap()
            .extend(extra.as_object().unwrap().clone());
        value.to_string()
    }

    fn comment() -> Comment {
        Comment {
            file: "a.rs".into(),
            line: 3,
            text: "why?".into(),
            ..Comment::default()
        }
    }

    #[test]
    fn comments_reach_an_agent_in_order_with_what_they_are_about() {
        let later = Comment {
            file: "b.rs".into(),
            line: 9,
            text: "wall clock is wrong here".into(),
            quote: "now = time.time()".into(),
            removed: true,
        };
        let first = Comment {
            quote: "fn main() {".into(),
            ..comment()
        };
        let message = comments_message(&[later, first]);
        let a = message
            .find("a.rs line 3, on \"fn main() {\": why?")
            .expect(&message);
        let b = message.find("b.rs line 9 (a line your change removed), on \"now = time.time()\"");
        assert!(b.is_some_and(|b| b > a), "{message}");
    }

    #[test]
    fn nothing_breaks_with_no_cellix_running() {
        let dir = tempfile::tempdir().unwrap();
        for kind in ["session-start", "prompt", "notify", "stop", "session-end"] {
            assert_eq!(handle(kind, &input(dir.path(), json!({}))), None);
        }
        let plan = input(dir.path(), json!({"tool_input": {"plan": "# P"}}));
        assert_eq!(handle("plan", &plan), None, "Claude Code asks as usual");
        assert_eq!(handle("prompt", "not json"), None);
    }

    #[test]
    fn a_hook_with_no_details_asks_nothing_of_a_running_cellix() {
        for kind in ["prompt", "plan", "stop"] {
            assert_eq!(handle(kind, "not json"), None);
            assert_eq!(handle(kind, "[1, 2]"), None);
        }
    }

    #[test]
    fn the_next_prompt_carries_pending_comments() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let shared: SharedComments = Arc::new(std::sync::Mutex::new(vec![comment()]));
        let _server = start(&root, shared.clone()).unwrap();
        let hook = input(&root, json!({"prompt": "carry on"}));
        let output = handle("prompt", &hook).unwrap();
        let parsed: Value = serde_json::from_str(&output).unwrap();
        let context = parsed["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap();
        assert!(context.contains("a.rs line 3: why?"), "{context}");
        assert!(shared.lock().unwrap().is_empty(), "delivered once");
        assert_eq!(handle("prompt", &hook), None);
    }

    #[test]
    fn plan_decision_reaches_the_hook() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let server = start(&root, Arc::default()).unwrap();
        let hook = input(&root, json!({"tool_input": {"plan": "# Plan\n"}}));
        let waiting = std::thread::spawn(move || handle("plan", &hook));
        loop {
            match server
                .requests
                .recv_timeout(Duration::from_secs(5))
                .unwrap()
            {
                Request::Plan { path, reply } => {
                    assert_eq!(std::fs::read_to_string(path).unwrap(), "# Plan\n");
                    reply
                        .send(Decision::SendBack("Split step two".into()))
                        .unwrap();
                    break;
                }
                _ => continue,
            }
        }
        let output = waiting.join().unwrap().unwrap();
        let parsed: Value = serde_json::from_str(&output).unwrap();
        let answer = &parsed["hookSpecificOutput"];
        assert_eq!(answer["hookEventName"], "PermissionRequest");
        assert_eq!(answer["decision"]["behavior"], "deny");
        assert_eq!(answer["decision"]["message"], "Split step two");
    }

    #[test]
    fn a_plan_after_an_approved_one_starts_at_version_one() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let server = start(&root, Arc::default()).unwrap();
        // Sent back once, approved, then a new plan in the same session.
        let answers = [
            ("# One\n", Decision::SendBack("Fewer steps".into())),
            ("# One, shorter\n", Decision::Approve(None)),
            ("# Two\n", Decision::SendBack("Later".into())),
        ];
        let mut held = Vec::new();
        for (plan, decision) in answers {
            let hook = input(&root, json!({"tool_input": {"plan": plan}}));
            let waiting = std::thread::spawn(move || handle("plan", &hook));
            loop {
                if let Request::Plan { path, reply } = server
                    .requests
                    .recv_timeout(Duration::from_secs(5))
                    .unwrap()
                {
                    let versions = (1..)
                        .map(|v| path.with_file_name(format!("Plan v{v}.md")))
                        .take_while(|p| p.exists())
                        .count();
                    held.push((path, versions));
                    reply.send(decision).unwrap();
                    break;
                }
            }
            waiting.join().unwrap();
        }
        assert_eq!(held[1].1, 1, "sent back, so the second is version 2");
        assert_eq!(held[2].1, 0, "after approval, a new plan is version 1");
        let away = held[2].0.with_file_name("Approved 1");
        let read = |name: &str| std::fs::read_to_string(away.join(name)).unwrap();
        assert_eq!(
            read("Plan.md"),
            "# One, shorter\n",
            "the approved plan is put away"
        );
        assert_eq!(read("Plan v1.md"), "# One\n");
    }

    /// Runs a hook on a thread, and answers the plan it holds with `decision`.
    fn answered(
        agent: &'static str,
        kind: &'static str,
        hook: String,
        decision: Decision,
    ) -> (Option<String>, String) {
        let root = hook_root(&hook);
        let server = start(&root, Arc::default()).unwrap();
        let waiting = std::thread::spawn(move || handle_for(agent, kind, &hook));
        loop {
            if let Request::Plan { path, reply } = server
                .requests
                .recv_timeout(Duration::from_secs(5))
                .unwrap()
            {
                let held = std::fs::read_to_string(path).unwrap();
                reply.send(decision).unwrap();
                return (waiting.join().unwrap(), held);
            }
        }
    }

    fn hook_root(hook: &str) -> PathBuf {
        let parsed: Value = serde_json::from_str(hook).unwrap();
        PathBuf::from(parsed["cwd"].as_str().unwrap())
    }

    fn gemini_plan(root: &Path, text: &str) -> String {
        let plan = root.join("plan.md");
        std::fs::write(&plan, text).unwrap();
        input(root, json!({"tool_input": {"plan_path": plan}}))
    }

    #[test]
    fn gemini_is_held_at_leaving_plan_mode_and_told_what_to_change() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let hook = gemini_plan(&root, "# G\n");
        let sent = Decision::SendBack("Fewer steps".into());
        let (output, held) = answered("Gemini", "plan", hook, sent);
        assert_eq!(held, "# G\n");
        let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
        assert_eq!(parsed["decision"], "deny");
        assert_eq!(parsed["reason"], "Fewer steps");
    }

    #[test]
    fn an_edit_to_geminis_plan_goes_back_in_its_file() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let hook = gemini_plan(&root, "# Old\n");
        let edited = Decision::Approve(Some("# New\n".into()));
        let (output, _) = answered("Gemini", "plan", hook, edited);
        let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
        assert_eq!(parsed["decision"], "allow");
        assert_eq!(
            std::fs::read_to_string(root.join("plan.md")).unwrap(),
            "# New\n"
        );
    }

    #[test]
    fn a_plan_from_codex_is_held_when_its_turn_ends() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let message = "Here it is.\n\n<proposed_plan>\n# C\n</proposed_plan>\n";
        let hook = input(&root, json!({"last_assistant_message": message}));
        let sent = Decision::SendBack("Say why".into());
        let (output, held) = answered("Codex", "stop", hook, sent);
        assert_eq!(held, "# C");
        let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
        assert_eq!(parsed["decision"], "block");
        assert_eq!(parsed["reason"], "Say why");
    }

    #[test]
    fn approving_a_codex_plan_with_changes_hands_them_over() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let message = "<proposed_plan>\n# C\n</proposed_plan>";
        let hook = input(&root, json!({"last_assistant_message": message}));
        let changed = "# C\n\n## Reviewer notes\n- Keep the old API.".to_string();
        let (output, _) = answered("Codex", "stop", hook, Decision::Approve(Some(changed)));
        let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
        assert_eq!(parsed["decision"], "block");
        assert!(
            parsed["reason"]
                .as_str()
                .unwrap()
                .contains("Keep the old API.")
        );
    }

    #[test]
    fn approving_a_codex_plan_lets_its_turn_end() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let message = "<proposed_plan>\n# C\n</proposed_plan>";
        let hook = input(&root, json!({"last_assistant_message": message}));
        let (output, _) = answered("Codex", "stop", hook, Decision::Approve(None));
        assert_eq!(output, None);
    }

    #[test]
    fn an_ordinary_codex_turn_isnt_held() {
        assert_eq!(proposed_plan("Done, the tests pass."), None);
        assert_eq!(proposed_plan("<proposed_plan>cut off"), None);
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let _server = start(&root, Arc::default()).unwrap();
        let hook = input(&root, json!({"last_assistant_message": "All done."}));
        assert_eq!(handle_for("Codex", "stop", &hook), None);
    }

    #[test]
    fn plan_hooks_are_given_time_for_a_person_to_read() {
        let hooks = |text: &str| serde_json::from_str::<Value>(text).unwrap();
        let gemini = hooks(include_str!(
            "../../cellix/integrations/gemini/hooks/hooks.json"
        ));
        let before = &gemini["hooks"]["BeforeTool"][0];
        assert_eq!(before["matcher"], "exit_plan_mode");
        assert_eq!(
            before["hooks"][0]["timeout"], 86_400_000,
            "Gemini counts milliseconds"
        );
        let codex = hooks(include_str!(
            "../../cellix/integrations/codex/hooks/hooks.json"
        ));
        assert_eq!(codex["hooks"]["Stop"][0]["hooks"][0]["timeout"], 86_400);
    }

    #[test]
    fn an_edited_plan_is_approved_as_edited() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let server = start(&root, Arc::default()).unwrap();
        let hook = input(
            &root,
            json!({"tool_input": {"plan": "# Old", "planFilePath": "/p.md"}}),
        );
        let waiting = std::thread::spawn(move || handle("plan", &hook));
        loop {
            if let Request::Plan { reply, .. } = server
                .requests
                .recv_timeout(Duration::from_secs(5))
                .unwrap()
            {
                reply.send(Decision::Approve(Some("# New".into()))).unwrap();
                break;
            }
        }
        let output = waiting.join().unwrap().unwrap();
        let parsed: Value = serde_json::from_str(&output).unwrap();
        let answer = &parsed["hookSpecificOutput"]["decision"];
        assert_eq!(answer["behavior"], "allow");
        assert_eq!(answer["updatedInput"]["plan"], "# New");
        assert_eq!(answer["updatedInput"]["planFilePath"], "/p.md");
    }

    #[test]
    fn events_carry_the_agents_name() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let server = start(&root, Arc::default()).unwrap();
        handle_for("Codex", "session-start", &input(&root, json!({})));
        match server
            .requests
            .recv_timeout(Duration::from_secs(5))
            .unwrap()
        {
            Request::Agent(event) => assert_eq!(event.agent, "Codex"),
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn a_failed_command_is_read_from_the_result() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let server = start(&root, Arc::default()).unwrap();
        let run = input(
            &root,
            json!({"tool_input": {"command": "cargo test"},
                   "tool_response": {"returnDisplay": "boom", "error": "exit 1"}}),
        );
        handle_for("Gemini", "tool-done", &run);
        match server
            .requests
            .recv_timeout(Duration::from_secs(5))
            .unwrap()
        {
            Request::Test(run) => {
                assert!(!run.passed);
                assert_eq!(run.output, "boom");
            }
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn test_runs_are_reported_and_other_commands_are_not() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let server = start(&root, Arc::default()).unwrap();
        let other = input(&root, json!({"tool_input": {"command": "ls"}}));
        handle("tool-done", &other);
        let run = input(
            &root,
            json!({"tool_input": {"command": "cargo test"}, "tool_response": {"stdout": "ok"}}),
        );
        handle("tool-failed", &run);
        match server
            .requests
            .recv_timeout(Duration::from_secs(5))
            .unwrap()
        {
            Request::Test(run) => {
                assert_eq!(run.command, "cargo test");
                assert!(!run.passed);
            }
            other => panic!("{other:?}"),
        }
    }
}