//! ADOPTED SESSIONS — the ones this host did not start. //! //! A person opens `claude` in a terminal, or an editor does. Nothing about //! that session reaches Cotton: no launch placed it, no hook of ours fires in //! it, and no pseudo-terminal of ours holds it. What it DOES leave is a file — //! `~/.claude/projects//.jsonl`, or //! `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl` — and that file is the whole //! of what this module reads. //! //! **What an adopted session is, exactly.** A `cotton_sessions` row with //! `host_owned = 0`: a card on the phone that shows the state, the last thing //! the agent said and the turns, and NOTHING a person can act on. There is no //! terminal to attach to, nothing to stop and no permission to answer, because //! this host does not own that process — `serve` refuses all four with a //! sentence rather than pretending. This is what replaces the global //! `SessionStart`/`Stop` hook scripts that used to file the same rows from //! inside every session ([Cotton note "The Code tool — why a Mac holds the sessions"]). //! //! **Three rules, and every one of them is a rule about not inventing:** //! //! 1. **Identity comes out of the transcript, never out of the path.** Claude //! names the file after the session and Codex does not, and a path parser //! would be a second spelling of an agent's convention. Both adapters read //! the head ([`crate::agents::Adapter::read_adopted_meta`]); a file whose //! head names no session is skipped and counted. //! 2. **Quiet is idle, and a DAY of quiet is ended — the transcript is the //! truth.** No write for [`IDLE_AFTER_SECONDS`] makes a session `idle`. The //! agent's own end marker on a file that has stopped changing makes it //! `ended`, as it always did. So, now, does [`ENDED_AFTER_SECONDS`] of //! silence with no marker at all: a session closed with Ctrl-C or a shut //! window leaves no marker and no process to reap, and the old rule left //! every one of them `idle` for ever — four hundred and seventy-four of //! them on the owner's own file, with `ended_at` null and a card that said //! a session from three weeks ago was waiting for him. `ended_at` is the //! transcript's LAST WRITE and the exit code stays NULL: nobody reaped this //! process, and a fabricated 0 would read on the phone as "it finished //! cleanly". A transcript that is written to again RE-OPENS — back to //! `running`, `ended_at` cleared — because the file is the truth and a file //! that grew is a session that is going again. //! 3. **A session this host OWNS is never adopted.** A hosted session writes //! the same transcript in the same directory; every scan is handed the //! agent session ids the host holds and skips their files, or one session //! would arrive on the phone twice. //! //! **Polled on a timer, not watched.** [`SCAN_EVERY_SECONDS`] mtimes, no //! filesystem-event dependency: the crate's dependency list is four crates and //! a notification framework for a directory that changes a few times a minute //! is not worth a fifth. A fifteen-second floor under "the phone learns a new //! session exists" is well inside what a card needs. //! //! Everything here is a PURE FUNCTION over values except [`scan`] and //! [`FileTranscripts`], which are the two reads — so `adopted_tests.rs` drives //! the whole state machine on a fake clock with no files at all, and //! `tests/adopted.rs` drives the reads over fixtures written into a temporary //! directory. **Never over the real `~/.claude`**: the transcripts there are //! the owner's own work. use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use crate::agents::{adapter, AdoptedMeta}; use crate::protocol::{Event, SessionState, Tool}; /// How long a transcript may go unwritten before its session reads `idle`. /// /// Ninety seconds. Both agents append as they work — a tool call, a reply, a /// token record — so a minute and a half of silence is a session waiting on a /// person or thinking about something long, and either way the card should /// stop saying "running". Short enough to be useful, long enough that a slow /// model call does not flicker the card. pub const IDLE_AFTER_SECONDS: i64 = 90; /// How long a transcript may go unwritten before its session reads `ended`. /// /// Twenty-four hours. A person who steps away from a session over lunch, or /// overnight, is coming back to it — that is the whole reason `idle` exists and /// why this is a DAY rather than an hour. Past a day, a transcript nobody has /// touched is not a session anybody is waiting on: the terminal was closed, the /// Mac was restarted, or Ctrl-C ended it without a marker, and in every one of /// those cases the honest reading is `ended` with no exit code. /// /// It is deliberately far above [`IDLE_AFTER_SECONDS`]: the two rules are one /// ladder, and a session that ends here has ALREADY spent a day reading `idle` /// on the card, which is the state that says "quiet, and nobody knows more than /// that". pub const ENDED_AFTER_SECONDS: i64 = 24 * 60 * 60; /// How often the host walks the transcript directories. /// /// Fifteen seconds: the latency between somebody opening `claude` in a /// terminal and its card appearing on the phone. A stat of a few dozen files /// at this cadence is nothing, and it costs no dependency. pub const SCAN_EVERY_SECONDS: u64 = 15; /// How much of a transcript's head is read to name its session. /// /// Both agents put the identity in the first records; sixty-four kilobytes is /// far past that and far under a transcript. pub const HEAD_BYTES: u64 = 64 * 1024; /// How much of a transcript's tail is read for the last turn and the end /// marker. /// /// Both parsers scan BACKWARDS from the end, so a tail is all they need — and /// reading a multi-megabyte transcript every fifteen seconds, for every /// session, to find its last line would be the cost this bound removes. A /// first line cut in half is not JSON and is skipped, which is what those /// parsers already do with a line they cannot read. pub const TAIL_BYTES: u64 = 256 * 1024; /// How deep a scan walks below a root. /// /// Claude files a transcript one directory down (`projects//`) and Codex /// three (`sessions/YYYY/MM/DD/`). Four is both with a step to spare, and a /// bound rather than an unbounded walk so a symlink into somebody's home /// directory cannot turn a scan into a filesystem crawl. pub const MAX_DEPTH: usize = 4; /// Where the two agents keep their transcripts on this Mac. /// /// Resolved from the environment by `main.rs` — never here, for the reason /// [`crate::data_dir`] gives: the library takes values and the binary reads /// the process. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Roots { /// `$CLAUDE_CONFIG_DIR/projects`, else `~/.claude/projects`. pub claude: PathBuf, /// `$CODEX_HOME/sessions`, else `~/.codex/sessions`. pub codex: PathBuf, /// `$CLAUDE_CONFIG_DIR/settings.json`, else `settings.json` in `~/.claude` — /// where the user's own hooks are registered ([`hooked_tools`]). pub claude_settings: PathBuf, /// `~/.config/tinmen/memory-mirror.json` — where that hook reads the /// server it posts turns to ([`hook_can_post`]). pub hook_creds: PathBuf, } /// The environment variable that moves Claude's configuration directory. pub const CLAUDE_CONFIG_DIR_ENV: &str = "CLAUDE_CONFIG_DIR"; /// The environment variable that moves Codex's home. pub const CODEX_HOME_ENV: &str = "CODEX_HOME"; impl Roots { /// The two roots, given this person's home and whatever the two agents' /// own overrides are set to. /// /// A blank override reads as no override — the same rule /// [`crate::data_dir::resolve_data_dir`] keeps, because an exported empty /// string is what a shell leaves behind and it means "unset" to the person /// who typed it. pub fn resolve(home: impl AsRef, claude: Option<&str>, codex: Option<&str>) -> Self { let home = home.as_ref(); let over = |value: Option<&str>, fallback: &str| -> PathBuf { match value.map(str::trim).filter(|value| !value.is_empty()) { Some(value) => PathBuf::from(value), None => home.join(fallback), } }; Self { claude: over(claude, ".claude").join("projects"), codex: over(codex, ".codex").join("sessions"), claude_settings: over(claude, ".claude").join("settings.json"), hook_creds: home.join(".config/tinmen/memory-mirror.json"), } } } /// The user's own `Stop` hook that logs every Claude session's turns through /// `log_session` — the session-log hook script, installed at user /// level as `~/.claude/scripts/cotton-session-log.sh`. pub const TURN_LOG_HOOK: &str = "cotton-session-log"; /// The agents whose turns the user's own hook logs on this Mac. /// /// **One source of turns per session.** That hook numbers a turn by its line in /// the transcript; this host numbers what it sampled. Both land on one /// `(session, seq)` prompt row, so a session both of them logged read as a mix /// of unrelated turns, each overwriting the other. For an agent answered here /// the host says `spoke` and leaves the turns to the hook. /// /// Read from the settings file, not from a session's rows: the hook's first /// turn may reach this Mac's file a minute after this host's, and a rule that /// waited for it would already have written the turn it exists to prevent. /// A file that is missing or not JSON registers nothing. Only Claude has such a /// hook. /// /// **Registered AND able to post.** The hook exits without a word when it has /// no server to post to — no endpoint, the frozen hosted one, or no token in /// `hook_creds` — and a host that said `spoke` for it then filed that /// session's turns nowhere. So the hook counts only when its own credentials /// would let it post; a hook that reads them from its environment instead is /// not seen here, and its turns are filed twice, never lost. pub fn hooked_tools(roots: &Roots) -> BTreeSet { let registered = std::fs::read_to_string(&roots.claude_settings) .map(|text| stop_hook_logs_turns(&text)) .unwrap_or(false); let can_post = std::fs::read_to_string(&roots.hook_creds) .map(|text| hook_can_post(&text)) .unwrap_or(false); if registered && can_post { BTreeSet::from([Tool::Claude]) } else { BTreeSet::new() } } /// Whether the turn-logging hook would post with these credentials — the /// hook's own gates (in the session-log hook script): an endpoint that /// is not the frozen hosted server's (`/functions/v1/cotton-mcp`), and a token. pub fn hook_can_post(creds: &str) -> bool { let Ok(value) = serde_json::from_str::(creds) else { return false; }; let field = |name: &str| { value .get(name) .and_then(serde_json::Value::as_str) .map(str::trim) .unwrap_or_default() .to_string() }; let endpoint = field("endpoint"); !endpoint.is_empty() && !endpoint.contains("/functions/v1/cotton-mcp") && !field("token").is_empty() } /// Whether this Claude settings text registers [`TURN_LOG_HOOK`] under `Stop`. /// /// Claude's own shape: `hooks.Stop` is a list of matchers, each with a list of /// `{ "type": "command", "command": … }`. pub fn stop_hook_logs_turns(settings: &str) -> bool { let Ok(value) = serde_json::from_str::(settings) else { return false; }; value .pointer("/hooks/Stop") .and_then(serde_json::Value::as_array) .into_iter() .flatten() .filter_map(|matcher| matcher.get("hooks").and_then(serde_json::Value::as_array)) .flatten() .filter_map(|hook| hook.get("command").and_then(serde_json::Value::as_str)) .any(|command| command.contains(TURN_LOG_HOOK)) } /// One transcript file, as a scan found it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Found { /// Which agent wrote it. pub tool: Tool, /// Where it is. pub path: PathBuf, /// Its size in bytes — what "the file grew" is decided by. pub len: u64, /// When it was last written, seconds since the epoch. pub modified: i64, } /// Reading a transcript, as a seam. /// /// Two reads and no third: the head names the session, the tail says what it /// last did. [`FileTranscripts`] is the one that touches a disk. pub trait Transcripts { /// The first [`HEAD_BYTES`] of a file, as text. fn head(&self, path: &Path) -> Option; /// The last [`TAIL_BYTES`] of a file, as text. fn tail(&self, path: &Path) -> Option; } /// The real one. #[derive(Debug, Clone, Copy, Default)] pub struct FileTranscripts; impl Transcripts for FileTranscripts { fn head(&self, path: &Path) -> Option { read_span(path, Span::Head(HEAD_BYTES)) } fn tail(&self, path: &Path) -> Option { read_span(path, Span::Tail(TAIL_BYTES)) } } enum Span { Head(u64), Tail(u64), } /// A bounded read of one end of a file. /// /// Lossy UTF-8 rather than a refusal: a transcript cut mid-character at a /// boundary this module chose is a line the parsers skip, and answering `None` /// for the whole file would lose every line before it. fn read_span(path: &Path, span: Span) -> Option { use std::io::{Read as _, Seek as _, SeekFrom}; let mut file = std::fs::File::open(path).ok()?; let len = file.metadata().ok()?.len(); let (from, take) = match span { Span::Head(bytes) => (0, bytes.min(len)), Span::Tail(bytes) => (len.saturating_sub(bytes), bytes.min(len)), }; file.seek(SeekFrom::Start(from)).ok()?; let mut buffer = vec![0u8; take as usize]; let read = file.read(&mut buffer).ok()?; buffer.truncate(read); Some(String::from_utf8_lossy(&buffer).into_owned()) } /// Walk the two roots and answer every transcript under them. /// /// A directory that is not there is NOT a failure: a Mac with no `codex` /// installed has no `~/.codex`, which is a fact about the Mac and not an /// error to report every fifteen seconds. pub fn scan(roots: &Roots) -> Vec { let mut found = Vec::new(); walk(&roots.claude, Tool::Claude, 0, &mut found); walk(&roots.codex, Tool::Codex, 0, &mut found); found.sort_by(|a, b| a.path.cmp(&b.path)); found } fn walk(dir: &Path, tool: Tool, depth: usize, into: &mut Vec) { if depth > MAX_DEPTH { return; } let Ok(entries) = std::fs::read_dir(dir) else { return; }; for entry in entries.flatten() { let path = entry.path(); // `metadata` FOLLOWS a symlink and `file_type` does not; a transcript // reached through a link is still a transcript, and the depth bound is // what keeps a link to `/` from being a crawl. let Ok(kind) = entry.file_type() else { continue }; if kind.is_dir() { walk(&path, tool, depth + 1, into); continue; } if !is_transcript(tool, &path) { continue; } let Ok(meta) = entry.metadata() else { continue }; into.push(Found { tool, len: meta.len(), modified: modified_epoch(&meta), path, }); } } /// Whether a file is one of this agent's transcripts. /// /// Claude's are `.jsonl`; Codex's are `rollout-*.jsonl`, and the /// prefix is checked because that directory also holds files that are not /// rollouts. pub fn is_transcript(tool: Tool, path: &Path) -> bool { let Some(name) = path.file_name().and_then(|name| name.to_str()) else { return false; }; if !name.ends_with(".jsonl") { return false; } match tool { Tool::Claude => true, Tool::Codex => name.starts_with("rollout-"), } } /// An epoch second, in the one spelling every stamp this crate writes takes. /// /// A CONVERSION, not a clock: [`crate::clock::Clock`] is the only thing here /// that reads the time, and this turns a number a caller already handed in /// into the text a row wants. An epoch outside what a date can hold reads as /// the epoch itself rather than panicking — a file whose mtime is not a real /// instant is a filesystem's problem, and a stamp of 1970 is a visible one. fn rfc3339(epoch: i64) -> String { chrono::DateTime::from_timestamp(epoch, 0) .unwrap_or(chrono::DateTime::UNIX_EPOCH) .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) } fn modified_epoch(meta: &std::fs::Metadata) -> i64 { meta.modified() .ok() .and_then(|at| at.duration_since(std::time::UNIX_EPOCH).ok()) .map(|since| since.as_secs() as i64) .unwrap_or_default() } /// What this host has already said about one adopted transcript. #[derive(Debug, Clone, PartialEq, Eq)] struct Watched { session_id: String, tool: Tool, len: u64, modified: i64, state: SessionState, /// Whether the tail carried the agent's own end marker last time it was /// read. marked_ended: bool, /// Turns emitted for this session, which is what `seq` counts. turns: u64, /// The last turn's text, so a re-read of an unchanged tail is not a /// second copy of the same turn. last_turn: Option, } /// What one pass observed, for the log and for a test. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct Observed { /// Sessions adopted for the first time in this pass. pub adopted: usize, /// Files this pass did not adopt: a session this host owns, or a head /// that named none. pub skipped: usize, } /// Everything this host remembers about the transcripts it is watching. /// /// Keyed by PATH, because the path is what a scan answers and the session id /// costs a read. One path is one session. #[derive(Debug, Default)] pub struct Watcher { seen: BTreeMap, /// The agents whose turns the user's own hook logs ([`hooked_tools`]). hooked: BTreeSet, } impl Watcher { /// A watcher that has seen nothing. pub fn new() -> Self { Self::default() } /// Every adopted session this watcher holds, by its agent session id. pub fn sessions(&self) -> BTreeMap { self.seen .values() .map(|held| (held.session_id.clone(), held.tool)) .collect() } /// Which agents' turns the user's own hook logs, as of this pass — read /// by the caller, because this module never reads a disk it was not /// handed. pub fn set_hooked(&mut self, tools: BTreeSet) { self.hooked = tools; } /// Whether this id is one of the sessions adopted here. pub fn holds(&self, session_id: &str) -> bool { self.seen .values() .any(|held| held.session_id == session_id) } /// Read one pass of the scan and answer the events it earned. /// /// `now` is both spellings of one instant — the epoch seconds the file /// times are compared against, and the RFC 3339 stamp an `adopted` event /// carries — because this module never reads a clock. /// /// `owned` is the agent session ids this host holds pseudo-terminals for. /// Their transcripts sit in the same directories and are skipped: rule 3. pub fn observe( &mut self, now_epoch: i64, now_rfc3339: &str, found: &[Found], owned: &BTreeSet, transcripts: &dyn Transcripts, ) -> (Vec, Observed) { let mut events = Vec::new(); let mut run = Observed::default(); for file in found { let first_sight = !self.seen.contains_key(&file.path); if first_sight { let Some(meta) = transcripts .head(&file.path) .and_then(|head| adapter(file.tool).read_adopted_meta(&head)) else { // A file whose head names no session. Counted rather than // adopted under a name this host made up. run.skipped += 1; continue; }; if owned.contains(&meta.session_id) || self.holds(&meta.session_id) { run.skipped += 1; continue; } events.push(adopted_event(file, &meta, now_rfc3339)); run.adopted += 1; self.seen.insert( file.path.clone(), Watched { session_id: meta.session_id, tool: file.tool, // Deliberately BEHIND the file, so the first pass reads // the tail and says what the session last did. len: u64::MAX, modified: i64::MIN, state: SessionState::Starting, marked_ended: false, turns: 0, last_turn: None, }, ); } let held = self.seen.get_mut(&file.path).expect("just inserted"); if owned.contains(&held.session_id) { // The host spawned a session with this id after the file was // adopted — it is the host's now, and the host's own events // are the truth about it. run.skipped += 1; continue; } let changed = file.len != held.len || file.modified != held.modified; let session_id = held.session_id.clone(); let tool = held.tool; if changed { if let Some(tail) = transcripts.tail(&file.path) { held.marked_ended = adapter(tool).transcript_ended(&tail); if let Some(turn) = adapter(tool).read_last_turn(&tail) { if held.last_turn.as_deref() != Some(turn.text.as_str()) { held.last_turn = Some(turn.text.clone()); if self.hooked.contains(&tool) { // The hook logs this session's turns; this // host only says what the card's line is. events.push(Event::Spoke { session_id: session_id.clone(), role: turn.role, text: turn.text, }); } else { held.turns += 1; events.push(Event::Turn { session_id: session_id.clone(), role: turn.role, text: turn.text, seq: held.turns, }); } } } } held.len = file.len; held.modified = file.modified; } let silent_for = now_epoch.saturating_sub(file.modified); let quiet = if first_sight { // No previous reading to compare against, so "it has stopped // changing" is the same thing `idle` is decided by. silent_for >= IDLE_AFTER_SECONDS } else { !changed }; // ONE LADDER, read from the top. A day of silence is `ended` // whatever the tail says, which is what makes a session closed // with Ctrl-C land somewhere other than `idle`; the marker is the // FASTER way to the same state and needs no day. Everything below // is the pair of rules that were always here. let next = if silent_for >= ENDED_AFTER_SECONDS || (held.marked_ended && quiet) { SessionState::Ended } else if silent_for >= IDLE_AFTER_SECONDS { SessionState::Idle } else { SessionState::Running }; if next != held.state { held.state = next; events.push(Event::State { session_id: session_id.clone(), state: next, waiting_kind: None, request_id: None, }); if next == SessionState::Ended { // No code and no signal: nobody here reaped this process, // and a fabricated 0 would read on the phone as "it // finished cleanly". The index's own rule. // // `at` is the transcript's OWN last write, never this // pass: a session that stopped at lunchtime and was found // quiet at midnight ended at lunchtime, and the file is // the only thing here that knows which. events.push(Event::Exited { session_id, code: None, signal: None, at: Some(rfc3339(file.modified)), error: None, }); } // AND IT CAN COME BACK. Somebody typing into a session this // host had written off — `--continue`, `--resume`, or a Mac // that was asleep for two days — moves the file, which moves // the state back to `running` on the line above. Taking the // end stamp back OFF the row is the mirror's job and it needs // no event of its own: a `state` that is not `ended` clears // `ended_at`, because a session that is going again has no end // (`cotton-client/src/session_host/mirror.rs`). } } (events, run) } } fn adopted_event(file: &Found, meta: &AdoptedMeta, now_rfc3339: &str) -> Event { Event::Adopted { session_id: meta.session_id.clone(), tool: file.tool, cwd: meta.cwd.clone(), // The transcript's own first stamp when it has one; otherwise the // instant this host first saw the file, which is the earliest thing it // can honestly say. started_at: meta .started_at .clone() .unwrap_or_else(|| now_rfc3339.to_string()), } } #[cfg(test)] #[path = "adopted_tests.rs"] mod adopted_tests;