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