Cotton code
574 lines · 19.2 KB · RustRaw
//! The adopted-session state machine, on a fake clock and fake transcripts.//!//! Not one of these tests touches a real transcript directory: the fixtures are//! the crate's own, the "files" are a map in memory, and every instant is an//! argument. The reads themselves are `tests/adopted.rs`.use std::collections::{BTreeMap, BTreeSet};use super::*;use crate::protocol::TurnRole;const CLAUDE: &str = include_str!("../tests/fixtures/claude-transcript.jsonl");const CLAUDE_ENDED: &str = include_str!("../tests/fixtures/claude-transcript-ended.jsonl");const CODEX: &str = include_str!("../tests/fixtures/codex-rollout.jsonl");/// The session id the Claude fixture names.const CLAUDE_SESSION: &str = "11111111-2222-3333-4444-555555555555";/// The session id the ended Claude fixture names.const ENDED_SESSION: &str = "22222222-3333-4444-5555-666666666666";/// The session id the Codex fixture names.const CODEX_SESSION: &str = "019a0000-0000-7000-8000-000000000001";/// Transcripts held in memory, keyed by path.#[derive(Default)]struct Fake(BTreeMap<PathBuf, String>);impl Fake {    fn with(path: &str, text: &str) -> Self {        let mut held = BTreeMap::new();        held.insert(PathBuf::from(path), text.to_string());        Self(held)    }    fn put(&mut self, path: &str, text: &str) {        self.0.insert(PathBuf::from(path), text.to_string());    }}impl Transcripts for Fake {    fn head(&self, path: &Path) -> Option<String> {        self.0.get(path).cloned()    }    fn tail(&self, path: &Path) -> Option<String> {        self.0.get(path).cloned()    }}fn found(tool: Tool, path: &str, len: u64, modified: i64) -> Found {    Found {        tool,        path: PathBuf::from(path),        len,        modified,    }}const NOW: &str = "2026-09-18T09:02:00Z";#[test]fn a_transcript_nobody_here_spawned_is_adopted_with_its_own_id_cwd_and_start() {    let mut watcher = Watcher::new();    let files = Fake::with("/p/a.jsonl", CLAUDE);    let (events, run) = watcher.observe(        1_000,        NOW,        &[found(Tool::Claude, "/p/a.jsonl", 900, 1_000)],        &BTreeSet::new(),        &files,    );    assert_eq!(run.adopted, 1);    assert_eq!(run.skipped, 0);    assert!(matches!(        &events[0],        Event::Adopted { session_id, tool, cwd, started_at }            if session_id == CLAUDE_SESSION                && *tool == Tool::Claude                && cwd.as_deref() == Some("/work/repo")                && started_at == "2026-09-18T09:00:00.000Z"    ));    assert!(watcher.holds(CLAUDE_SESSION));}#[test]fn the_first_sight_of_a_live_transcript_says_running_and_what_it_last_said() {    let mut watcher = Watcher::new();    let files = Fake::with("/p/a.jsonl", CLAUDE);    let (events, _) = watcher.observe(        1_000,        NOW,        &[found(Tool::Claude, "/p/a.jsonl", 900, 1_000)],        &BTreeSet::new(),        &files,    );    let turn = events        .iter()        .find_map(|event| match event {            Event::Turn { role, text, seq, .. } => Some((*role, text.clone(), *seq)),            _ => None,        })        .expect("the tail carries a turn");    assert_eq!(turn.0, TurnRole::Assistant);    assert_eq!(        turn.1,        "I added two: one for the bound and one for the replay tail."    );    assert_eq!(turn.2, 1, "the first turn this host saw is seq 1");    assert!(events        .iter()        .any(|event| matches!(event, Event::State { state: SessionState::Running, .. })));}#[test]fn a_transcript_that_has_not_been_written_for_ninety_seconds_is_idle() {    let mut watcher = Watcher::new();    let files = Fake::with("/p/a.jsonl", CLAUDE);    let file = found(Tool::Claude, "/p/a.jsonl", 900, 1_000);    watcher.observe(1_000, NOW, std::slice::from_ref(&file), &BTreeSet::new(), &files);    // One second short of the rule: still running.    let (events, _) = watcher.observe(        1_000 + IDLE_AFTER_SECONDS - 1,        NOW,        std::slice::from_ref(&file),        &BTreeSet::new(),        &files,    );    assert!(events.is_empty(), "nothing changed, so nothing is said");    let (events, _) = watcher.observe(        1_000 + IDLE_AFTER_SECONDS,        NOW,        &[file],        &BTreeSet::new(),        &files,    );    assert!(matches!(        events.as_slice(),        [Event::State {            state: SessionState::Idle,            ..        }]    ));}#[test]fn a_transcript_that_grows_again_goes_back_to_running_with_the_next_turn() {    let mut watcher = Watcher::new();    let mut files = Fake::with("/p/a.jsonl", CLAUDE);    watcher.observe(        1_000,        NOW,        &[found(Tool::Claude, "/p/a.jsonl", 900, 1_000)],        &BTreeSet::new(),        &files,    );    watcher.observe(        2_000,        NOW,        &[found(Tool::Claude, "/p/a.jsonl", 900, 1_000)],        &BTreeSet::new(),        &files,    );    let mut grown = CLAUDE.to_string();    grown.push_str("{\"type\":\"assistant\",\"message\":{\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"And a third.\"}]},\"sessionId\":\"11111111-2222-3333-4444-555555555555\",\"cwd\":\"/work/repo\",\"timestamp\":\"2026-09-18T09:30:00.000Z\"}\n");    files.put("/p/a.jsonl", &grown);    let (events, _) = watcher.observe(        2_010,        NOW,        &[found(Tool::Claude, "/p/a.jsonl", 1_200, 2_010)],        &BTreeSet::new(),        &files,    );    assert!(matches!(        &events[0],        Event::Turn { text, seq: 2, .. } if text == "And a third."    ));    assert!(events        .iter()        .any(|event| matches!(event, Event::State { state: SessionState::Running, .. })));}#[test]fn the_same_tail_read_twice_is_not_a_second_copy_of_the_same_turn() {    let mut watcher = Watcher::new();    let files = Fake::with("/p/a.jsonl", CLAUDE);    watcher.observe(        1_000,        NOW,        &[found(Tool::Claude, "/p/a.jsonl", 900, 1_000)],        &BTreeSet::new(),        &files,    );    // The file was touched but says the same thing.    let (events, _) = watcher.observe(        1_005,        NOW,        &[found(Tool::Claude, "/p/a.jsonl", 900, 1_005)],        &BTreeSet::new(),        &files,    );    assert!(        !events            .iter()            .any(|event| matches!(event, Event::Turn { .. })),        "the turn had already been said"    );}#[test]fn an_end_marker_plus_a_file_that_stopped_changing_is_ended_with_no_exit_code() {    let mut watcher = Watcher::new();    let files = Fake::with("/p/b.jsonl", CLAUDE_ENDED);    let file = found(Tool::Claude, "/p/b.jsonl", 800, 1_000);    watcher.observe(1_010, NOW, std::slice::from_ref(&file), &BTreeSet::new(), &files);    let (events, _) = watcher.observe(1_020, NOW, &[file], &BTreeSet::new(), &files);    assert!(matches!(        events.as_slice(),        [            Event::State {                state: SessionState::Ended,                ..            },            Event::Exited {                code: None,                signal: None,                ..            }        ]    ));    assert!(matches!(&events[1], Event::Exited { session_id, .. } if session_id == ENDED_SESSION));}#[test]fn a_transcript_with_no_end_marker_stays_idle_for_a_whole_day_before_it_ends() {    let mut watcher = Watcher::new();    let files = Fake::with("/p/a.jsonl", CLAUDE);    let file = found(Tool::Claude, "/p/a.jsonl", 900, 1_000);    watcher.observe(1_000, NOW, std::slice::from_ref(&file), &BTreeSet::new(), &files);    // Every reading short of the day: idle, and never an exit. A person at    // lunch, or asleep, is coming back to this session.    for tick in 1..10 {        let (events, _) = watcher.observe(            1_000 + tick * IDLE_AFTER_SECONDS,            NOW,            std::slice::from_ref(&file),            &BTreeSet::new(),            &files,        );        assert!(            !events                .iter()                .any(|event| matches!(event, Event::Exited { .. })),            "this host never reaped a process it does not own"        );    }    let (events, _) = watcher.observe(        1_000 + ENDED_AFTER_SECONDS - 1,        NOW,        std::slice::from_ref(&file),        &BTreeSet::new(),        &files,    );    assert!(events.is_empty(), "one second short of the day is still idle");}#[test]fn a_day_of_silence_with_no_marker_at_all_is_ended_at_the_transcript_s_last_write() {    let mut watcher = Watcher::new();    let files = Fake::with("/p/a.jsonl", CLAUDE);    let file = found(Tool::Claude, "/p/a.jsonl", 900, 1_000);    watcher.observe(1_000, NOW, std::slice::from_ref(&file), &BTreeSet::new(), &files);    let (events, _) = watcher.observe(        1_000 + ENDED_AFTER_SECONDS,        NOW,        &[file],        &BTreeSet::new(),        &files,    );    assert!(        matches!(            events.as_slice(),            [                Event::State { state: SessionState::Ended, .. },                Event::Exited { code: None, signal: None, .. }            ]        ),        "a session closed with Ctrl-C leaves no marker and is still ended: {events:?}"    );    // The transcript's own last write — 1_000 seconds past the epoch — and    // NEVER the instant this pass noticed, a whole day later.    assert!(matches!(        &events[1],        Event::Exited { at: Some(at), session_id, .. }            if at == "1970-01-01T00:16:40Z" && session_id == CLAUDE_SESSION    ));}#[test]fn the_marker_rule_still_ends_a_session_long_before_the_day_is_up() {    let mut watcher = Watcher::new();    let files = Fake::with("/p/b.jsonl", CLAUDE_ENDED);    let file = found(Tool::Claude, "/p/b.jsonl", 800, 1_000);    watcher.observe(1_010, NOW, std::slice::from_ref(&file), &BTreeSet::new(), &files);    let (events, _) = watcher.observe(1_020, NOW, &[file], &BTreeSet::new(), &files);    assert!(        matches!(&events[0], Event::State { state: SessionState::Ended, .. }),        "twenty seconds, not twenty-four hours: the agent said so itself"    );}#[test]fn a_transcript_written_to_after_a_day_of_silence_re_opens() {    let mut watcher = Watcher::new();    let mut files = Fake::with("/p/a.jsonl", CLAUDE);    let file = found(Tool::Claude, "/p/a.jsonl", 900, 1_000);    watcher.observe(1_000, NOW, std::slice::from_ref(&file), &BTreeSet::new(), &files);    let ended_at = 1_000 + ENDED_AFTER_SECONDS;    let (events, _) = watcher.observe(        ended_at,        NOW,        std::slice::from_ref(&file),        &BTreeSet::new(),        &files,    );    assert!(matches!(        &events[0],        Event::State { state: SessionState::Ended, .. }    ));    // Somebody typed into it: `--continue`, `--resume`, or a Mac that woke up.    files.put("/p/a.jsonl", CLAUDE);    let (events, _) = watcher.observe(        ended_at + 1,        NOW,        &[found(Tool::Claude, "/p/a.jsonl", 1_400, ended_at + 1)],        &BTreeSet::new(),        &files,    );    assert!(        events            .iter()            .any(|event| matches!(event, Event::State { state: SessionState::Running, .. })),        "the file is the truth, and a file that grew is a session going again: {events:?}"    );    assert!(        !events            .iter()            .any(|event| matches!(event, Event::Exited { .. })),        "a re-open is not a second exit"    );}#[test]fn a_transcript_first_seen_already_a_day_old_is_ended_on_the_pass_that_finds_it() {    let mut watcher = Watcher::new();    let files = Fake::with("/p/a.jsonl", CLAUDE);    let (events, run) = watcher.observe(        1_000 + ENDED_AFTER_SECONDS,        NOW,        &[found(Tool::Claude, "/p/a.jsonl", 900, 1_000)],        &BTreeSet::new(),        &files,    );    assert_eq!(run.adopted, 1, "it is still adopted — the card says what it was");    assert!(        events            .iter()            .any(|event| matches!(event, Event::Exited { code: None, .. })),        "and it arrives already ended rather than as a session waiting on somebody: {events:?}"    );}#[test]fn a_session_this_host_spawned_is_never_adopted_from_its_own_transcript() {    let mut watcher = Watcher::new();    let files = Fake::with("/p/a.jsonl", CLAUDE);    let owned: BTreeSet<String> = [CLAUDE_SESSION.to_string()].into_iter().collect();    let (events, run) = watcher.observe(        1_000,        NOW,        &[found(Tool::Claude, "/p/a.jsonl", 900, 1_000)],        &owned,        &files,    );    assert!(events.is_empty());    assert_eq!(run.adopted, 0);    assert_eq!(run.skipped, 1);    assert!(!watcher.holds(CLAUDE_SESSION));}#[test]fn a_file_whose_head_names_no_session_is_counted_rather_than_adopted_under_a_guess() {    let mut watcher = Watcher::new();    let files = Fake::with("/p/junk.jsonl", "not json at all\n{}\n");    let (events, run) = watcher.observe(        1_000,        NOW,        &[found(Tool::Claude, "/p/junk.jsonl", 20, 1_000)],        &BTreeSet::new(),        &files,    );    assert!(events.is_empty());    assert_eq!(run.adopted, 0);    assert_eq!(run.skipped, 1);}#[test]fn a_codex_rollout_is_adopted_by_its_session_meta_record() {    let mut watcher = Watcher::new();    let files = Fake::with("/p/rollout-x.jsonl", CODEX);    let (events, run) = watcher.observe(        1_000,        NOW,        &[found(Tool::Codex, "/p/rollout-x.jsonl", 700, 1_000)],        &BTreeSet::new(),        &files,    );    assert_eq!(run.adopted, 1);    assert!(matches!(        &events[0],        Event::Adopted { session_id, tool: Tool::Codex, cwd, .. }            if session_id == CODEX_SESSION && cwd.as_deref() == Some("/work/other")                || session_id == CODEX_SESSION && cwd.as_deref() == Some("/work/repo")    ));    assert_eq!(watcher.sessions().get(CODEX_SESSION), Some(&Tool::Codex));}#[test]fn two_files_naming_one_session_are_one_adopted_session() {    let mut watcher = Watcher::new();    let mut files = Fake::with("/p/a.jsonl", CLAUDE);    files.put("/p/copy.jsonl", CLAUDE);    let (events, run) = watcher.observe(        1_000,        NOW,        &[            found(Tool::Claude, "/p/a.jsonl", 900, 1_000),            found(Tool::Claude, "/p/copy.jsonl", 900, 1_000),        ],        &BTreeSet::new(),        &files,    );    assert_eq!(run.adopted, 1);    assert_eq!(run.skipped, 1);    assert_eq!(        events            .iter()            .filter(|event| matches!(event, Event::Adopted { .. }))            .count(),        1    );}#[test]fn the_roots_are_the_two_agents_own_and_an_override_moves_one() {    let plain = Roots::resolve("/home/me", None, None);    assert_eq!(plain.claude, PathBuf::from("/home/me/.claude/projects"));    assert_eq!(plain.codex, PathBuf::from("/home/me/.codex/sessions"));    let moved = Roots::resolve("/home/me", Some("/elsewhere/claude"), Some("/elsewhere/codex"));    assert_eq!(moved.claude, PathBuf::from("/elsewhere/claude/projects"));    assert_eq!(moved.codex, PathBuf::from("/elsewhere/codex/sessions"));}#[test]fn a_blank_override_reads_as_no_override() {    assert_eq!(        Roots::resolve("/home/me", Some("   "), Some("")),        Roots::resolve("/home/me", None, None)    );}#[test]fn only_the_files_each_agent_actually_writes_are_transcripts() {    assert!(is_transcript(        Tool::Claude,        Path::new("/p/-Users-me-repo/abc.jsonl")    ));    assert!(!is_transcript(Tool::Claude, Path::new("/p/notes.md")));    assert!(is_transcript(        Tool::Codex,        Path::new("/s/2026/09/18/rollout-2026-09-18T09-00-00-abc.jsonl")    ));    assert!(        !is_transcript(Tool::Codex, Path::new("/s/2026/09/18/history.jsonl")),        "a Codex rollout is named rollout-*, and that directory holds other files"    );}/// RULE: A session whose turns the user's own Stop hook logs gets `spoke` from this host and never `turn`, so the hook is that session's one source of turns.#[test]fn a_session_the_hook_logs_gets_its_line_and_no_turn() {    let mut watcher = Watcher::new();    watcher.set_hooked(BTreeSet::from([Tool::Claude]));    let mut files = Fake::with("/p/a.jsonl", CLAUDE);    files.put("/c/r.jsonl", CODEX);    let (events, _) = watcher.observe(        1_000,        NOW,        &[            found(Tool::Claude, "/p/a.jsonl", 900, 1_000),            found(Tool::Codex, "/c/r.jsonl", 900, 1_000),        ],        &BTreeSet::new(),        &files,    );    let claude: Vec<&Event> = events        .iter()        .filter(|event| event_session(event) == Some(CLAUDE_SESSION))        .collect();    assert!(claude.iter().any(|event| matches!(        event,        Event::Spoke { role: TurnRole::Assistant, text, .. }            if text == "I added two: one for the bound and one for the replay tail."    )));    assert!(!claude.iter().any(|event| matches!(event, Event::Turn { .. })));    assert!(        events.iter().any(|event| matches!(            event,            Event::Turn { session_id, .. } if session_id == CODEX_SESSION        )),        "an agent no hook logs keeps its turns"    );}fn event_session(event: &Event) -> Option<&str> {    match event {        Event::Turn { session_id, .. }        | Event::Spoke { session_id, .. }        | Event::State { session_id, .. }        | Event::Adopted { session_id, .. } => Some(session_id),        _ => None,    }}/// RULE: The turn-logging hook counts as registered only when a `Stop` hook command names it in Claude's settings.#[test]fn only_a_stop_hook_naming_the_turn_log_counts() {    let registered = r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"bash \"$HOME/.claude/scripts/cotton-session-log.sh\" || true"}]}]}}"#;    assert!(stop_hook_logs_turns(registered));    let elsewhere = r#"{"hooks":{"SessionEnd":[{"hooks":[{"type":"command","command":"cotton-session-log.sh"}]}],"Stop":[{"hooks":[{"type":"command","command":"say done"}]}]}}"#;    assert!(!stop_hook_logs_turns(elsewhere));    assert!(!stop_hook_logs_turns("{}"));    assert!(!stop_hook_logs_turns("not json"));    assert!(hooked_tools(&Roots::resolve("/nonexistent", None, None)).is_empty());}/// RULE: The turn-logging hook counts only when its own credentials would let it post, because a hook that exits silently would leave its sessions' turns filed nowhere.#[test]fn a_registered_hook_with_nowhere_to_post_does_not_count() {    let dir = tempfile::tempdir().expect("a temp dir");    let roots = Roots::resolve(dir.path(), None, None);    std::fs::create_dir_all(roots.claude_settings.parent().expect("a parent")).expect("mkdir");    std::fs::write(        &roots.claude_settings,        r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"bash cotton-session-log.sh"}]}]}}"#,    )    .expect("settings");    assert!(hooked_tools(&roots).is_empty(), "no credentials file");    std::fs::create_dir_all(roots.hook_creds.parent().expect("a parent")).expect("mkdir");    let creds = |endpoint: &str, token: &str| {        std::fs::write(&roots.hook_creds, format!(r#"{{"endpoint":"{endpoint}","token":"{token}"}}"#))            .expect("creds");    };    creds("https://example.test/mcp", "");    assert!(hooked_tools(&roots).is_empty(), "no token");    creds("https://old.test/functions/v1/cotton-mcp", "t");    assert!(hooked_tools(&roots).is_empty(), "the frozen hosted server");    creds("https://example.test/mcp", "t");    assert_eq!(hooked_tools(&roots), BTreeSet::from([Tool::Claude]));}