1use 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
14const MAX_OUTPUT: usize = 20_000;
16const LABEL_LENGTH: usize = 60;
17const ASKED_LENGTH: usize = 120;
19const AGENT_KEY: &str = "cellix_agent";
21pub const HELD_VAR: &str = "CELLIX_HELD";
23pub const SIDE_QUESTION_VAR: &str = "CELLIX_SIDE_QUESTION";
27
28pub fn side_question() -> bool {
30 std::env::var_os(SIDE_QUESTION_VAR).is_some_and(|v| !v.is_empty())
31}
32
33#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
36pub struct Resumable {
37 pub agent: String,
39 pub session: String,
41 #[serde(default, skip_serializing_if = "String::is_empty")]
43 pub transcript: String,
44}
45
46pub fn remember(held: &Path, agent: &str, session: &str, transcript: &str) {
49 if session.is_empty() || !held.extension().is_some_and(|e| e == "sock") {
50 return;
51 }
52 let word = Resumable {
53 agent: agent.to_string(),
54 session: session.to_string(),
55 transcript: transcript.to_string(),
56 };
57 let path = held.with_extension("agent");
58 let known = std::fs::read(&path)
59 .ok()
60 .and_then(|bytes| serde_json::from_slice::<Resumable>(&bytes).ok());
61 if known.as_ref() == Some(&word) {
62 return;
63 }
64 if let Ok(json) = serde_json::to_vec(&word) {
65 let _ = std::fs::write(path, json);
66 }
67}
68pub const PLAN_WAITING: &str = "Plan waiting for review";
70const CHECKPOINT_WAIT: Duration = Duration::from_secs(3);
74
75const TEST_COMMANDS: [&str; 13] = [
77 "cargo test",
78 "cargo nextest",
79 "pytest",
80 "npm test",
81 "npm run test",
82 "pnpm test",
83 "yarn test",
84 "vitest",
85 "jest",
86 "go test",
87 "rspec",
88 "make test",
89 "harness/x",
90];
91
92pub fn is_test_command(command: &str) -> bool {
93 TEST_COMMANDS.iter().any(|c| command.contains(c))
94}
95
96fn roots(input: &Value) -> Vec<PathBuf> {
98 let cwd = input["cwd"]
99 .as_str()
100 .map(PathBuf::from)
101 .or_else(|| std::env::current_dir().ok())
102 .unwrap_or_default();
103 workspaces(&cwd)
104}
105
106pub fn workspaces(folder: &std::path::Path) -> Vec<PathBuf> {
108 let cwd = dunce::canonicalize(folder).unwrap_or_else(|_| folder.to_path_buf());
109 let mut roots = vec![cwd.clone()];
110 let top = Command::new("git")
111 .arg("-C")
112 .arg(&cwd)
113 .args(["rev-parse", "--show-toplevel"])
114 .output();
115 if let Ok(output) = top
116 && output.status.success()
117 {
118 let text = String::from_utf8_lossy(&output.stdout);
119 let top = PathBuf::from(text.trim());
120 let top = if cfg!(windows) {
122 dunce::canonicalize(&top).unwrap_or(top)
123 } else {
124 top
125 };
126 roots.push(top);
127 }
128 roots
129}
130
131fn ask(roots: &[PathBuf], line: &str) -> Option<String> {
132 roots.iter().find_map(|root| request(root, line).ok())
133}
134
135fn session_of(input: &Value) -> String {
137 input["session_id"].as_str().unwrap_or("").to_string()
138}
139
140fn agent_of(input: &Value) -> String {
142 input[AGENT_KEY]
143 .as_str()
144 .unwrap_or("Claude Code")
145 .to_string()
146}
147
148fn task_root(roots: &[PathBuf]) -> Option<PathBuf> {
151 roots
152 .iter()
153 .find(|r| socket_path(r).exists())
154 .or_else(|| roots.get(1))
155 .or_else(|| roots.first().filter(|r| r.join(".git").exists()))
156 .cloned()
157}
158
159fn log(roots: &[PathBuf], event: &Event) {
161 if let Some(root) = task_root(roots) {
162 let _ = tasks::record(&root, event);
163 }
164}
165
166fn tell(roots: &[PathBuf], input: &Value, state: AgentState, detail: &str) {
167 tell_asked(roots, input, state, detail, String::new());
168}
169
170fn tell_asked(roots: &[PathBuf], input: &Value, state: AgentState, detail: &str, asked: String) {
172 let event = AgentEvent {
173 session: session_of(input),
174 agent: agent_of(input),
175 state,
176 detail: detail.to_string(),
177 folder: roots
178 .first()
179 .map(|r| r.display().to_string())
180 .unwrap_or_default(),
181 pid: agent_pid(),
182 transcript: input["transcript_path"].as_str().unwrap_or("").to_string(),
183 name: std::env::var(crate::team::NAME_VAR).unwrap_or_default(),
186 prompt: asked,
187 };
188 if let Ok(json) = serde_json::to_string(&event) {
189 ask(roots, &format!("event {json}"));
190 }
191}
192
193#[cfg(unix)]
196fn agent_pid() -> Option<u32> {
197 let parent = std::os::unix::process::parent_id();
198 let (above, name) = process_of(parent)?;
199 let shell = ["sh", "bash", "zsh", "dash", "fish", "ksh"];
200 let name = name
201 .rsplit('/')
202 .next()
203 .unwrap_or(&name)
204 .trim_start_matches('-');
205 Some(if shell.contains(&name) { above } else { parent })
206}
207
208#[cfg(not(unix))]
209fn agent_pid() -> Option<u32> {
210 None
211}
212
213fn is_held_program(held: &Path) -> bool {
217 let child = std::fs::read_to_string(held.with_extension("pid"))
218 .ok()
219 .and_then(|text| text.trim().parse().ok());
220 #[cfg(unix)]
221 let parent_of = |pid| process_of(pid).map(|(parent, _)| parent);
222 #[cfg(not(unix))]
223 let parent_of = |_| None;
224 held_program(child, agent_pid(), parent_of)
225}
226
227fn held_program(
232 child: Option<u32>,
233 agent: Option<u32>,
234 parent_of: impl Fn(u32) -> Option<u32>,
235) -> bool {
236 let (Some(child), Some(agent)) = (child, agent) else {
237 return true;
238 };
239 agent == child || parent_of(agent) == Some(child)
240}
241
242#[cfg(unix)]
244fn process_of(pid: u32) -> Option<(u32, String)> {
245 if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) {
246 let (head, rest) = stat.rsplit_once(')')?;
248 let name = head.split_once('(')?.1.to_string();
249 let ppid = rest.split_whitespace().nth(1)?.parse().ok()?;
250 return Some((ppid, name));
251 }
252 let output = Command::new("ps")
253 .args(["-o", "ppid=,comm=", "-p", &pid.to_string()])
254 .output()
255 .ok()?;
256 let text = String::from_utf8_lossy(&output.stdout);
257 let (ppid, name) = text.trim().split_once(char::is_whitespace)?;
258 Some((ppid.trim().parse().ok()?, name.trim().to_string()))
259}
260
261fn asks(input: &Value) -> bool {
267 match input["notification_type"].as_str() {
268 Some(kind) => {
269 let kind = kind.to_lowercase();
270 kind.contains("permission")
271 || kind == "agent_needs_input"
272 || (kind.starts_with("elicitation") && kind.ends_with("dialog"))
273 }
274 None => {
275 let message = input["message"].as_str().unwrap_or("").to_lowercase();
276 !message.contains("waiting for your input")
277 }
278 }
279}
280
281fn idles(input: &Value) -> bool {
284 matches!(
285 input["notification_type"].as_str(),
286 Some("idle_prompt" | "agent_completed" | "agent_idle")
287 )
288}
289
290fn takes_context(agent: &str) -> bool {
293 matches!(agent, "Claude Code" | "Codex" | "Gemini")
294}
295
296fn as_claude_says(input: &mut Value) {
301 let first = |input: &Value, keys: &[&str]| {
302 keys.iter()
303 .find_map(|key| input[*key].as_str().filter(|v| !v.is_empty()))
304 .map(str::to_string)
305 };
306 if input["session_id"].as_str().is_none_or(str::is_empty)
307 && let Some(id) = first(input, &["conversation_id", "sessionId"])
308 {
309 input["session_id"] = json!(id);
310 }
311 if input["cwd"].as_str().is_none_or(str::is_empty)
312 && let Some(folder) = input["workspace_roots"][0].as_str().map(str::to_string)
313 {
314 input["cwd"] = json!(folder);
315 }
316 if input["transcript_path"].as_str().is_none_or(str::is_empty)
317 && let Some(path) = first(input, &["transcriptPath"])
318 {
319 input["transcript_path"] = json!(path);
320 }
321 if input["tool_response"].is_null() {
322 let said = ["tool_result", "toolResult", "tool_output"]
323 .iter()
324 .map(|key| &input[*key])
325 .find(|value| !value.is_null())
326 .cloned();
327 if let Some(said) = said {
328 input["tool_response"] = said;
329 }
330 }
331 if input["tool_input"].is_null() && !input["toolArgs"].is_null() {
332 input["tool_input"] = input["toolArgs"].clone();
333 }
334}
335
336fn failure_words(input: &Value) -> String {
338 let reason = ["error_type", "error", "reason", "message"]
339 .iter()
340 .find_map(|field| input[*field].as_str().filter(|s| !s.is_empty()));
341 match reason {
342 Some(reason) => format!("Stopped: {}", reason.replace('_', " ")),
343 None => "Stopped on an error".to_string(),
344 }
345}
346
347fn request_words(input: &Value, agent: &str) -> String {
350 if let Some(message) = input["message"].as_str().filter(|m| !m.is_empty()) {
351 return message.to_string();
352 }
353 if let Some(command) = input["tool_input"]["command"].as_str() {
354 return format!("{agent} asks to run {command}");
355 }
356 let tool = input["tool_name"].as_str().filter(|t| !t.is_empty());
357 let on = ["path", "file_path"]
359 .iter()
360 .find_map(|key| input["tool_input"][*key].as_str())
361 .or_else(|| input["permission"]["paths"][0].as_str())
362 .filter(|on| !on.is_empty());
363 match (tool, on) {
364 (Some(tool), Some(on)) => format!("{agent} asks to use {tool} on {on}"),
365 (Some(tool), None) => format!("{agent} asks to use {tool}"),
366 _ => "Needs your attention".to_string(),
367 }
368}
369
370pub fn with_prompt(stdin: &str, prompt: Option<&str>) -> String {
374 let (Some(prompt), Ok(mut input)) = (prompt, serde_json::from_str::<Value>(stdin)) else {
375 return stdin.to_string();
376 };
377 if !input.is_object() || input["prompt"].as_str().is_some_and(|p| !p.is_empty()) {
378 return stdin.to_string();
379 }
380 input["prompt"] = json!(prompt);
381 input.to_string()
382}
383
384pub fn comments_message(comments: &[Comment]) -> String {
386 let mut text = String::from("Review comments on your changes:\n");
387 let mut sorted: Vec<&Comment> = comments.iter().collect();
389 sorted.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
390 for comment in sorted {
391 text.push_str(&format!("- {}\n", comment.message()));
392 }
393 text
394}
395
396pub fn asked(prompt: &str) -> String {
399 let line = prompt.lines().map(str::trim).find(|line| !line.is_empty());
400 let Some(line) = line.filter(|line| !line.starts_with('/')) else {
401 return String::new();
402 };
403 let words = line.split_whitespace().collect::<Vec<_>>().join(" ");
404 let mut asked: String = words.chars().take(ASKED_LENGTH).collect();
405 if words.chars().count() > ASKED_LENGTH {
406 asked.push('…');
407 }
408 asked
409}
410
411fn label(prompt: &str) -> String {
412 let line = prompt.lines().next().unwrap_or("Prompt").trim();
413 let mut label: String = line.chars().take(LABEL_LENGTH).collect();
414 if line.chars().count() > LABEL_LENGTH {
415 label.push('…');
416 }
417 label
418}
419
420fn on_prompt(roots: &[PathBuf], input: &Value) -> Option<String> {
421 if let Some(root) = roots.first() {
422 let prompt = input["prompt"].as_str().unwrap_or("Prompt");
423 let event = task_root(roots).map(|log| {
425 let threads = threads::load(&log)
426 .map(|t| threads::next_id(&t) - 1)
427 .unwrap_or(0);
428 let event = Event::Prompt {
429 at: tasks::now(),
430 session: session_of(input),
431 agent: agent_of(input),
432 text: tasks::clip_prompt(prompt),
433 commit: None,
434 threads,
435 };
436 (log, event)
437 });
438 checkpoint_briefly(root, &label(prompt), event);
439 }
440 let prompt = input["prompt"].as_str().unwrap_or("");
441 tell_asked(roots, input, AgentState::Working, "Working", asked(prompt));
442 if !takes_context(&agent_of(input)) {
443 return None;
444 }
445 let prompt = input["prompt"].as_str().unwrap_or("");
449 let key = crate::prompt_key(prompt);
450 if ask(roots, &format!("alone {key:016x}")).as_deref() == Some("yes") {
451 return None;
452 }
453 let comments: Vec<Comment> = ask(roots, "take")
454 .and_then(|reply| serde_json::from_str(&reply).ok())
455 .unwrap_or_default();
456 let threads: Vec<Thread> = ask(roots, "take-threads")
457 .and_then(|reply| serde_json::from_str(&reply).ok())
458 .unwrap_or_default();
459 let mut context = String::new();
460 if !comments.is_empty() {
461 context.push_str(&comments_message(&comments));
462 }
463 for thread in &threads {
464 context.push_str(&thread.message());
465 context.push('\n');
466 }
467 if context.is_empty() {
468 return None;
469 }
470 let output = json!({"hookSpecificOutput": {
471 "hookEventName": "UserPromptSubmit",
472 "additionalContext": context,
473 }});
474 Some(output.to_string())
475}
476
477fn checkpoint_briefly(root: &Path, label: &str, prompt: Option<(PathBuf, Event)>) {
480 let exe = std::env::current_exe()
482 .ok()
483 .filter(|exe| exe.file_stem().is_some_and(|stem| stem == "cellix"));
484 let Some(exe) = exe else {
485 let prompt = prompt.as_ref().map(|(log, e)| (log.as_path(), e.clone()));
486 tasks::checkpoint_prompt(root, label, prompt);
487 return;
488 };
489 let mut command = Command::new(exe);
490 command.args(["checkpoint", label]);
491 if let Some((log, event)) = &prompt {
492 command.env(tasks::ROOT_VAR, log).env(
493 tasks::EVENT_VAR,
494 serde_json::to_string(event).unwrap_or_default(),
495 );
496 }
497 command
498 .current_dir(root)
499 .stdin(Stdio::null())
500 .stdout(Stdio::null())
501 .stderr(Stdio::null());
502 #[cfg(unix)]
504 std::os::unix::process::CommandExt::process_group(&mut command, 0);
505 let Ok(mut child) = command.spawn() else {
506 return;
507 };
508 let started = Instant::now();
509 while started.elapsed() < CHECKPOINT_WAIT {
510 if !matches!(child.try_wait(), Ok(None)) {
511 return;
512 }
513 std::thread::sleep(Duration::from_millis(10));
514 }
515}
516
517fn review_plan(roots: &[PathBuf], input: &Value, plan: &str) -> Option<(String, Option<String>)> {
519 let socket = roots.iter().map(|r| socket_path(r)).find(|s| s.exists())?;
520 let session: String = input["session_id"]
521 .as_str()
522 .unwrap_or("session")
523 .chars()
524 .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
525 .collect();
526 let folder = socket.with_extension("").join(session);
528 std::fs::create_dir_all(&folder).ok()?;
529 let path = keep_versions(&folder, plan).ok()?;
530 tell(roots, input, AgentState::NeedsYou, PLAN_WAITING);
531 let file = path.display().to_string();
532 log(
533 roots,
534 &Event::Plan {
535 at: tasks::now(),
536 session: session_of(input),
537 agent: agent_of(input),
538 file: file.clone(),
539 },
540 );
541 let reply = ask(roots, &format!("plan {file}"))?;
542 let (verdict, text) = reply.split_once(' ').unwrap_or((&reply, "null"));
543 let text: Option<String> = serde_json::from_str(text).ok()?;
544 let kept = if verdict == "approve" {
546 put_versions_away(&folder).ok().flatten()
547 } else {
548 None
549 };
550 if matches!(verdict, "approve" | "send-back") {
551 log(
552 roots,
553 &Event::Answer {
554 at: tasks::now(),
555 file,
556 approved: verdict == "approve",
557 note: if verdict == "approve" {
558 String::new()
559 } else {
560 text.clone().unwrap_or_default()
561 },
562 kept: kept.map(|k| k.display().to_string()),
563 },
564 );
565 }
566 Some((verdict.to_string(), text))
567}
568
569pub fn put_versions_away(folder: &Path) -> std::io::Result<Option<PathBuf>> {
573 let plan = folder.join("Plan.md");
574 if !plan.exists() {
575 return Ok(None);
576 }
577 let mut number = 1;
578 while folder.join(format!("Approved {number}")).exists() {
579 number += 1;
580 }
581 let away = folder.join(format!("Approved {number}"));
582 std::fs::create_dir_all(&away)?;
583 let mut version = 1;
584 loop {
585 let name = format!("Plan v{version}.md");
586 if !folder.join(&name).exists() {
587 break;
588 }
589 std::fs::rename(folder.join(&name), away.join(&name))?;
590 version += 1;
591 }
592 std::fs::rename(plan, away.join("Plan.md"))?;
593 Ok(Some(away))
594}
595
596pub fn keep_versions(folder: &Path, plan: &str) -> std::io::Result<PathBuf> {
599 let path = folder.join("Plan.md");
600 if let Ok(old) = std::fs::read_to_string(&path)
601 && old != plan
602 {
603 let mut version = 1;
604 while folder.join(format!("Plan v{version}.md")).exists() {
605 version += 1;
606 }
607 std::fs::write(folder.join(format!("Plan v{version}.md")), old)?;
608 }
609 std::fs::write(&path, plan)?;
610 Ok(path)
611}
612
613fn on_plan(roots: &[PathBuf], input: &Value) -> Option<String> {
615 let plan = input["tool_input"]["plan"].as_str()?;
616 let (verdict, text) = review_plan(roots, input, plan)?;
617 let decision = match (verdict.as_str(), text) {
619 ("send-back", Some(message)) => json!({"behavior": "deny", "message": message}),
620 ("approve", edited) => {
621 let mut plan_input = input["tool_input"].clone();
623 if let Some(edited) = edited {
624 if let (Some(file), Some(config)) = (
627 input["tool_input"]["planFilePath"].as_str(),
628 claude_config(),
629 ) {
630 write_plan_file(Path::new(file), &edited, &config.join("plans"));
631 }
632 plan_input["plan"] = json!(edited);
633 }
634 json!({"behavior": "allow", "updatedInput": plan_input})
635 }
636 _ => return None,
637 };
638 let output = json!({"hookSpecificOutput": {
639 "hookEventName": "PermissionRequest",
640 "decision": decision,
641 }});
642 Some(output.to_string())
643}
644
645fn on_gemini_plan(roots: &[PathBuf], input: &Value) -> Option<String> {
648 let path = PathBuf::from(input["tool_input"]["plan_path"].as_str()?);
649 let path = match input["cwd"].as_str() {
650 Some(folder) => Path::new(folder).join(path),
651 None => path,
652 };
653 if !is_plain_markdown(&path) {
656 return None;
657 }
658 let plan = std::fs::read_to_string(&path).ok()?;
659 let (verdict, text) = review_plan(roots, input, &plan)?;
660 let output = match (verdict.as_str(), text) {
661 ("send-back", Some(reason)) => json!({"decision": "deny", "reason": reason}),
662 ("approve", edited) => {
663 if let Some(edited) = edited {
664 std::fs::write(&path, edited).ok()?;
665 }
666 json!({"decision": "allow"})
667 }
668 _ => return None,
669 };
670 Some(output.to_string())
671}
672
673fn claude_config() -> Option<PathBuf> {
675 std::env::var_os("CLAUDE_CONFIG_DIR")
676 .map(PathBuf::from)
677 .or_else(|| {
678 let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
679 Some(PathBuf::from(home).join(".claude"))
680 })
681}
682
683fn is_plain_markdown(path: &Path) -> bool {
685 path.extension().is_some_and(|e| e == "md")
686 && std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_file())
687}
688
689fn write_plan_file(file: &Path, edited: &str, plans: &Path) -> bool {
692 let (Ok(folder), Some(parent)) = (dunce::canonicalize(plans), file.parent()) else {
693 return false;
694 };
695 let inside = dunce::canonicalize(parent).is_ok_and(|parent| parent == folder);
696 inside && is_plain_markdown(file) && std::fs::write(file, edited).is_ok()
697}
698
699fn proposed_plan(message: &str) -> Option<&str> {
701 let (_, rest) = message.split_once("<proposed_plan>")?;
702 let (plan, _) = rest.split_once("</proposed_plan>")?;
703 Some(plan.trim())
704}
705
706fn on_codex_stop(roots: &[PathBuf], input: &Value) -> Option<String> {
711 let plan = proposed_plan(input["last_assistant_message"].as_str()?)?;
712 let (verdict, text) = review_plan(roots, input, plan)?;
713 match (verdict.as_str(), text) {
714 ("send-back", Some(reason)) => {
715 Some(json!({"decision": "block", "reason": reason}).to_string())
716 }
717 ("approve", Some(changed)) if changed.trim() != plan.trim() => {
718 let reason = format!(
719 "The reviewer approved your plan with changes. This is the plan to follow \
720 now; implement it when asked.\n\n{changed}"
721 );
722 Some(json!({"decision": "block", "reason": reason}).to_string())
723 }
724 _ => None,
725 }
726}
727
728fn piped(command: &str) -> bool {
731 let bare = command.replace("||", "");
732 bare.contains('|') && !command.contains("pipefail")
733}
734
735fn reads_as_failed(output: &str) -> bool {
738 let marked = ["FAILED", "failures:", "test result: F", "FAIL "]
739 .iter()
740 .any(|mark| output.contains(mark));
741 marked
742 || output.match_indices(" failed").any(|(at, _)| {
743 let count = output[..at].split_whitespace().next_back().unwrap_or("");
744 count.parse::<u64>().is_ok_and(|n| n > 0)
745 })
746}
747
748fn said_exit(text: &str) -> Option<i64> {
750 let lower = text.to_lowercase();
751 ["exit code: ", "exit code ", "exited with code "]
752 .iter()
753 .find_map(|mark| {
754 let at = lower.find(mark)? + mark.len();
755 let digits: String = lower[at..]
756 .chars()
757 .take_while(|c| c.is_ascii_digit() || *c == '-')
758 .collect();
759 digits.parse().ok()
760 })
761}
762
763fn on_tool(roots: &[PathBuf], input: &Value, passed: bool) {
764 tell(roots, input, AgentState::Working, "Working");
766 let command = input["tool_input"]["command"].as_str().unwrap_or("");
767 if !is_test_command(command) {
768 return;
769 }
770 let unpacked: Option<Value> = input["tool_response"]
772 .as_str()
773 .and_then(|text| serde_json::from_str(text).ok())
774 .filter(Value::is_object);
775 let response = unpacked.as_ref().unwrap_or(&input["tool_response"]);
776 let text = response["stdout"]
777 .as_str()
778 .or_else(|| input["error"].as_str())
779 .or_else(|| response["returnDisplay"].as_str())
780 .or_else(|| response["output"].as_str())
781 .or_else(|| response["llmContent"].as_str())
782 .or_else(|| response["text_result_for_llm"].as_str())
783 .or_else(|| response["textResultForLlm"].as_str())
784 .or_else(|| response.as_str())
785 .unwrap_or("");
786 let status = &response["exit_status"];
789 let exit = response["exit_code"]
790 .as_i64()
791 .or(response["exitCode"].as_i64())
792 .or_else(|| status.as_i64())
793 .or_else(|| status.as_str().and_then(|s| s.trim().parse().ok()))
794 .or_else(|| response["llmContent"].as_str().and_then(said_exit))
795 .or_else(|| said_exit(text));
796 let unsaid = exit.is_none() && agent_of(input) != "Claude Code";
799 let passed = passed
800 && exit.unwrap_or(0) == 0
801 && response["error"].is_null()
802 && !((piped(command) || unsaid) && reads_as_failed(text));
803 let start = text
804 .char_indices()
805 .rev()
806 .nth(MAX_OUTPUT)
807 .map_or(0, |(at, _)| at);
808 log(
809 roots,
810 &Event::Test {
811 at: tasks::now(),
812 session: session_of(input),
813 command: command.to_string(),
814 passed,
815 output: tasks::clip_output(text),
816 },
817 );
818 let run = TestRun {
819 command: command.to_string(),
820 passed,
821 output: text[start..].to_string(),
822 };
823 if let Ok(json) = serde_json::to_string(&run) {
824 ask(roots, &format!("test {json}"));
825 }
826}
827
828pub fn handle(kind: &str, stdin: &str) -> Option<String> {
830 handle_for("Claude Code", kind, stdin)
831}
832
833pub fn handle_for(agent: &str, kind: &str, stdin: &str) -> Option<String> {
835 handle_as(agent, kind, stdin, side_question())
836}
837
838fn handle_as(agent: &str, kind: &str, stdin: &str, side: bool) -> Option<String> {
841 if side {
842 return None;
843 }
844 let mut input: Value = serde_json::from_str(stdin).ok()?;
847 if !input.is_object() {
848 return None;
849 }
850 as_claude_says(&mut input);
851 input[AGENT_KEY] = json!(agent);
852 let roots = roots(&input);
853 if matches!(kind, "session-start" | "prompt")
854 && let Some(held) = std::env::var_os(HELD_VAR)
855 && is_held_program(Path::new(&held))
856 {
857 remember(
858 Path::new(&held),
859 agent,
860 input["session_id"].as_str().unwrap_or(""),
861 input["transcript_path"].as_str().unwrap_or(""),
862 );
863 }
864 match kind {
865 "session-start" => tell(&roots, &input, AgentState::Idle, "Ready"),
866 "prompt" if agent == "Cursor" => {
868 on_prompt(&roots, &input);
869 return Some(json!({"continue": true}).to_string());
870 }
871 "prompt" => return on_prompt(&roots, &input),
872 "working" => tell(&roots, &input, AgentState::Working, "Working"),
874 "plan" if agent == "Gemini" => return on_gemini_plan(&roots, &input),
875 "plan" => return on_plan(&roots, &input),
876 "notify" if asks(&input) => {
877 let detail = request_words(&input, agent);
878 tell(&roots, &input, AgentState::NeedsYou, &detail);
879 }
880 "notify" if idles(&input) => tell(&roots, &input, AgentState::Idle, "Waiting for you"),
882 "notify" => {}
884 "tool-done" => on_tool(&roots, &input, true),
885 "tool-failed" => on_tool(&roots, &input, false),
886 "stop" if input["status"] == "error" => {
888 tell(&roots, &input, AgentState::Idle, &failure_words(&input));
889 }
890 "stop" if input["status"] == "aborted" => {
891 tell(&roots, &input, AgentState::Idle, "Waiting for you");
892 }
893 "stop" => {
894 tell(&roots, &input, AgentState::Idle, "Finished");
895 if agent == "Codex" {
896 return on_codex_stop(&roots, &input);
897 }
898 }
899 "stop-failed" => tell(&roots, &input, AgentState::Idle, &failure_words(&input)),
901 "session-end" => tell(&roots, &input, AgentState::Ended, "Ended"),
902 _ => {}
903 }
904 None
905}
906
907#[cfg(test)]
908mod tests {
909 #[test]
910 fn a_held_agent_leaves_word_of_how_to_resume_it() {
911 let dir = tempfile::tempdir().unwrap();
912 let socket = dir.path().join("1-2.sock");
913 super::remember(&socket, "Claude Code", "abc-123", "/t/abc-123.jsonl");
914 let word: super::Resumable =
915 serde_json::from_slice(&std::fs::read(dir.path().join("1-2.agent")).unwrap()).unwrap();
916 assert_eq!(word.agent, "Claude Code");
917 assert_eq!(word.session, "abc-123");
918 assert_eq!(word.transcript, "/t/abc-123.jsonl");
919 super::remember(&socket, "Claude Code", "def-456", "");
921 let text = std::fs::read_to_string(dir.path().join("1-2.agent")).unwrap();
922 assert!(text.contains("def-456"), "{text}");
923 super::remember(&socket, "Claude Code", "", "");
925 assert!(
926 std::fs::read_to_string(dir.path().join("1-2.agent"))
927 .unwrap()
928 .contains("def-456")
929 );
930 super::remember(&dir.path().join("notes.txt"), "Claude Code", "x", "");
931 assert!(!dir.path().join("notes.agent").exists());
932 }
933
934 use super::*;
935 use crate::{Decision, Request, Server, SharedComments, start};
936 use std::path::Path;
937
938 #[test]
939 fn each_plan_keeps_the_one_before_it() {
940 let dir = tempfile::tempdir().unwrap();
941 keep_versions(dir.path(), "first").unwrap();
942 keep_versions(dir.path(), "first").unwrap();
943 assert!(
944 !dir.path().join("Plan v1.md").exists(),
945 "the same plan again is no version"
946 );
947 keep_versions(dir.path(), "second").unwrap();
948 let path = keep_versions(dir.path(), "third").unwrap();
949 assert_eq!(std::fs::read_to_string(path).unwrap(), "third");
950 let read = |name: &str| std::fs::read_to_string(dir.path().join(name)).unwrap();
951 assert_eq!(read("Plan v1.md"), "first");
952 assert_eq!(read("Plan v2.md"), "second");
953 }
954
955 #[test]
956 fn an_agent_run_by_the_held_agent_leaves_its_resume_alone() {
957 let parents = |pid| match pid {
959 150 => Some(100),
960 300 => Some(250), 250 => Some(150),
962 _ => None,
963 };
964 assert!(held_program(Some(100), Some(100), parents), "the program");
965 assert!(
966 held_program(Some(100), Some(150), parents),
967 "under its shell"
968 );
969 assert!(!held_program(Some(100), Some(300), parents), "one it ran");
970 assert!(
971 held_program(None, Some(300), parents),
972 "an older host says nothing"
973 );
974 if cfg!(not(unix)) {
977 return;
978 }
979 let dir = tempfile::tempdir().unwrap();
980 let held = dir.path().join("1-2.sock");
981 std::fs::write(held.with_extension("pid"), "1").unwrap();
982 assert!(!is_held_program(&held), "this test isn't pid 1's agent");
983 }
984
985 #[test]
986 fn a_pipe_hides_a_failed_test_and_the_output_gives_it_away() {
987 assert!(piped("cargo test | tail"));
988 assert!(!piped("cargo test || true"));
989 assert!(!piped("set -o pipefail; cargo test | tail"));
990 assert!(reads_as_failed("test result: FAILED. 1 passed; 2 failed"));
991 assert!(!reads_as_failed("test result: ok. 9 passed; 0 ignored"));
992 assert!(!reads_as_failed(
993 "test result: ok. 9 passed; 0 failed; 0 ignored"
994 ));
995 assert!(reads_as_failed("Tests: 1 failed, 5 passed, 6 total"));
996 }
997
998 #[test]
999 fn a_failed_run_in_codex_or_gemini_is_not_taken_for_a_pass() {
1000 let dir = tempfile::tempdir().unwrap();
1001 let root = dir.path().canonicalize().unwrap();
1002 let server = start(&root, Arc::default()).unwrap();
1003 let run = |response: Value| {
1004 input(
1005 &root,
1006 json!({"tool_input": {"command": "cargo test"}, "tool_response": response}),
1007 )
1008 };
1009 let codex = json!({"exit_code": 101, "stdout": "error: test failed"}).to_string();
1011 handle_for("Codex", "tool-done", &run(Value::String(codex)));
1012 assert!(!next_test(&server).passed, "Codex's exit code");
1013 let gemini =
1015 json!({"llmContent": "Command: cargo test\nExit Code: 101", "returnDisplay": "…"});
1016 handle_for("Gemini", "tool-done", &run(gemini));
1017 assert!(!next_test(&server).passed, "Gemini's words");
1018 let failing = json!({"output": "test result: FAILED. 3 passed; 1 failed"});
1020 handle_for("Codex", "tool-done", &run(failing));
1021 assert!(!next_test(&server).passed, "the output");
1022 let passing = json!({"output": "test result: ok. 3 passed; 0 failed"});
1023 handle_for("Codex", "tool-done", &run(passing));
1024 assert!(next_test(&server).passed, "a pass still passes");
1025 }
1026 use std::sync::Arc;
1027 use std::time::Duration;
1028
1029 fn input(dir: &Path, extra: Value) -> String {
1030 let mut value = json!({"cwd": dir, "session_id": "s1"});
1031 value
1032 .as_object_mut()
1033 .unwrap()
1034 .extend(extra.as_object().unwrap().clone());
1035 value.to_string()
1036 }
1037
1038 fn comment() -> Comment {
1039 Comment {
1040 file: "a.rs".into(),
1041 line: 3,
1042 text: "why?".into(),
1043 ..Comment::default()
1044 }
1045 }
1046
1047 #[test]
1048 fn comments_reach_an_agent_in_order_with_what_they_are_about() {
1049 let later = Comment {
1050 file: "b.rs".into(),
1051 line: 9,
1052 text: "wall clock is wrong here".into(),
1053 quote: "now = time.time()".into(),
1054 removed: true,
1055 };
1056 let first = Comment {
1057 quote: "fn main() {".into(),
1058 ..comment()
1059 };
1060 let message = comments_message(&[later, first]);
1061 let a = message
1062 .find("a.rs line 3, on \"fn main() {\": why?")
1063 .expect(&message);
1064 let b = message.find("b.rs line 9 (a line your change removed), on \"now = time.time()\"");
1065 assert!(b.is_some_and(|b| b > a), "{message}");
1066 }
1067
1068 #[test]
1069 fn nothing_breaks_with_no_cellix_running() {
1070 let dir = tempfile::tempdir().unwrap();
1071 for kind in ["session-start", "prompt", "notify", "stop", "session-end"] {
1072 assert_eq!(handle(kind, &input(dir.path(), json!({}))), None);
1073 }
1074 let plan = input(dir.path(), json!({"tool_input": {"plan": "# P"}}));
1075 assert_eq!(handle("plan", &plan), None, "Claude Code asks as usual");
1076 assert_eq!(handle("prompt", "not json"), None);
1077 }
1078
1079 #[test]
1080 fn a_hook_with_no_details_asks_nothing_of_a_running_cellix() {
1081 for kind in ["prompt", "plan", "stop"] {
1082 assert_eq!(handle(kind, "not json"), None);
1083 assert_eq!(handle(kind, "[1, 2]"), None);
1084 }
1085 }
1086
1087 #[test]
1088 fn the_next_prompt_carries_pending_comments() {
1089 let dir = tempfile::tempdir().unwrap();
1090 let root = dir.path().canonicalize().unwrap();
1091 let shared: SharedComments = Arc::new(std::sync::Mutex::new(vec![comment()]));
1092 let _server = start(&root, shared.clone()).unwrap();
1093 let hook = input(&root, json!({"prompt": "carry on"}));
1094 let output = handle("prompt", &hook).unwrap();
1095 let parsed: Value = serde_json::from_str(&output).unwrap();
1096 let context = parsed["hookSpecificOutput"]["additionalContext"]
1097 .as_str()
1098 .unwrap();
1099 assert!(context.contains("a.rs line 3: why?"), "{context}");
1100 assert!(shared.lock().unwrap().is_empty(), "delivered once");
1101 assert_eq!(handle("prompt", &hook), None);
1102 }
1103
1104 #[test]
1108 fn under_a_side_question_every_hook_does_nothing() {
1109 let dir = tempfile::tempdir().unwrap();
1110 let root = dir.path().canonicalize().unwrap();
1111 let shared: SharedComments = Arc::new(std::sync::Mutex::new(vec![comment()]));
1112 let server = start(&root, shared.clone()).unwrap();
1113 let kinds = [
1114 "session-start",
1115 "prompt",
1116 "working",
1117 "plan",
1118 "notify",
1119 "tool-done",
1120 "tool-failed",
1121 "stop",
1122 "stop-failed",
1123 "session-end",
1124 ];
1125 for agent in [
1126 "Claude Code",
1127 "Codex",
1128 "Gemini",
1129 "OpenCode",
1130 "Copilot",
1131 "Cursor",
1132 ] {
1133 for kind in kinds {
1134 let hook = input(
1135 &root,
1136 json!({"prompt": "Explain this", "tool_input": {"command": "cargo test", "plan": "# P"},
1137 "notification_type": "permission_prompt"}),
1138 );
1139 assert_eq!(handle_as(agent, kind, &hook, true), None, "{agent} {kind}");
1140 }
1141 }
1142 assert_eq!(shared.lock().unwrap().len(), 1, "no comment was taken");
1143 assert!(
1144 server.requests.try_recv().is_err(),
1145 "Cellix was told something"
1146 );
1147 assert!(!root.join(".cellix").exists(), "nothing was logged");
1148 let hook = input(&root, json!({"prompt": "Explain this"}));
1150 let output = handle_as("Claude Code", "prompt", &hook, false).unwrap();
1151 assert!(output.contains("a.rs line 3: why?"), "{output}");
1152 }
1153
1154 #[test]
1158 fn a_comment_asked_on_its_own_goes_alone() {
1159 let dir = tempfile::tempdir().unwrap();
1160 let root = dir.path().canonicalize().unwrap();
1161 let shared: SharedComments = Arc::new(std::sync::Mutex::new(vec![comment()]));
1162 let server = start(&root, shared.clone()).unwrap();
1163 let alone = "Comment 2 on note.md line 1, about \"ICL\": what is it?";
1164 let answering = std::thread::spawn(move || {
1165 let mut asked = Vec::new();
1166 while let Ok(request) = server.requests.recv_timeout(Duration::from_secs(3)) {
1167 match request {
1168 Request::Alone { key, reply } => {
1169 asked.push(key);
1170 let _ = reply.send(key == crate::prompt_key(alone));
1171 }
1172 Request::TakeThreads(reply) => {
1173 let _ = reply.send("[]".to_string());
1174 }
1175 _ => {}
1176 }
1177 }
1178 asked
1179 });
1180 let spaced = format!(" {}\n", alone.replace(", about", ",\n about"));
1182 let hook = input(&root, json!({ "prompt": spaced }));
1183 assert_eq!(handle("prompt", &hook), None, "nothing else is handed over");
1184 assert_eq!(
1185 shared.lock().unwrap().len(),
1186 1,
1187 "the review's comment waits"
1188 );
1189 let other = input(&root, json!({"prompt": "carry on"}));
1190 let output = handle("prompt", &other).expect("the next prompt carries it");
1191 assert!(output.contains("a.rs line 3: why?"), "{output}");
1192 assert!(shared.lock().unwrap().is_empty());
1193 let asked = answering.join().unwrap();
1194 assert_eq!(asked.len(), 2, "each prompt asked once: {asked:?}");
1195 }
1196
1197 #[test]
1198 fn plan_decision_reaches_the_hook() {
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(&root, json!({"tool_input": {"plan": "# Plan\n"}}));
1203 let waiting = std::thread::spawn(move || handle("plan", &hook));
1204 loop {
1205 match server
1206 .requests
1207 .recv_timeout(Duration::from_secs(5))
1208 .unwrap()
1209 {
1210 Request::Plan { path, reply } => {
1211 assert_eq!(std::fs::read_to_string(path).unwrap(), "# Plan\n");
1212 reply
1213 .send(Decision::SendBack("Split step two".into()))
1214 .unwrap();
1215 break;
1216 }
1217 _ => continue,
1218 }
1219 }
1220 let output = waiting.join().unwrap().unwrap();
1221 let parsed: Value = serde_json::from_str(&output).unwrap();
1222 let answer = &parsed["hookSpecificOutput"];
1223 assert_eq!(answer["hookEventName"], "PermissionRequest");
1224 assert_eq!(answer["decision"]["behavior"], "deny");
1225 assert_eq!(answer["decision"]["message"], "Split step two");
1226 }
1227
1228 #[test]
1229 fn a_plan_after_an_approved_one_starts_at_version_one() {
1230 let dir = tempfile::tempdir().unwrap();
1231 let root = dir.path().canonicalize().unwrap();
1232 let server = start(&root, Arc::default()).unwrap();
1233 let answers = [
1235 ("# One\n", Decision::SendBack("Fewer steps".into())),
1236 ("# One, shorter\n", Decision::Approve(None)),
1237 ("# Two\n", Decision::SendBack("Later".into())),
1238 ];
1239 let mut held = Vec::new();
1240 for (plan, decision) in answers {
1241 let hook = input(&root, json!({"tool_input": {"plan": plan}}));
1242 let waiting = std::thread::spawn(move || handle("plan", &hook));
1243 loop {
1244 if let Request::Plan { path, reply } = server
1245 .requests
1246 .recv_timeout(Duration::from_secs(5))
1247 .unwrap()
1248 {
1249 let versions = (1..)
1250 .map(|v| path.with_file_name(format!("Plan v{v}.md")))
1251 .take_while(|p| p.exists())
1252 .count();
1253 held.push((path, versions));
1254 reply.send(decision).unwrap();
1255 break;
1256 }
1257 }
1258 waiting.join().unwrap();
1259 }
1260 assert_eq!(held[1].1, 1, "sent back, so the second is version 2");
1261 assert_eq!(held[2].1, 0, "after approval, a new plan is version 1");
1262 let away = held[2].0.with_file_name("Approved 1");
1263 let read = |name: &str| std::fs::read_to_string(away.join(name)).unwrap();
1264 assert_eq!(
1265 read("Plan.md"),
1266 "# One, shorter\n",
1267 "the approved plan is put away"
1268 );
1269 assert_eq!(read("Plan v1.md"), "# One\n");
1270 }
1271
1272 fn answered(
1274 agent: &'static str,
1275 kind: &'static str,
1276 hook: String,
1277 decision: Decision,
1278 ) -> (Option<String>, String) {
1279 let root = hook_root(&hook);
1280 let server = start(&root, Arc::default()).unwrap();
1281 let waiting = std::thread::spawn(move || handle_for(agent, kind, &hook));
1282 loop {
1283 if let Request::Plan { path, reply } = server
1284 .requests
1285 .recv_timeout(Duration::from_secs(5))
1286 .unwrap()
1287 {
1288 let held = std::fs::read_to_string(path).unwrap();
1289 reply.send(decision).unwrap();
1290 return (waiting.join().unwrap(), held);
1291 }
1292 }
1293 }
1294
1295 fn hook_root(hook: &str) -> PathBuf {
1296 let parsed: Value = serde_json::from_str(hook).unwrap();
1297 PathBuf::from(parsed["cwd"].as_str().unwrap())
1298 }
1299
1300 fn gemini_plan(root: &Path, text: &str) -> String {
1301 let plan = root.join("plan.md");
1302 std::fs::write(&plan, text).unwrap();
1303 input(root, json!({"tool_input": {"plan_path": plan}}))
1304 }
1305
1306 #[test]
1307 fn gemini_is_held_at_leaving_plan_mode_and_told_what_to_change() {
1308 let dir = tempfile::tempdir().unwrap();
1309 let root = dir.path().canonicalize().unwrap();
1310 let hook = gemini_plan(&root, "# G\n");
1311 let sent = Decision::SendBack("Fewer steps".into());
1312 let (output, held) = answered("Gemini", "plan", hook, sent);
1313 assert_eq!(held, "# G\n");
1314 let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
1315 assert_eq!(parsed["decision"], "deny");
1316 assert_eq!(parsed["reason"], "Fewer steps");
1317 }
1318
1319 #[test]
1320 fn an_edit_to_geminis_plan_goes_back_in_its_file() {
1321 let dir = tempfile::tempdir().unwrap();
1322 let root = dir.path().canonicalize().unwrap();
1323 let hook = gemini_plan(&root, "# Old\n");
1324 let edited = Decision::Approve(Some("# New\n".into()));
1325 let (output, _) = answered("Gemini", "plan", hook, edited);
1326 let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
1327 assert_eq!(parsed["decision"], "allow");
1328 assert_eq!(
1329 std::fs::read_to_string(root.join("plan.md")).unwrap(),
1330 "# New\n"
1331 );
1332 }
1333
1334 #[test]
1335 fn a_plan_from_codex_is_held_when_its_turn_ends() {
1336 let dir = tempfile::tempdir().unwrap();
1337 let root = dir.path().canonicalize().unwrap();
1338 let message = "Here it is.\n\n<proposed_plan>\n# C\n</proposed_plan>\n";
1339 let hook = input(&root, json!({"last_assistant_message": message}));
1340 let sent = Decision::SendBack("Say why".into());
1341 let (output, held) = answered("Codex", "stop", hook, sent);
1342 assert_eq!(held, "# C");
1343 let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
1344 assert_eq!(parsed["decision"], "block");
1345 assert_eq!(parsed["reason"], "Say why");
1346 }
1347
1348 #[test]
1349 fn approving_a_codex_plan_with_changes_hands_them_over() {
1350 let dir = tempfile::tempdir().unwrap();
1351 let root = dir.path().canonicalize().unwrap();
1352 let message = "<proposed_plan>\n# C\n</proposed_plan>";
1353 let hook = input(&root, json!({"last_assistant_message": message}));
1354 let changed = "# C\n\n## Reviewer notes\n- Keep the old API.".to_string();
1355 let (output, _) = answered("Codex", "stop", hook, Decision::Approve(Some(changed)));
1356 let parsed: Value = serde_json::from_str(&output.unwrap()).unwrap();
1357 assert_eq!(parsed["decision"], "block");
1358 assert!(
1359 parsed["reason"]
1360 .as_str()
1361 .unwrap()
1362 .contains("Keep the old API.")
1363 );
1364 }
1365
1366 #[test]
1367 fn approving_a_codex_plan_lets_its_turn_end() {
1368 let dir = tempfile::tempdir().unwrap();
1369 let root = dir.path().canonicalize().unwrap();
1370 let message = "<proposed_plan>\n# C\n</proposed_plan>";
1371 let hook = input(&root, json!({"last_assistant_message": message}));
1372 let (output, _) = answered("Codex", "stop", hook, Decision::Approve(None));
1373 assert_eq!(output, None);
1374 }
1375
1376 #[test]
1377 fn an_ordinary_codex_turn_isnt_held() {
1378 assert_eq!(proposed_plan("Done, the tests pass."), None);
1379 assert_eq!(proposed_plan("<proposed_plan>cut off"), None);
1380 let dir = tempfile::tempdir().unwrap();
1381 let root = dir.path().canonicalize().unwrap();
1382 let _server = start(&root, Arc::default()).unwrap();
1383 let hook = input(&root, json!({"last_assistant_message": "All done."}));
1384 assert_eq!(handle_for("Codex", "stop", &hook), None);
1385 }
1386
1387 #[test]
1388 fn plan_hooks_are_given_time_for_a_person_to_read() {
1389 let hooks = |text: &str| serde_json::from_str::<Value>(text).unwrap();
1390 let gemini = hooks(include_str!(
1391 "../../cellix/integrations/gemini/hooks/hooks.json"
1392 ));
1393 let before = &gemini["hooks"]["BeforeTool"][0];
1394 assert_eq!(before["matcher"], "exit_plan_mode");
1395 assert_eq!(
1396 before["hooks"][0]["timeout"], 86_400_000,
1397 "Gemini counts milliseconds"
1398 );
1399 let codex = hooks(include_str!(
1400 "../../cellix/integrations/codex/hooks/hooks.json"
1401 ));
1402 assert_eq!(codex["hooks"]["Stop"][0]["hooks"][0]["timeout"], 86_400);
1403 }
1404
1405 #[test]
1406 fn an_edited_plan_is_written_only_to_claude_codes_own_plan_file() {
1407 let dir = tempfile::tempdir().unwrap();
1408 let plans = dir.path().join(".claude/plans");
1409 std::fs::create_dir_all(&plans).unwrap();
1410 let plan = plans.join("refunds.md");
1411 std::fs::write(&plan, "# Old").unwrap();
1412 assert!(write_plan_file(&plan, "# New", &plans));
1413 assert_eq!(std::fs::read_to_string(&plan).unwrap(), "# New");
1414 let settings = dir.path().join(".claude/settings.json");
1416 std::fs::write(&settings, "{}").unwrap();
1417 assert!(!write_plan_file(&settings, "# New", &plans));
1418 assert!(!write_plan_file(
1419 &plans.join("../settings.json"),
1420 "x",
1421 &plans
1422 ));
1423 assert!(!write_plan_file(&plans.join("new.md"), "x", &plans));
1424 assert!(!plans.join("new.md").exists());
1425 assert_eq!(std::fs::read_to_string(&settings).unwrap(), "{}");
1426 assert!(is_plain_markdown(&plan));
1428 assert!(!is_plain_markdown(&settings));
1429 #[cfg(unix)]
1430 {
1431 let link = plans.join("link.md");
1432 std::os::unix::fs::symlink(&settings, &link).unwrap();
1433 assert!(!is_plain_markdown(&link));
1434 assert!(!write_plan_file(&link, "x", &plans));
1435 }
1436 }
1437
1438 #[test]
1439 fn an_edited_plan_is_approved_as_edited() {
1440 let dir = tempfile::tempdir().unwrap();
1441 let root = dir.path().canonicalize().unwrap();
1442 let server = start(&root, Arc::default()).unwrap();
1443 let hook = input(
1444 &root,
1445 json!({"tool_input": {"plan": "# Old", "planFilePath": "/p.md"}}),
1446 );
1447 let waiting = std::thread::spawn(move || handle("plan", &hook));
1448 loop {
1449 if let Request::Plan { reply, .. } = server
1450 .requests
1451 .recv_timeout(Duration::from_secs(5))
1452 .unwrap()
1453 {
1454 reply.send(Decision::Approve(Some("# New".into()))).unwrap();
1455 break;
1456 }
1457 }
1458 let output = waiting.join().unwrap().unwrap();
1459 let parsed: Value = serde_json::from_str(&output).unwrap();
1460 let answer = &parsed["hookSpecificOutput"]["decision"];
1461 assert_eq!(answer["behavior"], "allow");
1462 assert_eq!(answer["updatedInput"]["plan"], "# New");
1463 assert_eq!(answer["updatedInput"]["planFilePath"], "/p.md");
1464 }
1465
1466 #[test]
1467 fn events_carry_the_agents_name() {
1468 let dir = tempfile::tempdir().unwrap();
1469 let root = dir.path().canonicalize().unwrap();
1470 let server = start(&root, Arc::default()).unwrap();
1471 handle_for("Codex", "session-start", &input(&root, json!({})));
1472 match server
1473 .requests
1474 .recv_timeout(Duration::from_secs(5))
1475 .unwrap()
1476 {
1477 Request::Agent(event) => assert_eq!(event.agent, "Codex"),
1478 other => panic!("{other:?}"),
1479 }
1480 }
1481
1482 #[test]
1485 fn a_prompt_tells_cellix_what_was_asked() {
1486 let dir = tempfile::tempdir().unwrap();
1487 let root = dir.path().canonicalize().unwrap();
1488 let server = start(&root, Arc::default()).unwrap();
1489 let asked_of = |prompt: &str| {
1490 handle_for("Codex", "prompt", &input(&root, json!({"prompt": prompt})));
1491 loop {
1492 match server
1493 .requests
1494 .recv_timeout(Duration::from_secs(5))
1495 .unwrap()
1496 {
1497 Request::Agent(event) => return event,
1498 _ => continue,
1499 }
1500 }
1501 };
1502 let event = asked_of("\n Fix the login redirect\nand its test");
1503 assert_eq!(event.state, AgentState::Working);
1504 assert_eq!(event.prompt, "Fix the login redirect");
1505 assert_eq!(asked_of("/clear").prompt, "", "a command names nothing");
1506 let long = "word ".repeat(40);
1507 let cut = asked_of(&long).prompt;
1508 assert_eq!(cut.chars().count(), ASKED_LENGTH + 1, "{cut}");
1509 assert!(cut.ends_with('…'));
1510 handle_for("Codex", "stop", &input(&root, json!({})));
1512 let stop = loop {
1513 match server
1514 .requests
1515 .recv_timeout(Duration::from_secs(5))
1516 .unwrap()
1517 {
1518 Request::Agent(event) => break event,
1519 _ => continue,
1520 }
1521 };
1522 assert_eq!(stop.prompt, "");
1523 }
1524
1525 #[test]
1526 fn a_failed_command_is_read_from_the_result() {
1527 let dir = tempfile::tempdir().unwrap();
1528 let root = dir.path().canonicalize().unwrap();
1529 let server = start(&root, Arc::default()).unwrap();
1530 let run = input(
1531 &root,
1532 json!({"tool_input": {"command": "cargo test"},
1533 "tool_response": {"returnDisplay": "boom", "error": "exit 1"}}),
1534 );
1535 handle_for("Gemini", "tool-done", &run);
1536 let run = next_test(&server);
1537 assert!(!run.passed);
1538 assert_eq!(run.output, "boom");
1539 }
1540
1541 #[test]
1542 fn test_runs_are_reported_and_other_commands_are_not() {
1543 let dir = tempfile::tempdir().unwrap();
1544 let root = dir.path().canonicalize().unwrap();
1545 let server = start(&root, Arc::default()).unwrap();
1546 let other = input(&root, json!({"tool_input": {"command": "ls"}}));
1547 handle("tool-done", &other);
1548 let run = input(
1549 &root,
1550 json!({"tool_input": {"command": "cargo test"}, "tool_response": {"stdout": "ok"}}),
1551 );
1552 handle("tool-failed", &run);
1553 let run = next_test(&server);
1555 assert_eq!(run.command, "cargo test");
1556 assert!(!run.passed);
1557 }
1558
1559 fn next_test(server: &Server) -> TestRun {
1561 loop {
1562 match server
1563 .requests
1564 .recv_timeout(Duration::from_secs(5))
1565 .unwrap()
1566 {
1567 Request::Test(run) => return run,
1568 Request::Agent(event) => assert_eq!(event.state, AgentState::Working),
1569 other => panic!("{other:?}"),
1570 }
1571 }
1572 }
1573
1574 fn next_event(server: &Server, wait: Duration) -> Option<AgentEvent> {
1576 match server.requests.recv_timeout(wait) {
1577 Ok(Request::Agent(event)) => Some(event),
1578 Ok(other) => panic!("{other:?}"),
1579 Err(_) => None,
1580 }
1581 }
1582
1583 #[test]
1584 fn only_a_request_counts_as_needing_you() {
1585 let dir = tempfile::tempdir().unwrap();
1586 let root = dir.path().canonicalize().unwrap();
1587 let server = start(&root, Arc::default()).unwrap();
1588 let idle = "Claude is waiting for your input";
1591 handle(
1592 "notify",
1593 &input(
1594 &root,
1595 json!({"notification_type": "idle_prompt", "message": idle}),
1596 ),
1597 );
1598 let event = next_event(&server, Duration::from_secs(5)).unwrap();
1599 assert_eq!(
1600 (event.state, event.detail.as_str()),
1601 (AgentState::Idle, "Waiting for you")
1602 );
1603 handle("notify", &input(&root, json!({"message": idle})));
1606 for kind in [
1607 "auth_success",
1608 "elicitation_complete",
1609 "elicitation_response",
1610 ] {
1611 handle(
1612 "notify",
1613 &input(&root, json!({"notification_type": kind, "message": "Done"})),
1614 );
1615 }
1616 let asking = "Claude needs your permission to use Bash";
1618 handle(
1619 "notify",
1620 &input(
1621 &root,
1622 json!({"notification_type": "permission_prompt", "message": asking}),
1623 ),
1624 );
1625 let event = next_event(&server, Duration::from_secs(5)).unwrap();
1626 assert_eq!(
1627 (event.state, event.detail.as_str()),
1628 (AgentState::NeedsYou, asking)
1629 );
1630 let codex = input(
1632 &root,
1633 json!({"tool_name": "Bash", "tool_input": {"command": "cargo publish"}}),
1634 );
1635 handle_for("Codex", "notify", &codex);
1636 let event = next_event(&server, Duration::from_secs(5)).unwrap();
1637 assert_eq!(event.state, AgentState::NeedsYou);
1638 assert_eq!(event.detail, "Codex asks to run cargo publish");
1639 let gemini = input(
1641 &root,
1642 json!({"notification_type": "ToolPermission", "message": "Allow rm?"}),
1643 );
1644 handle_for("Gemini", "notify", &gemini);
1645 assert_eq!(
1646 next_event(&server, Duration::from_secs(5)).unwrap().state,
1647 AgentState::NeedsYou
1648 );
1649 assert_eq!(next_event(&server, Duration::from_millis(300)), None);
1650 }
1651
1652 #[test]
1653 fn a_turn_the_api_cut_short_is_not_left_working() {
1654 let dir = tempfile::tempdir().unwrap();
1655 let root = dir.path().canonicalize().unwrap();
1656 let server = start(&root, Arc::default()).unwrap();
1657 handle(
1659 "stop-failed",
1660 &input(&root, json!({"error_type": "rate_limit"})),
1661 );
1662 let event = next_event(&server, Duration::from_secs(5)).unwrap();
1663 assert_eq!(
1664 (event.state, event.detail.as_str()),
1665 (AgentState::Idle, "Stopped: rate limit")
1666 );
1667 let asking = json!({"notification_type": "elicitation_dialog", "message": "Which port?"});
1669 handle("notify", &input(&root, asking));
1670 let event = next_event(&server, Duration::from_secs(5)).unwrap();
1671 assert_eq!(event.state, AgentState::NeedsYou);
1672 }
1673
1674 #[test]
1675 fn a_tool_that_ran_means_the_request_was_answered() {
1676 let dir = tempfile::tempdir().unwrap();
1677 let root = dir.path().canonicalize().unwrap();
1678 let server = start(&root, Arc::default()).unwrap();
1679 let asking = json!({"notification_type": "permission_prompt", "message": "Claude needs your permission to use Edit"});
1680 handle("notify", &input(&root, asking));
1681 let event = next_event(&server, Duration::from_secs(5)).unwrap();
1682 assert_eq!(event.state, AgentState::NeedsYou);
1683 assert_eq!(event.pid.is_some(), cfg!(unix));
1685 let edited = json!({"tool_name": "Edit", "tool_input": {"file_path": "notes.txt"}});
1687 handle("tool-done", &input(&root, edited));
1688 let event = next_event(&server, Duration::from_secs(5)).unwrap();
1689 assert_eq!(event.state, AgentState::Working);
1690 }
1691
1692 #[test]
1693 fn an_agents_work_is_logged_for_the_task_view() {
1694 let dir = tempfile::tempdir().unwrap();
1695 let root = dir.path().canonicalize().unwrap();
1696 let git = |args: &[&str]| {
1697 let status = Command::new("git").arg("-C").arg(&root).args(args).status();
1698 assert!(status.unwrap().success());
1699 };
1700 git(&["init", "-q"]);
1701 std::fs::write(root.join("a.rs"), "fn a() {}\n").unwrap();
1702 git(&["add", "."]);
1703 git(&[
1704 "-c",
1705 "user.name=T",
1706 "-c",
1707 "user.email=t@example.com",
1708 "commit",
1709 "-qm",
1710 "a",
1711 ]);
1712 let server = start(&root, Arc::default()).unwrap();
1713 handle(
1714 "prompt",
1715 &input(&root, json!({"prompt": "Add a refund route"})),
1716 );
1717 for decision in [
1719 Decision::SendBack("Only paid orders".into()),
1720 Decision::Approve(None),
1721 ] {
1722 let hook = input(&root, json!({"tool_input": {"plan": "# Refunds\n"}}));
1723 let waiting = std::thread::spawn(move || handle("plan", &hook));
1724 loop {
1725 let request = server
1726 .requests
1727 .recv_timeout(Duration::from_secs(5))
1728 .unwrap();
1729 if let Request::Plan { reply, .. } = request {
1730 reply.send(decision).unwrap();
1731 break;
1732 }
1733 }
1734 waiting.join().unwrap();
1735 }
1736 let run = input(
1737 &root,
1738 json!({"tool_input": {"command": "cargo test"}, "tool_response": {"stdout": "FAILED"}}),
1739 );
1740 handle("tool-failed", &run);
1741
1742 let events = tasks::load(&root);
1743 let found = tasks::tasks(&events, |_| None);
1744 assert_eq!(found.len(), 1, "{events:?}");
1745 let task = &found[0];
1746 assert_eq!(
1747 (task.name.as_str(), task.agent.as_str()),
1748 ("Add a refund route", "Claude Code")
1749 );
1750 let turn = task.turns().next().unwrap();
1751 assert!(
1752 turn.commit.is_some(),
1753 "the prompt is logged with its checkpoint"
1754 );
1755 assert_eq!(turn.tests.len(), 1);
1756 assert!(!turn.tests[0].passed);
1757 let outcomes: Vec<&tasks::Outcome> = task.plans().map(|p| &p.outcome).collect();
1758 assert_eq!(
1759 outcomes[0],
1760 &tasks::Outcome::SentBack("Only paid orders".into())
1761 );
1762 assert!(matches!(outcomes[1], tasks::Outcome::Approved(Some(_))));
1763 let ignore = std::fs::read_to_string(root.join(".cellix/.gitignore")).unwrap();
1765 assert!(ignore.contains("tasks.jsonl"));
1766 }
1767
1768 #[test]
1771 fn opencode_copilot_and_cursor_report_through_the_same_hooks() {
1772 use AgentState::{Idle, NeedsYou, Working};
1773 let dir = tempfile::tempdir().unwrap();
1774 let root = dir.path().canonicalize().unwrap();
1775 let shared: SharedComments = Arc::default();
1776 let server = start(&root, shared.clone()).unwrap();
1777 let news = || {
1778 let event = next_event(&server, Duration::from_secs(5)).unwrap();
1779 (event.agent, event.session, event.state, event.detail)
1780 };
1781 let with = |base: Value, extra: Value| {
1782 let mut value = base;
1783 let fields = extra.as_object().unwrap().clone();
1784 value.as_object_mut().unwrap().extend(fields);
1785 value.to_string()
1786 };
1787
1788 let copilot = |extra| {
1790 let base =
1791 json!({"session_id": "cp-1", "timestamp": "2026-11-17T12:00:00Z", "cwd": root});
1792 with(base, extra)
1793 };
1794 let asking = json!({"hook_event_name": "Notification", "notification_type": "permission_prompt",
1795 "message": "Allow cargo publish?"});
1796 handle_for("Copilot", "notify", &copilot(asking));
1797 let asked = (
1798 "Copilot".into(),
1799 "cp-1".into(),
1800 NeedsYou,
1801 "Allow cargo publish?".into(),
1802 );
1803 assert_eq!(news(), asked);
1804 let idle = json!({"hook_event_name": "Notification", "notification_type": "agent_idle"});
1805 handle_for("Copilot", "notify", &copilot(idle));
1806 assert_eq!(news().2, Idle);
1807 let tool = json!({"hook_event_name": "PostToolUse", "tool_name": "bash",
1808 "tool_input": {"command": "ls"}, "tool_result": {"result_type": "success"}});
1809 handle_for("Copilot", "tool-done", &copilot(tool));
1810 assert_eq!(news().2, Working);
1811 handle_for(
1812 "Copilot",
1813 "stop",
1814 &copilot(json!({"hook_event_name": "Stop", "stop_reason": "end_turn"})),
1815 );
1816 assert_eq!(news().3, "Finished");
1817
1818 let cursor = |extra| {
1821 let base = json!({"conversation_id": "cu-1", "generation_id": "g-1", "model": "x",
1822 "cursor_version": "2.0", "workspace_roots": [root], "user_email": null});
1823 with(base, extra)
1824 };
1825 shared.lock().unwrap().push(comment());
1826 let said = handle_for(
1827 "Cursor",
1828 "prompt",
1829 &cursor(json!({"prompt": "Fix it", "attachments": []})),
1830 );
1831 assert_eq!(said.as_deref(), Some(r#"{"continue":true}"#));
1832 assert_eq!(
1833 news(),
1834 ("Cursor".into(), "cu-1".into(), Working, "Working".into())
1835 );
1836 assert_eq!(shared.lock().unwrap().len(), 1, "the comment waits");
1837 handle_for(
1838 "Cursor",
1839 "stop",
1840 &cursor(json!({"status": "error", "loop_count": 0})),
1841 );
1842 assert_eq!(news().3, "Stopped on an error");
1843 handle_for(
1844 "Cursor",
1845 "stop",
1846 &cursor(json!({"status": "aborted", "loop_count": 0})),
1847 );
1848 assert_eq!(news().3, "Waiting for you");
1849 handle_for(
1850 "Cursor",
1851 "stop",
1852 &cursor(json!({"status": "completed", "loop_count": 0})),
1853 );
1854 assert_eq!(news().3, "Finished");
1855
1856 handle_for(
1858 "OpenCode",
1859 "working",
1860 &input(&root, json!({"session_id": "oc-1"})),
1861 );
1862 assert_eq!(
1863 news(),
1864 ("OpenCode".into(), "oc-1".into(), Working, "Working".into())
1865 );
1866 }
1867
1868 #[test]
1873 fn kiro_reports_through_the_same_hooks() {
1874 use AgentState::{Ended, Idle, NeedsYou, Working};
1875 let dir = tempfile::tempdir().unwrap();
1876 let root = dir.path().canonicalize().unwrap();
1877 let shared: SharedComments = Arc::default();
1878 let server = start(&root, shared.clone()).unwrap();
1879 let news = || {
1880 let event = next_event(&server, Duration::from_secs(5)).unwrap();
1881 assert_eq!(
1882 (event.agent.as_str(), event.session.as_str()),
1883 ("Kiro", "f2946a26")
1884 );
1885 (event.state, event.detail, event.prompt)
1886 };
1887 let kiro = |event: &str, extra: Value| {
1888 let mut value =
1889 json!({"hook_event_name": event, "cwd": root, "session_id": "f2946a26"});
1890 let fields = extra.as_object().unwrap().clone();
1891 value.as_object_mut().unwrap().extend(fields);
1892 value.to_string()
1893 };
1894 let spawned = kiro("agentSpawn", json!({}));
1895 assert_eq!(handle_for("Kiro", "session-start", &spawned), None);
1896 assert_eq!(news().0, Idle);
1897
1898 shared.lock().unwrap().push(comment());
1900 let submitted = kiro("UserPromptSubmit", json!({}));
1901 let prompt = with_prompt(&submitted, Some("Add a refund route"));
1902 assert_eq!(handle_for("Kiro", "prompt", &prompt), None);
1903 let asked = (Working, "Working".into(), "Add a refund route".into());
1904 assert_eq!(news(), asked);
1905 assert_eq!(shared.lock().unwrap().len(), 1, "the comment waits");
1906 let given = kiro("UserPromptSubmit", json!({"prompt": "Keep this"}));
1907 assert!(with_prompt(&given, Some("Not this")).contains("Keep this"));
1908 assert_eq!(with_prompt("not json", Some("x")), "not json");
1909
1910 let run = json!({"tool_name": "execute_bash", "tool_input": {"command": "cargo publish"},
1912 "permission": {"capability": "shell", "command": "cargo publish"}});
1913 handle_for("Kiro", "notify", &kiro("PermissionRequest", run));
1914 let asks = (
1915 NeedsYou,
1916 "Kiro asks to run cargo publish".into(),
1917 String::new(),
1918 );
1919 assert_eq!(news(), asks);
1920 let write = json!({"tool_name": "fs_write", "tool_input": {"content": "…"},
1921 "permission": {"capability": "fs_write", "paths": ["src/orders.rs"]}});
1922 handle_for("Kiro", "notify", &kiro("PermissionRequest", write));
1923 assert_eq!(news().1, "Kiro asks to use fs_write on src/orders.rs");
1924
1925 let starts = kiro("PreToolUse", json!({"tool_name": "execute_bash"}));
1927 handle_for("Kiro", "working", &starts);
1928 assert_eq!(news().0, Working);
1929 let ran = json!({"tool_name": "execute_bash", "tool_input": {"command": "cargo test"},
1930 "tool_response": {"exit_status": "101", "stdout": "error: test failed"}});
1931 handle_for("Kiro", "tool-done", &kiro("PostToolUse", ran));
1932 assert!(!next_test(&server).passed, "its exit status");
1933
1934 handle_for("Kiro", "stop", &kiro("Stop", json!({})));
1935 assert_eq!(news(), (Idle, "Finished".into(), String::new()));
1936 handle_for("Kiro", "session-end", &kiro("SessionEnd", json!({})));
1937 assert_eq!(news().0, Ended);
1938 }
1939}