//! `log_session` and `list_sessions`, driven through `dispatch::call_tool` //! over a fake `ToolServices` rather than the `/v1/mcp` endpoint. //! //! The property under test throughout: A SESSION LOG MUST NEVER FAIL. A //! summary too long, a prompt that grows when its secret is redacted, a seq //! already written, a blank line — each is absorbed, because the Stop hook //! advances its cursor only on success and a refusal is a session that records //! nothing further, for ever. //! //! ONE CASE STAYED IN `cotton-server`: the one that reads `cotton_mcp_audit`. //! A handler asks `ctx.audit` for a line, but the SERVER decides what an audit //! row is — the `args_summary` it redacts is computed at the transport, never //! in a handler — so that assertion belongs to the crate that writes the row. mod support; use std::sync::atomic::{AtomicU64, Ordering}; use cotton_store::schema::ddl::SCHEMA_VERSION; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use support::harness::Harness; use support::mcp::{call_tool, call_tool_raw, mint_token_ref}; /// When every seeded row says it was written. const AT: &str = "2026-08-22T10:00:00.000Z"; /// The session every `log_session` case logs, unless it says otherwise. const EXTERNAL_ID: &str = "11111111-2222-4333-8444-555555555555"; const LAST_ACTIVE: &str = "2026-08-24T01:02:03.456Z"; // ── the fixture ───────────────────────────────────────────────────────────── fn op(table: &str, row_id: &str, patch: Value) -> Value { static NEXT: AtomicU64 = AtomicU64::new(0); let n = NEXT.fetch_add(1, Ordering::Relaxed); json!({ "opId": format!("01J{:023}", n), "deviceId": "device:seed", "kind": "upsert", "table": table, "rowId": row_id, "patch": patch, "hlc": format!("1700000000{:03}:0000:device:seed", n), "schemaVersion": SCHEMA_VERSION, }) } /// The ops a device's push would have folded, folded the same way — the /// harness panics on a rejection, exactly as the push assertion did. fn seed(h: &Harness, ops: Vec) { h.seed(&ops); } fn project_op(h: &Harness, id: &str, slug: &str, repos: &[&str]) -> Value { let name = { let mut chars = slug.chars(); match chars.next() { Some(first) => first.to_uppercase().collect::() + chars.as_str(), None => String::new(), } }; op( "cotton_memory_projects", id, json!({ "id": id, "workspace_id": h.workspace_id, "slug": slug, "name": name, "repos": repos, "status": "active", "created_at": AT, "updated_at": AT, }), ) } struct Seeded { h: Harness, secret: String, } fn harness_with_token() -> Seeded { let h = Harness::new(); let secret = mint_token_ref(&h, &["read", "write"], "Claude"); Seeded { h, secret } } /// The base arguments every `log_session` case starts from. fn base() -> Map { let mut args = Map::new(); args.insert("tool".to_string(), Value::from("claude-code")); args.insert("externalId".to_string(), Value::from(EXTERNAL_ID)); args.insert("machine".to_string(), Value::from("studio")); args.insert("lastActiveAt".to_string(), Value::from(LAST_ACTIVE)); args } /// `{ ...base, ...over }` — `over` last, so a case can replace any default. fn with(over: Value) -> Value { let mut args = base(); if let Some(over) = over.as_object() { for (key, value) in over { args.insert(key.clone(), value.clone()); } } Value::Object(args) } fn log(s: &Seeded, over: Value) -> support::mcp::ToolAnswer { call_tool_raw(&s.h, &s.secret, "log_session", with(over)) } // ── reading the file back ─────────────────────────────────────────────────── fn one(h: &Harness, sql: &str, params: Vec) -> Option { h.with(|db| db.get(sql, ¶ms)).expect("the read runs") } fn all(h: &Harness, sql: &str, params: Vec) -> Vec { h.with(|db| db.all(sql, ¶ms)).expect("the read runs") } fn run(h: &Harness, sql: &str, params: Vec) { h.run(sql, ¶ms); } /// One column of the session row with this external id. fn session_text(h: &Harness, external_id: &str, column: &str) -> Option { one( h, &format!("SELECT {column} AS value FROM cotton_sessions WHERE external_id = ?"), vec![SqlValue::Text(external_id.to_string())], ) .and_then(|row| row.text("value").map(str::to_string)) } fn session_int(h: &Harness, external_id: &str, column: &str) -> Option { one( h, &format!("SELECT {column} AS value FROM cotton_sessions WHERE external_id = ?"), vec![SqlValue::Text(external_id.to_string())], ) .and_then(|row| row.int("value")) } fn session_count(h: &Harness) -> i64 { one(h, "SELECT count(*) AS n FROM cotton_sessions", Vec::new()) .and_then(|row| row.int("n")) .unwrap_or(0) } /// Every prompt in the file, by seq: `(seq, text, ts)`. fn prompts(h: &Harness) -> Vec<(i64, String, String)> { all( h, "SELECT seq, text, ts FROM cotton_prompts ORDER BY seq", Vec::new(), ) .iter() .map(|row| { ( row.int("seq").unwrap_or_default(), row.text("text").unwrap_or_default().to_string(), row.text("ts").unwrap_or_default().to_string(), ) }) .collect() } /// Every turn in the file: `(seq, role, text)`. fn turns(h: &Harness) -> Vec<(i64, String, String)> { all( h, "SELECT seq, role, text FROM cotton_prompts ORDER BY seq", Vec::new(), ) .iter() .map(|row| { ( row.int("seq").unwrap_or_default(), row.text("role").unwrap_or_default().to_string(), row.text("text").unwrap_or_default().to_string(), ) }) .collect() } /// Every table a phone syncing from zero would be handed rows in. /// /// There is no log: the tables answer for an author, so this is an exchange /// from empty cursors. fn op_tables(h: &Harness) -> Vec { every_op(h).into_iter().map(|op| op.table).collect() } /// Every op this file would hand a peer starting from nothing, page by page: /// the kit and the shell a harness holds fill more than one page. fn every_op(h: &Harness) -> Vec { let mut seen = std::collections::BTreeMap::new(); let mut ops = Vec::new(); loop { let page = cotton_store::exchange::answer(&h.db, &seen, 5_000).expect("the file answers a peer"); ops.extend(page.ops); seen = page.cursors; if !page.has_more { return ops; } } } /// The listed sessions, by external id, newest first. fn listed(s: &Seeded, args: Value) -> Vec { call_tool(&s.h, &s.secret, "list_sessions", args)["sessions"] .as_array() .expect("a sessions array") .iter() .map(|row| row["externalId"].as_str().unwrap_or_default().to_string()) .collect() } /// The one listed session, whole. fn only_session(s: &Seeded) -> Value { call_tool(&s.h, &s.secret, "list_sessions", json!({}))["sessions"][0].clone() } /// UTF-16 code units, which is what every cap in the port counts. fn units(value: &str) -> usize { value.encode_utf16().count() } // ── log_session ───────────────────────────────────────────────────────────── #[test] fn a_new_sessions_id_is_derived_from_the_pair_the_table_is_unique_on() { // `cotton_sessions` is `UNIQUE (tool, external_id)`, and two servers can // both hear about one agent session — the hook through one, the bus // through the other. A minted uuid apiece was two rows the index refuses // to hold: the second arrival is rejected for ever, and every later // `log_session` patch of the losing id is an INSERT of half a row that // meets `NOT NULL cotton_sessions.tool`. 2,993 parked writes on one // standby Mac were exactly that, said again once a minute. let s = harness_with_token(); let answer = log(&s, json!({})); assert!(!answer.is_error, "{}", answer.text); assert_eq!( answer.json()["sessionId"], json!(cotton_store::protocol::derived_id::session_id( "claude-code", EXTERNAL_ID )), "a session's id is `(tool, external_id)` hashed, never minted" ); } #[test] fn inserts_a_session_with_its_prompts_then_upserts_idempotently() { let s = harness_with_token(); let first = log( &s, json!({ "summary": "Shipped the server.", "prompts": [ { "seq": 131, "ts": "2026-08-24T01:00:00.000Z", "text": "fix the build" }, { "seq": 135, "ts": "2026-08-24T01:01:00+05:30", "text": "now the tests" }, ], "transcriptRef": "host:studio:projects/x/abc.jsonl", }), ); assert!(!first.is_error, "{}", first.text); let first = first.json(); assert_eq!(first["promptCount"], json!(2)); assert_eq!(first["inserted"], json!(2)); assert!(first["sessionId"].is_string()); assert_eq!( session_text(&s.h, EXTERNAL_ID, "tool").as_deref(), Some("claude-code") ); assert_eq!( session_text(&s.h, EXTERNAL_ID, "machine").as_deref(), Some("studio") ); assert_eq!( session_text(&s.h, EXTERNAL_ID, "summary").as_deref(), Some("Shipped the server.") ); assert_eq!(session_int(&s.h, EXTERNAL_ID, "turn_count"), Some(1)); assert_eq!(session_int(&s.h, EXTERNAL_ID, "prompt_count"), Some(2)); assert_eq!( session_text(&s.h, EXTERNAL_ID, "started_at").as_deref(), Some(LAST_ACTIVE) ); assert_eq!( session_text(&s.h, EXTERNAL_ID, "last_active_at").as_deref(), Some(LAST_ACTIVE) ); assert_eq!( session_text(&s.h, EXTERNAL_ID, "transcript_ref").as_deref(), Some("host:studio:projects/x/abc.jsonl") ); // Sparse seqs are kept as given; a zoned ts lands in Z form. assert_eq!( prompts(&s.h), vec![ ( 131, "fix the build".to_string(), "2026-08-24T01:00:00.000Z".to_string() ), ( 135, "now the tests".to_string(), "2026-08-23T19:31:00.000Z".to_string() ), ] ); let second = log( &s, json!({ "lastActiveAt": "2026-08-24T01:10:00.000Z", "summary": "Shipped the server and the app.", "prompts": [ { "seq": 135, "ts": "2026-08-24T01:01:00.000Z", "text": "now the tests (resent)" }, { "seq": 137, "ts": "2026-08-24T01:05:00.000Z", "text": "and the docs" }, ], }), ); assert!(!second.is_error, "{}", second.text); let second = second.json(); assert_eq!(second["sessionId"], first["sessionId"]); assert_eq!(second["promptCount"], json!(3)); assert_eq!(second["inserted"], json!(1)); assert_eq!( session_text(&s.h, EXTERNAL_ID, "summary").as_deref(), Some("Shipped the server and the app.") ); assert_eq!(session_int(&s.h, EXTERNAL_ID, "turn_count"), Some(2)); assert_eq!(session_int(&s.h, EXTERNAL_ID, "prompt_count"), Some(3)); assert_eq!( session_text(&s.h, EXTERNAL_ID, "started_at").as_deref(), Some(LAST_ACTIVE) ); assert_eq!( session_text(&s.h, EXTERNAL_ID, "last_active_at").as_deref(), Some("2026-08-24T01:10:00.000Z") ); assert_eq!( prompts(&s.h) .into_iter() .map(|(_, text, _)| text) .collect::>(), vec!["fix the build", "now the tests", "and the docs"] ); assert_eq!(session_count(&s.h), 1); } /// RULE: log_session writes no user turn that is a phone message the Mac typed into the session, so the owner's words appear once on the session page, as the phone's own row. #[test] fn a_turn_that_is_a_delivered_phone_message_is_not_written_again() { let s = harness_with_token(); let first = log(&s, json!({})); assert!(!first.is_error, "{}", first.text); let session_row = first.json()["sessionId"] .as_str() .expect("a row") .to_string(); // Sent in the order a person would: the instruction before the agent's // answer (seq 2, at AT), the reply after it. for (id, kind, body, status, created) in [ ("msg-typed", "instruction", "Plan the day\r\nthen the week", "done", "2026-08-22T09:59:00.000Z"), ("msg-answer", "answer", "Yes, go ahead", "claimed", "2026-08-22T10:00:30.000Z"), ("msg-withdrawn", "instruction", "Never sent", "withdrawn", "2026-08-22T10:00:40.000Z"), ] { run( &s.h, "INSERT INTO cotton_session_messages \ (id, workspace_id, to_kind, to_session_id, from_kind, kind, body, status, \ created_at, updated_at) \ VALUES (?, ?, 'session', ?, 'owner', ?, ?, ?, ?, ?)", vec![ SqlValue::Text(id.to_string()), SqlValue::Text(s.h.workspace_id.clone()), SqlValue::Text(session_row.clone()), SqlValue::Text(kind.to_string()), SqlValue::Text(body.to_string()), SqlValue::Text(status.to_string()), SqlValue::Text(created.to_string()), SqlValue::Text(created.to_string()), ], ); } let answer = log( &s, json!({ "prompts": [ { "seq": 1, "ts": AT, "role": "user", "text": "Plan the day\nthen the week" }, { "seq": 2, "ts": AT, "role": "assistant", "text": "Plan the day\nthen the week" }, { "seq": 3, "ts": "2026-08-22T10:01:00.000Z", "role": "user", "text": "Yes, go ahead" }, { "seq": 4, "ts": "2026-08-22T10:01:10.000Z", "role": "user", "text": "Never sent" }, { "seq": 5, "ts": "2026-08-22T10:01:20.000Z", "role": "user", "text": "typed at the Mac" }, ], }), ); assert!(!answer.is_error, "{}", answer.text); assert_eq!(answer.json()["promptCount"], json!(3)); let kept: Vec<(i64, String)> = turns(&s.h) .into_iter() .map(|(seq, role, _)| (seq, role)) .collect(); assert_eq!( kept, vec![ (2, "assistant".to_string()), (4, "user".to_string()), (5, "user".to_string()), ] ); } /// RULE: in log_session a delivered message absorbs at most one turn — two "yes" messages absorb exactly two "yes" turns, a third "yes" typed at the Mac is written, whether the hook sends the turns one exchange at a time or resends them all. #[test] fn two_yes_messages_absorb_two_turns_and_a_third_yes_is_written() { let s = harness_with_token(); let first = log(&s, json!({})); assert!(!first.is_error, "{}", first.text); let session_row = first.json()["sessionId"] .as_str() .expect("a row") .to_string(); for (id, created) in [ ("msg-yes-1", "2026-01-01T00:00:01.000Z"), ("msg-yes-2", "2026-01-01T00:00:05.000Z"), ] { run( &s.h, "INSERT INTO cotton_session_messages \ (id, workspace_id, to_kind, to_session_id, from_kind, kind, body, status, \ created_at, updated_at) \ VALUES (?, ?, 'session', ?, 'owner', 'answer', 'yes', 'done', ?, ?)", vec![ SqlValue::Text(id.to_string()), SqlValue::Text(s.h.workspace_id.clone()), SqlValue::Text(session_row.clone()), SqlValue::Text(created.to_string()), SqlValue::Text(created.to_string()), ], ); } let exchanges = [ json!([ { "seq": 3, "ts": "2026-01-01T00:00:02.000Z", "role": "user", "text": "yes" }, { "seq": 4, "ts": "2026-01-01T00:00:03.000Z", "role": "assistant", "text": "Done the first." }, ]), json!([ { "seq": 5, "ts": "2026-01-01T00:00:06.000Z", "role": "user", "text": "yes" }, { "seq": 6, "ts": "2026-01-01T00:00:07.000Z", "role": "assistant", "text": "Done the second." }, ]), json!([ { "seq": 7, "ts": "2026-01-01T00:00:08Z", "role": "user", "text": "yes" }, ]), ]; let mut everything = Vec::new(); for exchange in &exchanges { let answer = log(&s, json!({ "prompts": exchange })); assert!(!answer.is_error, "{}", answer.text); everything.extend(exchange.as_array().expect("a list").iter().cloned()); } // A hook that lost its cursor sends the whole transcript again. let resent = log(&s, json!({ "prompts": everything })); assert!(!resent.is_error, "{}", resent.text); let users: Vec = turns(&s.h) .into_iter() .filter(|(_, role, _)| role == "user") .map(|(seq, _, _)| seq) .collect(); assert_eq!(users, vec![7], "only the third yes, typed at the Mac, is a turn"); } #[test] fn redacts_the_summary_and_every_prompt_before_the_write() { let s = harness_with_token(); log( &s, json!({ "summary": "Rotated to ghp_abcdefghijklmnopqrstuvwxyz0123456789 and moved on.", "prompts": [ { "seq": 1, "ts": LAST_ACTIVE, "text": "use sk-proj-abcdefghijklmnop1234 please" }, ], }), ); assert_eq!( session_text(&s.h, EXTERNAL_ID, "summary").as_deref(), Some("Rotated to [redacted:github-token] and moved on.") ); assert_eq!(prompts(&s.h)[0].1, "use [redacted:api-key] please"); } #[test] fn extracts_shipped_pr_and_commit_links_from_the_summary() { let s = harness_with_token(); log( &s, json!({ "summary": "Opened https://github.com/example/repo/pull/2062 (see \ https://github.com/example/repo/pull/2062) and \ https://github.com/example/repo/commit/abc123def; docs at \ https://github.com/example/repo/blob/main/README.md.", }), ); let shipped = session_text(&s.h, EXTERNAL_ID, "shipped").expect("a shipped column"); assert_eq!( serde_json::from_str::(&shipped).expect("shipped is JSON"), json!([ "https://github.com/example/repo/pull/2062", "https://github.com/example/repo/commit/abc123def", ]) ); } #[test] fn resolves_the_project_from_the_repo_unassigned_when_several_match_explicit_when_named() { let s = harness_with_token(); seed( &s.h, vec![ project_op(&s.h, "p-tinmen", "tinmen", &["github.com/example/tinmen"]), project_op(&s.h, "p-cotton", "cotton", &["github.com/example/shared"]), project_op(&s.h, "p-other", "other", &["github.com/example/shared"]), ], ); let logged = log( &s, json!({ "externalId": "one", "repoUrl": "git@github.com:example/tinmen.git" }), ); assert!(!logged.is_error, "{}", logged.text); assert_eq!( session_text(&s.h, "one", "project_id").as_deref(), Some("p-tinmen") ); assert_eq!( session_text(&s.h, "one", "repo_url").as_deref(), Some("github.com/example/tinmen") ); log( &s, json!({ "externalId": "many", "repoUrl": "https://github.com/example/shared" }), ); assert_eq!(session_text(&s.h, "many", "project_id"), None); log( &s, json!({ "externalId": "explicit", "repoUrl": "https://github.com/example/shared", "project": "cotton", }), ); assert_eq!( session_text(&s.h, "explicit", "project_id").as_deref(), Some("p-cotton") ); // Prompts carry the project too. log( &s, json!({ "externalId": "one", "repoUrl": "git@github.com:example/tinmen.git", "prompts": [{ "seq": 0, "ts": LAST_ACTIVE, "text": "hello" }], }), ); assert_eq!( one(&s.h, "SELECT project_id FROM cotton_prompts", Vec::new()) .and_then(|row| row.text("project_id").map(str::to_string)) .as_deref(), Some("p-tinmen") ); } #[test] fn does_not_overwrite_a_project_the_owner_reassigned() { let s = harness_with_token(); seed( &s.h, vec![ project_op(&s.h, "p-tinmen", "tinmen", &["github.com/example/tinmen"]), project_op(&s.h, "p-cotton", "cotton", &[]), ], ); log( &s, json!({ "repoUrl": "https://github.com/example/tinmen" }), ); run( &s.h, "UPDATE cotton_sessions SET project_id = 'p-cotton' WHERE external_id = ?", vec![SqlValue::Text(EXTERNAL_ID.to_string())], ); log( &s, json!({ "repoUrl": "https://github.com/example/tinmen" }), ); assert_eq!( session_text(&s.h, EXTERNAL_ID, "project_id").as_deref(), Some("p-cotton") ); } #[test] fn sets_turn_count_explicitly_when_passed_and_refuses_an_unknown_tool() { let s = harness_with_token(); log(&s, json!({ "turnCount": 7 })); assert_eq!(session_int(&s.h, EXTERNAL_ID, "turn_count"), Some(7)); log(&s, json!({})); assert_eq!(session_int(&s.h, EXTERNAL_ID, "turn_count"), Some(8)); let refused = log(&s, json!({ "tool": "vim" })); assert!(refused.is_error); assert!(refused.text.contains("claude-code"), "{}", refused.text); } #[test] fn truncates_an_over_long_summary_rather_than_failing_the_log_and_skips_blank_prompts() { let s = harness_with_token(); let answer = log( &s, json!({ "summary": "y".repeat(2500), "title": "t".repeat(200), "prompts": [ { "seq": 0, "ts": LAST_ACTIVE, "text": " " }, { "seq": 1, "ts": LAST_ACTIVE, "text": "real" }, ], }), ); assert!(!answer.is_error, "{}", answer.text); assert_eq!( units(&session_text(&s.h, EXTERNAL_ID, "summary").unwrap_or_default()), 2000 ); assert_eq!( units(&session_text(&s.h, EXTERNAL_ID, "title").unwrap_or_default()), 140 ); assert_eq!( prompts(&s.h) .into_iter() .map(|(seq, _, _)| seq) .collect::>(), vec![1] ); } // Measured, not theorised. Three redaction rules make their match LONGER — // ` Bearer abcdefgh` (16) becomes ` Bearer [redacted:bearer]` (25) — so a value // clipped to the cap FIRST and redacted after lands one character past it and // the row's CHECK refuses the whole call. That is not a lost line: the Stop // hook advances its cursor only on success, so the poisoned prompt is resent // every turn and fails every turn, and the session records nothing further, // for ever. #[test] fn a_prompt_at_the_cap_that_grows_when_redacted_still_lands() { let s = harness_with_token(); let answer = log( &s, json!({ "summary": format!("{} Bearer abcdefgh", "s".repeat(2000)), "prompts": [ { "seq": 0, "ts": LAST_ACTIVE, "text": format!("{} Bearer abcdefgh", "p".repeat(7976)) }, ], }), ); assert!(!answer.is_error, "{}", answer.text); let stored = prompts(&s.h); assert_eq!(stored.len(), 1); assert!(units(&stored[0].1) <= 8000, "{}", units(&stored[0].1)); assert!(!stored[0].1.contains("abcdefgh")); let summary = session_text(&s.h, EXTERNAL_ID, "summary").unwrap_or_default(); assert!(units(&summary) <= 2000, "{}", units(&summary)); assert!(!summary.contains("abcdefgh")); } #[test] fn a_prompt_seq_that_already_exists_is_skipped_never_a_failed_call() { let s = harness_with_token(); log( &s, json!({ "prompts": [{ "seq": 0, "ts": LAST_ACTIVE, "text": "the first ask" }] }), ); // The same seq again, with different text: the row that exists wins and // the call succeeds — `UNIQUE(session_id, seq)` never reaches the caller. let again = log( &s, json!({ "prompts": [{ "seq": 0, "ts": LAST_ACTIVE, "text": "a re-send of the same line" }], }), ); assert!(!again.is_error, "{}", again.text); assert_eq!( prompts(&s.h) .into_iter() .map(|(_, text, _)| text) .collect::>(), vec!["the first ask"] ); } #[test] fn lands_the_session_and_its_prompts_as_ops_the_phones_pull() { let s = harness_with_token(); log( &s, json!({ "prompts": [{ "seq": 0, "ts": LAST_ACTIVE, "text": "hello" }] }), ); let tables = op_tables(&s.h); assert!(tables.iter().any(|table| table == "cotton_sessions")); assert!(tables.iter().any(|table| table == "cotton_prompts")); } // ── list_sessions ─────────────────────────────────────────────────────────── fn log_three(s: &Seeded) { seed( &s.h, vec![project_op( &s.h, "p-tinmen", "tinmen", &["github.com/example/tinmen"], )], ); call_tool( &s.h, &s.secret, "log_session", json!({ "tool": "claude-code", "externalId": "a", "machine": "studio", "lastActiveAt": "2026-08-24T01:00:00.000Z", "repoUrl": "https://github.com/example/tinmen", "summary": "Rotated the litestream token.", "prompts": [ { "seq": 0, "ts": "2026-08-24T00:59:00.000Z", "text": "rotate the litestream token" }, ], }), ); call_tool( &s.h, &s.secret, "log_session", json!({ "tool": "codex", "externalId": "b", "machine": "laptop", "lastActiveAt": "2026-08-24T03:00:00.000Z", "summary": "Renamed the server.", "prompts": [{ "seq": 0, "ts": "2026-08-24T02:59:00.000Z", "text": "rename the server" }], }), ); call_tool( &s.h, &s.secret, "log_session", json!({ "tool": "claude-code", "externalId": "c", "machine": "studio", "lastActiveAt": "2026-08-24T02:00:00.000Z", "summary": "Nothing much.", }), ); } #[test] fn lists_newest_first_with_the_specs_fields_filtered_by_project_and_machine() { let s = harness_with_token(); log_three(&s); let result = call_tool(&s.h, &s.secret, "list_sessions", json!({})); let sessions = result["sessions"].as_array().expect("sessions").clone(); assert_eq!( sessions .iter() .map(|row| row["externalId"].as_str().unwrap_or_default()) .collect::>(), vec!["b", "c", "a"] ); let oldest = &sessions[2]; assert_eq!(oldest["tool"], "claude-code"); assert_eq!(oldest["machine"], "studio"); assert_eq!(oldest["project"], "tinmen"); assert_eq!(oldest["summary"], "Rotated the litestream token."); assert_eq!(oldest["promptCount"], json!(1)); assert_eq!(oldest["turnCount"], json!(1)); assert_eq!(listed(&s, json!({ "project": "tinmen" })), vec!["a"]); assert_eq!(listed(&s, json!({ "machine": "laptop" })), vec!["b"]); assert_eq!(listed(&s, json!({ "limit": 1 })), vec!["b"]); } #[test] fn searches_prompts_with_q_and_returns_the_sessions_that_hit_with_snippets() { let s = harness_with_token(); log_three(&s); let result = call_tool( &s.h, &s.secret, "list_sessions", json!({ "q": "litestream" }), ); let sessions = result["sessions"].as_array().expect("sessions").clone(); assert_eq!( sessions .iter() .map(|row| row["externalId"].as_str().unwrap_or_default()) .collect::>(), vec!["a"] ); let snippet = sessions[0]["hits"][0]["snippet"] .as_str() .expect("a snippet"); assert!(snippet.contains("litestream"), "{snippet}"); } // ── the whole conversation, and the model (v37) ───────────────────────────── #[test] fn lands_the_assistants_turns_beside_the_owners_and_a_turn_without_a_role_is_the_owners() { let s = harness_with_token(); let answer = log( &s, json!({ "prompts": [ { "seq": 3, "ts": LAST_ACTIVE, "text": "why is nothing listening" }, { "seq": 4, "ts": LAST_ACTIVE, "role": "assistant", "text": "The arm line was truncated." }, { "seq": 7, "ts": LAST_ACTIVE, "role": "user", "text": "fix it" }, ], }), ); assert!(!answer.is_error, "{}", answer.text); assert_eq!( turns(&s.h), vec![ ( 3, "user".to_string(), "why is nothing listening".to_string() ), ( 4, "assistant".to_string(), "The arm line was truncated.".to_string() ), (7, "user".to_string(), "fix it".to_string()), ] ); assert_eq!(only_session(&s)["promptCount"], json!(3)); } #[test] fn refuses_a_role_nobody_declared_in_words() { let s = harness_with_token(); let refused = log( &s, json!({ "prompts": [{ "seq": 1, "ts": LAST_ACTIVE, "role": "robot", "text": "beep" }] }), ); assert!(refused.is_error); assert!( refused.text.contains("role must be one of user, assistant"), "{}", refused.text ); } #[test] fn keeps_the_model_the_tool_reports_and_the_latest_wins() { let s = harness_with_token(); log(&s, json!({ "model": "claude-opus-4-1-20250805" })); assert_eq!(only_session(&s)["model"], "claude-opus-4-1-20250805"); log(&s, json!({ "model": "claude-fable-5-1" })); assert_eq!(only_session(&s)["model"], "claude-fable-5-1"); // A call that says nothing about the model leaves it alone. log(&s, json!({})); assert_eq!(only_session(&s)["model"], "claude-fable-5-1"); } // ── the title is the first prompt, set once ───────────────────────────────── #[test] fn takes_title_if_empty_on_the_turn_that_creates_the_row() { let s = harness_with_token(); log(&s, json!({ "titleIfEmpty": "write the v30 migration" })); assert_eq!(only_session(&s)["title"], "write the v30 migration"); } // The Stop hook sends the first prompt on every turn it can; the row's title is // set once and belongs to the session after that. #[test] fn never_overwrites_a_title_the_session_already_has() { let s = harness_with_token(); log(&s, json!({ "titleIfEmpty": "the first thing I typed" })); log(&s, json!({ "titleIfEmpty": "the second thing I typed" })); assert_eq!(only_session(&s)["title"], "the first thing I typed"); } #[test] fn lets_an_explicit_title_overwrite_because_that_one_was_meant() { let s = harness_with_token(); log(&s, json!({ "titleIfEmpty": "the first thing I typed" })); log(&s, json!({ "title": "v30, properly named" })); assert_eq!(only_session(&s)["title"], "v30, properly named"); } // ── a resumed session reopens its row ─────────────────────────────────────── /// When the SessionEnd hook stamped the row, and when the resume logs again. const ENDED: &str = "2026-09-08T09:00:00.000Z"; const RESUMED: &str = "2026-09-08T09:58:00.000Z"; fn ended_at(s: &Seeded) -> Option { session_text(&s.h, EXTERNAL_ID, "ended_at") } // The bug: `claude --resume` brings the same external id back, the Stop hook // logs turns again carrying no `endedAt`, and the row stayed ended for ever. #[test] fn a_session_that_logs_after_its_end_reopens() { let s = harness_with_token(); log(&s, json!({})); log(&s, json!({ "lastActiveAt": ENDED, "endedAt": ENDED })); assert_eq!(ended_at(&s).as_deref(), Some(ENDED)); log(&s, json!({ "lastActiveAt": RESUMED })); assert_eq!(ended_at(&s), None); assert_eq!(only_session(&s)["endedAt"], Value::Null); } // Only activity AFTER the end reopens it. A Stop hook's retry, or a push that // arrives out of order, lands at or before the stamp and leaves it alone. #[test] fn a_call_that_lands_at_or_before_the_end_leaves_the_end_alone() { let s = harness_with_token(); log(&s, json!({ "lastActiveAt": ENDED, "endedAt": ENDED })); log(&s, json!({ "lastActiveAt": ENDED })); assert_eq!(ended_at(&s).as_deref(), Some(ENDED)); log(&s, json!({ "lastActiveAt": "2026-09-08T08:59:59.999Z" })); assert_eq!(ended_at(&s).as_deref(), Some(ENDED)); } // An explicit `endedAt` is the SessionEnd hook speaking, and it outranks the // activity on the same call — including the one that ends a session which had // already been resumed once. #[test] fn an_explicit_ended_at_still_ends_the_session() { let s = harness_with_token(); log(&s, json!({ "lastActiveAt": ENDED, "endedAt": ENDED })); log(&s, json!({ "lastActiveAt": RESUMED })); assert_eq!(ended_at(&s), None); log(&s, json!({ "lastActiveAt": RESUMED, "endedAt": RESUMED })); assert_eq!(ended_at(&s).as_deref(), Some(RESUMED)); } // ── and never a row the helper owns ───────────────────────────────────────── // // A hosted row's life is the helper's: `queued → starting → running|idle| // waiting → ended`, and `session_birth::write_resume` is the one way back. // Clearing `ended_at` here while `state` stays `ended` is a half-alive card — // `list_sessions` shows it as running and Resume will not resume it. /// The hosted row this pair is about, ended by the helper, with the agent's /// own id on it — so `(tool, external_id)` lands here with nothing to fold. fn seed_ended_host_row(s: &Seeded, host_owned: i64) { seed_claim(&s.h, ROW, MAC, "ended", host_owned, CLAIMED_AT); run( &s.h, "UPDATE cotton_sessions SET external_id = ?, ended_at = ? WHERE id = ?", vec![ SqlValue::Text(EXTERNAL_ID.to_string()), SqlValue::Text(ENDED.to_string()), SqlValue::Text(ROW.to_string()), ], ); } #[test] fn a_late_hook_moves_a_host_owned_rows_heartbeat_and_nothing_else() { let s = harness_with_token(); seed_ended_host_row(&s, 1); // The Stop hook of a session the helper has already ended — later than the // end, and carrying no `endedAt` of its own. let answer = log(&s, json!({ "sessionId": ROW, "lastActiveAt": RESUMED })); assert!(!answer.is_error, "{}", answer.text); assert_eq!( ended_at(&s).as_deref(), Some(ENDED), "the END is the helper's to say" ); assert_eq!(session_text(&s.h, EXTERNAL_ID, "state").as_deref(), Some("ended")); assert_eq!( session_text(&s.h, EXTERNAL_ID, "last_active_at").as_deref(), Some(RESUMED), "the heartbeat still moves — the call happened" ); // An explicit `endedAt` is still the call speaking, on any row. log(&s, json!({ "sessionId": ROW, "lastActiveAt": RESUMED, "endedAt": RESUMED })); assert_eq!(ended_at(&s).as_deref(), Some(RESUMED)); } #[test] fn the_same_late_call_reopens_a_row_nobody_hosts() { let s = harness_with_token(); seed_ended_host_row(&s, 0); log(&s, json!({ "sessionId": ROW, "lastActiveAt": RESUMED })); assert_eq!(ended_at(&s), None, "an adopted row has no other way back"); assert_eq!( session_text(&s.h, EXTERNAL_ID, "last_active_at").as_deref(), Some(RESUMED) ); } // ── the window ────────────────────────────────────────────────────────────── // `read.sessions` used to ask for the WHOLE SET — a million — and the session // host adopts a row for every session it finds in an agent's own transcript // directory, so the phone downloaded four hundred and seventy-four sessions to // draw the dozen that were happening. `since` is what it asks with instead. #[test] fn since_keeps_the_sessions_that_did_something_at_or_after_it() { let s = harness_with_token(); let old = "2026-09-01T10:00:00.000Z"; let recent = "2026-09-08T10:00:00.000Z"; log(&s, json!({ "externalId": "old-one", "lastActiveAt": old })); log(&s, json!({ "externalId": "recent-one", "lastActiveAt": recent })); // No window: both. let mut everything = listed(&s, json!({})); everything.sort(); assert_eq!(everything, vec!["old-one", "recent-one"]); assert_eq!( listed(&s, json!({ "since": "2026-09-05T00:00:00.000Z" })), vec!["recent-one"] ); // The boundary is inclusive — a session that spoke exactly at the cutoff // is inside the window it names. let mut both = listed(&s, json!({ "since": old })); both.sort(); assert_eq!(both, vec!["old-one", "recent-one"]); // And nothing in a window that starts after everything. assert!(listed(&s, json!({ "since": "2026-10-01T00:00:00.000Z" })).is_empty()); } // A session that ENDED inside the window is in it: the queue's "done today" is // exactly that, and filtering on `ended_at` would drop everything still open. #[test] fn since_reads_the_last_activity_and_not_the_end() { let s = harness_with_token(); log( &s, json!({ "externalId": "ended-recently", "lastActiveAt": "2026-09-08T10:00:00.000Z", "endedAt": "2026-09-08T10:00:00.000Z" }), ); assert_eq!( listed(&s, json!({ "since": "2026-09-05T00:00:00.000Z" })), vec!["ended-recently"] ); } // Refused rather than ignored: a caller asking for a week and silently being // handed every session that ever ran is the failure the parameter prevents. #[test] fn refuses_a_since_that_is_not_an_instant() { let s = harness_with_token(); for bad in [json!("last tuesday"), json!(17), json!(true)] { let refused = call_tool_raw(&s.h, &s.secret, "list_sessions", json!({ "since": bad })); assert!(refused.is_error, "{bad} was accepted"); assert!( refused.text.contains("since must be an ISO 8601 timestamp"), "{}", refused.text ); } // Null is "no window", exactly as an absent key is. assert_eq!(listed(&s, json!({ "since": Value::Null })), Vec::::new()); } // ── who owns the terminal ─────────────────────────────────────────────────── // A screen has to be able to tell a session Cotton HOLDS from one it merely // adopted off a transcript: the second has no terminal, no stop and no // permission to answer, and drawing them the same way is what put four hundred // idle transcripts under a heading that said Running. #[test] fn says_whether_a_session_host_owns_the_terminal() { let s = harness_with_token(); log(&s, json!({})); assert_eq!(only_session(&s)["hostOwned"], json!(false)); run( &s.h, "UPDATE cotton_sessions SET host_owned = 1 WHERE external_id = ?", vec![SqlValue::Text(EXTERNAL_ID.to_string())], ); assert_eq!(only_session(&s)["hostOwned"], json!(true)); } // ── the backstop: a hook that finds no row adopts the claim it belongs to ──── // // The 2026-09-22 twin. The Mac claimed a queued session and the helper spawned // the agent; the agent's SessionStart hook called `log_session` eighteen // seconds later. The server's row had no `external_id` yet, so the call matched // nothing and CREATED A SECOND ROW — `host_owned = 0`, title "mac-c · cottondb // · main" — and that is the card the phone showed, with no Terminal tab and no // Stop. Every later turn landed on the twin. /// The Mac whose key signs the hooks' calls. const MAC: &str = "device:mac-c"; /// The moment the executor claimed the row — a minute before the hook fires. const CLAIMED_AT: &str = "2026-08-24T01:01:03.456Z"; fn admit_the_mac(h: &Harness, device_id: &str) { run( h, "INSERT INTO cotton_devices (id, workspace_id, device_id, name, platform, app_version, \ approved_at, approved_by_device, created_at, updated_at) \ VALUES (?,?,?,?,?,?,?,?,?,?)", vec![ SqlValue::Text(format!("device-row-{device_id}")), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(device_id.to_string()), SqlValue::Text("mac-c".to_string()), SqlValue::Text("mac".to_string()), SqlValue::Text("0.10.1".to_string()), SqlValue::Text(AT.to_string()), SqlValue::Text("self".to_string()), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string()), ], ); } /// A session the executor has CLAIMED on this Mac: host-owned, `starting`, and /// with no agent id on it yet. #[allow(clippy::too_many_arguments)] fn seed_claim( h: &Harness, id: &str, device_id: &str, state: &str, host_owned: i64, claimed_at: &str, ) { run( h, "INSERT INTO cotton_sessions \ (id, workspace_id, tool, machine, device_id, prompt, state, state_at, claimed_at, \ last_active_at, host_owned, created_at, updated_at) \ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", vec![ SqlValue::Text(id.to_string()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text("claude-code".to_string()), SqlValue::Text("mac-c".to_string()), SqlValue::Text(device_id.to_string()), SqlValue::Text("list the big feature todos".to_string()), SqlValue::Text(state.to_string()), SqlValue::Text(claimed_at.to_string()), SqlValue::Text(claimed_at.to_string()), SqlValue::Text(claimed_at.to_string()), SqlValue::Integer(host_owned), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string()), ], ); } fn log_as_the_mac(s: &Seeded, over: Value) -> support::mcp::ToolAnswer { support::mcp::call_tool_signed_by(&s.h, &s.secret, MAC, "log_session", with(over)) } fn sessions_count(h: &Harness) -> usize { all(h, "SELECT id FROM cotton_sessions", vec![]).len() } #[test] fn a_hook_naming_no_known_id_adopts_the_claim_this_mac_is_holding() { let s = harness_with_token(); admit_the_mac(&s.h, MAC); seed_claim(&s.h, "sess-1", MAC, "starting", 1, CLAIMED_AT); let answer = log_as_the_mac(&s, json!({})); assert!(!answer.is_error, "{}", answer.text); assert_eq!(sessions_count(&s.h), 1, "one session, one row — never a twin"); let row = one( &s.h, "SELECT id, external_id, host_owned, state FROM cotton_sessions", vec![], ) .expect("the session"); assert_eq!(row.text("id"), Some("sess-1")); assert_eq!( row.text("external_id"), Some(EXTERNAL_ID), "the row learns the agent's id, so every later turn lands on it" ); assert_eq!( row.int("host_owned"), Some(1), "Cotton still hosts it — which is what gives the card its Terminal tab and its Stop" ); assert_eq!(row.text("state"), Some("starting")); } #[test] fn a_second_turn_lands_on_the_adopted_row_by_its_id() { let s = harness_with_token(); admit_the_mac(&s.h, MAC); seed_claim(&s.h, "sess-1", MAC, "starting", 1, CLAIMED_AT); log_as_the_mac(&s, json!({})); log_as_the_mac(&s, json!({ "lastActiveAt": "2026-08-24T01:30:00.000Z" })); assert_eq!(sessions_count(&s.h), 1); } #[test] fn a_claim_on_another_mac_is_never_adopted() { let s = harness_with_token(); admit_the_mac(&s.h, MAC); seed_claim(&s.h, "sess-1", "device:someone-else", "starting", 1, CLAIMED_AT); log_as_the_mac(&s, json!({})); assert_eq!( sessions_count(&s.h), 2, "a row on another Mac is another Mac's session, whatever the hostname says" ); } #[test] fn a_session_nobody_hosts_is_never_adopted() { let s = harness_with_token(); admit_the_mac(&s.h, MAC); // `host_owned = 0` — a session found in an agent's own transcript, which // this call is not about. seed_claim(&s.h, "sess-1", MAC, "running", 0, CLAIMED_AT); log_as_the_mac(&s, json!({})); assert_eq!(sessions_count(&s.h), 2); } #[test] fn a_row_still_waiting_for_a_mac_is_never_adopted() { let s = harness_with_token(); admit_the_mac(&s.h, MAC); // `queued` — nothing has claimed it, so nothing on this machine is running // under it. seed_claim(&s.h, "sess-1", MAC, "queued", 1, CLAIMED_AT); log_as_the_mac(&s, json!({})); assert_eq!(sessions_count(&s.h), 2); } #[test] fn a_claim_older_than_the_window_is_never_adopted() { let s = harness_with_token(); admit_the_mac(&s.h, MAC); // Claimed an hour before this call: whatever that session is, it is not the // one announcing itself now. seed_claim(&s.h, "sess-1", MAC, "starting", 1, "2026-08-24T00:02:03.456Z"); log_as_the_mac(&s, json!({})); assert_eq!(sessions_count(&s.h), 2); } #[test] fn a_caller_with_no_device_identity_adopts_nothing() { let s = harness_with_token(); admit_the_mac(&s.h, MAC); seed_claim(&s.h, "sess-1", MAC, "starting", 1, CLAIMED_AT); // No `signed_by`: an assistant over a token knows a hostname it was told // and nothing else, and adopting on the strength of a string is how a // phantom session becomes a real one. log(&s, json!({})); assert_eq!(sessions_count(&s.h), 2); } // ── the mechanism: the hook NAMES the row, and it is a token call ──────────── // // The backstop above cannot fire for the hooks. `~/.claude/scripts/cotton- // session-{start,log,end}.sh` authenticate with `authorization: Bearer ` // and the MCP transport sets no `caller_device` for a token, so `device_id` is // NULL and `adoptable_here` declines at its first line — every time, for every // hosted session. That is why the twin of 2026-09-22 kept coming back. // // What replaces it is deterministic and has no race in it: the helper knows // `cotton_sessions.id` before it spawns the agent, puts it in the agent's // environment, and the hooks pass it back as `sessionId`. Both arrival orders // below end with ONE row. /// The row the phone created and the Mac was asked to run. const ROW: &str = "sess-named"; /// The phone's `queued` row, exactly as the SERVER holds it in the window the /// twin was born in: no agent id, no claim synced yet, `host_owned` not /// written. Nothing here may be a condition of adoption. fn seed_queued_row(h: &Harness, id: &str) { seed_claim(h, id, MAC, "queued", 0, CLAIMED_AT); } fn only_row(h: &Harness) -> cotton_store::driver::Row { one( h, "SELECT id, external_id, host_owned, state, machine FROM cotton_sessions", vec![], ) .expect("the session") } #[test] fn the_hook_lands_on_the_row_it_names_before_the_mac_s_claim_arrives() { let s = harness_with_token(); seed_queued_row(&s.h, ROW); // A TOKEN call — no `signed_by`, because that is what a hook is. let answer = log(&s, json!({ "sessionId": ROW })); assert!(!answer.is_error, "{}", answer.text); assert_eq!(sessions_count(&s.h), 1, "one session, one row — never a twin"); let row = only_row(&s.h); assert_eq!(row.text("id"), Some(ROW)); assert_eq!( row.text("external_id"), Some(EXTERNAL_ID), "the named row learns the agent's id, so every later turn lands on it" ); assert_eq!( row.text("state"), Some("queued"), "the hook says who it is, never what the Mac is doing" ); // AND THE MAC'S CLAIM IS NOW A NO-OP. It writes the same id onto the same // row, where before it hit `UNIQUE (tool, external_id)` against the twin // and parked as a rejected op. run( &s.h, "UPDATE cotton_sessions SET external_id = ?, state = 'starting', host_owned = 1 \ WHERE id = ?", vec![ SqlValue::Text(EXTERNAL_ID.to_string()), SqlValue::Text(ROW.to_string()), ], ); assert_eq!(sessions_count(&s.h), 1); } #[test] fn the_hook_lands_on_the_row_it_names_after_the_mac_s_claim_arrives() { let s = harness_with_token(); seed_claim(&s.h, ROW, MAC, "starting", 1, CLAIMED_AT); // The claim reached the server first, carrying the id the executor chose. run( &s.h, "UPDATE cotton_sessions SET external_id = ? WHERE id = ?", vec![ SqlValue::Text(EXTERNAL_ID.to_string()), SqlValue::Text(ROW.to_string()), ], ); let answer = log(&s, json!({ "sessionId": ROW })); assert!(!answer.is_error, "{}", answer.text); assert_eq!(sessions_count(&s.h), 1, "one session, one row — never a twin"); let row = only_row(&s.h); assert_eq!(row.text("id"), Some(ROW)); assert_eq!(row.text("external_id"), Some(EXTERNAL_ID)); assert_eq!(row.int("host_owned"), Some(1), "still Cotton's terminal"); assert_eq!( row.text("machine"), Some("studio"), "the machine follows the call, as it always has" ); } #[test] fn every_turn_of_a_named_session_lands_on_the_one_row() { let s = harness_with_token(); seed_queued_row(&s.h, ROW); log(&s, json!({ "sessionId": ROW })); log(&s, json!({ "sessionId": ROW, "lastActiveAt": "2026-08-24T01:30:00.000Z" })); log(&s, json!({ "sessionId": ROW, "endedAt": "2026-08-24T02:00:00.000Z" })); assert_eq!(sessions_count(&s.h), 1); assert_eq!(only_row(&s.h).text("id"), Some(ROW)); } #[test] fn a_row_id_this_database_does_not_hold_fails_the_call() { let s = harness_with_token(); // A caller that names a row claims to KNOW which row it is. An id naming // none of them is a caller mistaken about its own identity, and the // sentence is the only way it ever finds out. let answer = log(&s, json!({ "sessionId": "sess-that-never-was" })); assert!(answer.is_error, "{}", answer.text); assert!( answer.text.contains("no such session: sess-that-never-was"), "{}", answer.text ); assert_eq!(sessions_count(&s.h), 0, "and nothing was written"); } #[test] fn a_truncated_row_id_fails_rather_than_stamping_the_twin() { let s = harness_with_token(); // The 2026-09-25 shape: the hosted row the caller MEANT, and beside it the // adopted twin its agent id is on. seed_claim(&s.h, ROW, MAC, "running", 1, CLAIMED_AT); log(&s, json!({ "lastActiveAt": LAST_ACTIVE })); let twin = twin_id(&s.h); // The first eight characters of a row id are not a row id. Before this, // the name fell through, `(tool, external_id)` found the twin, and the // twin's heartbeat moved while the row the caller meant looked dead. let answer = log( &s, json!({ "sessionId": &ROW[..4], "lastActiveAt": "2026-08-24T03:00:00.000Z" }), ); assert!(answer.is_error, "{}", answer.text); assert!(answer.text.contains("no such session"), "{}", answer.text); assert_eq!( session_text(&s.h, EXTERNAL_ID, "last_active_at").as_deref(), Some(LAST_ACTIVE), "the twin's heartbeat is exactly where it was" ); assert_eq!(session_text(&s.h, EXTERNAL_ID, "id").as_deref(), Some(twin.as_str())); assert_eq!(sessions_count(&s.h), 2, "and no third row"); } #[test] fn a_row_already_logging_another_agent_is_left_alone() { let s = harness_with_token(); seed_claim(&s.h, ROW, MAC, "running", 1, CLAIMED_AT); run( &s.h, "UPDATE cotton_sessions SET external_id = 'the-agent-that-lives-here' WHERE id = ?", vec![SqlValue::Text(ROW.to_string())], ); // A second agent started BY HAND inside the hosted session's own terminal // inherits its environment, and so names a row that is not its own. Two // agents cannot share a row: it gets its own, and the hosted session's log // is untouched. let answer = log(&s, json!({ "sessionId": ROW })); assert!(!answer.is_error, "{}", answer.text); assert_eq!(sessions_count(&s.h), 2); assert_eq!( session_text(&s.h, "the-agent-that-lives-here", "id").as_deref(), Some(ROW), "the hosted session still holds its own row" ); } #[test] fn a_named_row_belonging_to_another_tool_is_never_written_to() { let s = harness_with_token(); seed_queued_row(&s.h, ROW); run( &s.h, "UPDATE cotton_sessions SET tool = 'codex' WHERE id = ?", vec![SqlValue::Text(ROW.to_string())], ); log(&s, json!({ "sessionId": ROW })); assert_eq!(sessions_count(&s.h), 2); assert_eq!( session_text(&s.h, EXTERNAL_ID, "tool").as_deref(), Some("claude-code") ); } // ── the twin already on the file, folded back ─────────────────────────────── // // The rows that split BEFORE the hooks carried `sessionId` are still split, // and the half the owner needs is the worse off: the hosted row has no // `external_id`, which is what `can_resume` requires, so Resume never appears // for the session it is about. The next call that NAMES the hosted row puts // the two back together. /// The twin, born the way the real one was: a call naming no row, which made /// its own adopted row and logged the session's turns onto it. fn log_the_twin(s: &Seeded) { log( s, json!({ "titleIfEmpty": "mac-c · cottondb · main", "prompts": [ { "seq": 0, "ts": LAST_ACTIVE, "text": "the first ask" }, { "seq": 1, "ts": LAST_ACTIVE, "text": "the second" }, ], }), ); } /// `(seq, text)` for one session's turns, in order. fn turns_of(h: &Harness, session_id: &str) -> Vec<(i64, String)> { all( h, "SELECT seq, text FROM cotton_prompts WHERE session_id = ? ORDER BY seq", vec![SqlValue::Text(session_id.to_string())], ) .iter() .map(|row| { ( row.int("seq").unwrap_or_default(), row.text("text").unwrap_or_default().to_string(), ) }) .collect() } /// The id of the row that is NOT the one the hooks name. fn twin_id(h: &Harness) -> String { one( h, "SELECT id FROM cotton_sessions WHERE id <> ?", vec![SqlValue::Text(ROW.to_string())], ) .and_then(|row| row.text("id").map(str::to_string)) .expect("the twin") } #[test] fn a_twin_folds_into_the_host_owned_row_the_call_names() { let s = harness_with_token(); seed_claim(&s.h, ROW, MAC, "ended", 1, CLAIMED_AT); // The helper ended the hosted row BEFORE the activity that folds into it — // the shape a reopen reads. run( &s.h, "UPDATE cotton_sessions SET ended_at = ? WHERE id = ?", vec![ SqlValue::Text(CLAIMED_AT.to_string()), SqlValue::Text(ROW.to_string()), ], ); log_the_twin(&s); assert_eq!(sessions_count(&s.h), 2, "the split this fold is about"); let twin = twin_id(&s.h); let answer = log( &s, json!({ "sessionId": ROW, "lastActiveAt": "2026-08-24T01:30:00.000Z" }), ); assert!(!answer.is_error, "{}", answer.text); assert_eq!(answer.json()["sessionId"], json!(ROW), "the call goes on as an update of the named row"); // THE AGENT'S ID IS ON THE HOSTED ROW — which is what `can_resume` reads, // and so what puts the owner's Resume button back on the card. assert_eq!( session_text(&s.h, EXTERNAL_ID, "id").as_deref(), Some(ROW), "`UNIQUE (tool, external_id)` — one row holds it, and it is this one" ); assert_eq!(session_int(&s.h, EXTERNAL_ID, "host_owned"), Some(1)); assert_eq!( session_text(&s.h, EXTERNAL_ID, "title").as_deref(), Some("mac-c · cottondb · main"), "the twin's title comes across, because the row it folds into had none" ); // AND THE FOLD DOES NOT RAISE THE DEAD. The call's activity is later than // the helper's end, and on a hosted row that changes nothing but the // heartbeat. assert_eq!(session_text(&s.h, EXTERNAL_ID, "state").as_deref(), Some("ended")); assert_eq!( session_text(&s.h, EXTERNAL_ID, "ended_at").as_deref(), Some(CLAIMED_AT) ); // THE TWIN IS WITHDRAWN, not deleted, and says where its session went. let row = one( &s.h, "SELECT external_id, state, ended_at, error, host_owned FROM cotton_sessions WHERE id = ?", vec![SqlValue::Text(twin.clone())], ) .expect("the twin"); assert_eq!(row.text("external_id"), None, "the id came off first"); assert_eq!(row.text("state"), Some("withdrawn")); assert!(row.text("ended_at").is_some()); assert_eq!( row.text("error"), Some(format!("folded into the session it was: {ROW}").as_str()) ); assert_eq!(row.int("host_owned"), Some(0), "it WAS adopted, and stays so"); // THE TURNS MOVED, in order and nowhere twice. assert_eq!( turns_of(&s.h, ROW), vec![ (0, "the first ask".to_string()), (1, "the second".to_string()) ] ); assert!(turns_of(&s.h, &twin).is_empty()); assert_eq!(session_int(&s.h, EXTERNAL_ID, "prompt_count"), Some(2)); // AND THE NEXT CALL IS A PLAIN UPDATE — nothing left to fold. let again = log( &s, json!({ "sessionId": ROW, "lastActiveAt": "2026-08-24T02:00:00.000Z" }), ); assert!(!again.is_error, "{}", again.text); assert_eq!(sessions_count(&s.h), 2); assert_eq!(session_text(&s.h, EXTERNAL_ID, "id").as_deref(), Some(ROW)); assert_eq!(turns_of(&s.h, ROW).len(), 2); assert_eq!( session_text(&s.h, EXTERNAL_ID, "last_active_at").as_deref(), Some("2026-08-24T02:00:00.000Z") ); assert_eq!( session_text(&s.h, EXTERNAL_ID, "ended_at").as_deref(), Some(CLAIMED_AT), "the continuation leaves the helper's end alone too" ); } #[test] fn a_named_row_nobody_hosts_never_takes_a_twin_s_session() { let s = harness_with_token(); // `host_owned = 0`: two adopted rows are two transcripts, and moving a // session between them gives nobody a terminal back. seed_claim(&s.h, ROW, MAC, "ended", 0, CLAIMED_AT); log_the_twin(&s); let twin = twin_id(&s.h); let answer = log(&s, json!({ "sessionId": ROW })); assert!(!answer.is_error, "{}", answer.text); assert_eq!( session_text(&s.h, EXTERNAL_ID, "id").as_deref(), Some(twin.as_str()), "the id stays where it was" ); assert_eq!(turns_of(&s.h, &twin).len(), 2); assert_eq!( one( &s.h, "SELECT count(*) AS n FROM cotton_sessions WHERE state = 'withdrawn'", vec![], ) .and_then(|row| row.int("n")), Some(0), "nothing was folded" ); } #[test] fn a_named_row_already_logging_another_agent_never_takes_a_twin_s_session() { let s = harness_with_token(); seed_claim(&s.h, ROW, MAC, "running", 1, CLAIMED_AT); run( &s.h, "UPDATE cotton_sessions SET external_id = 'the-agent-that-lives-here' WHERE id = ?", vec![SqlValue::Text(ROW.to_string())], ); log_the_twin(&s); let twin = twin_id(&s.h); let answer = log(&s, json!({ "sessionId": ROW })); assert!(!answer.is_error, "{}", answer.text); assert_eq!( session_text(&s.h, "the-agent-that-lives-here", "id").as_deref(), Some(ROW), "the hosted session still holds its own agent" ); assert_eq!( session_text(&s.h, EXTERNAL_ID, "id").as_deref(), Some(twin.as_str()) ); assert_eq!(turns_of(&s.h, &twin).len(), 2); } #[test] fn a_call_that_names_no_row_folds_nothing() { let s = harness_with_token(); seed_claim(&s.h, ROW, MAC, "ended", 1, CLAIMED_AT); log_the_twin(&s); let twin = twin_id(&s.h); // The hooks that made the twin in the first place: no `sessionId`, and no // way for the server to know which hosted row this agent is. Nothing may // move on a guess. let answer = log(&s, json!({ "lastActiveAt": "2026-08-24T01:30:00.000Z" })); assert!(!answer.is_error, "{}", answer.text); assert_eq!(sessions_count(&s.h), 2); assert_eq!( session_text(&s.h, EXTERNAL_ID, "id").as_deref(), Some(twin.as_str()) ); assert_eq!(turns_of(&s.h, &twin).len(), 2); assert!(turns_of(&s.h, ROW).is_empty()); assert_eq!( one( &s.h, "SELECT external_id, state FROM cotton_sessions WHERE id = ?", vec![SqlValue::Text(ROW.to_string())], ) .and_then(|row| row.text("external_id").map(str::to_string)), None, "the hosted row is exactly as it was" ); } // ── the project conversation (schema v31) ─────────────────────────────────── // // `create_session`, `get_session`, `open_project_conversation`, the two new // `list_sessions` filters and `log_session`'s task mirror. The rule these // share: every opening goes through ONE birth // (`cotton_tools::session_birth::write_session`), so a session asked for over // MCP is the same queued row the phone writes. /// A workspace with one project the conversation cases work in. fn with_project() -> Seeded { let s = harness_with_token(); seed(&s.h, vec![project_op(&s.h, "project-1", "cotton", &[])]); s } fn call(s: &Seeded, tool: &str, args: Value) -> support::mcp::ToolAnswer { call_tool_raw(&s.h, &s.secret, tool, args) } #[test] fn create_session_queues_a_thread_under_the_conversation_that_asked_for_it() { let s = with_project(); let conversation = call_tool( &s.h, &s.secret, "open_project_conversation", json!({ "project": "cotton" }), ); let parent = conversation["id"].as_str().expect("the conversation").to_string(); let answer = call_tool( &s.h, &s.secret, "create_session", json!({ "project": "cotton", "prompt": "Fix the flaky money test.\nThen open a pull request.", "parentSessionId": parent, }), ); assert_eq!(answer["state"], json!("queued")); assert_eq!(answer["kind"], json!("thread")); assert_eq!(answer["parentSessionId"], json!(parent)); // A queued row nothing has placed says why on `hold_reason`, and the // DISPATCHER writes it — so it is null at birth, not a guess. assert_eq!(answer["holdReason"], Value::Null); let id = answer["id"].as_str().expect("the row").to_string(); // The SAME row the phone would have written: host-owned, on no Mac yet, // with the prompt's first line as its title. let row = one( &s.h, "SELECT kind, parent_session_id, state, host_owned, title, prompt, project_id, \ device_id, chosen_by FROM cotton_sessions WHERE id = ?", vec![SqlValue::Text(id)], ) .expect("the thread"); assert_eq!(row.text("kind"), Some("thread")); assert_eq!(row.text("parent_session_id"), Some(parent.as_str())); assert_eq!(row.text("state"), Some("queued")); assert_eq!(row.int("host_owned"), Some(1)); assert_eq!(row.text("title"), Some("Fix the flaky money test.")); assert_eq!(row.text("project_id"), Some("project-1")); // ANY MAC: the owner named none, so the dispatcher decides and `chosen_by` // is still nobody's. assert!(row.text("device_id").is_none()); assert!(row.text("chosen_by").is_none()); } #[test] fn create_session_refuses_an_unknown_project_an_empty_prompt_and_a_parent_that_is_not_a_row() { let s = with_project(); let unknown = call( &s, "create_session", json!({ "project": "nowhere", "prompt": "do it" }), ); assert!(unknown.is_error); assert!(unknown.text.contains("nowhere"), "{}", unknown.text); let blank = call( &s, "create_session", json!({ "project": "cotton", "prompt": " " }), ); assert!(blank.is_error); assert!(blank.text.contains("prompt"), "{}", blank.text); let stranger = call( &s, "create_session", json!({ "project": "cotton", "prompt": "do it", "parentSessionId": "11111111-2222-4333-8444-999999999999", }), ); assert!(stranger.is_error); assert!( stranger.text.contains("no session with id"), "{}", stranger.text ); // Not one of the three landed. assert_eq!( session_count(&s.h), 0, "a refusal writes nothing, and a queue with a row nobody asked for is worse than none" ); } #[test] fn open_project_conversation_is_the_same_row_however_often_it_is_asked_for() { let s = with_project(); let first = call_tool( &s.h, &s.secret, "open_project_conversation", json!({ "project": "cotton" }), ); assert_eq!(first["created"], json!(true)); assert_eq!(first["kind"], json!("conversation")); assert_eq!(first["state"], json!("queued")); assert_eq!(first["project"], json!("cotton")); let again = call_tool( &s.h, &s.secret, "open_project_conversation", json!({ "project": "cotton" }), ); assert_eq!(again["id"], first["id"], "one conversation per project"); assert_eq!(again["created"], json!(false)); assert_eq!( session_count(&s.h), 1, "the second call opened nothing — the file holds one conversation per project" ); // The row is what the design says it is: host-owned, the owner's, on any // Mac, opened with the standing prompt that names its own id. let id = first["id"].as_str().expect("the row").to_string(); let row = one( &s.h, "SELECT kind, host_owned, chosen_by, requested_device_id, prompt, title \ FROM cotton_sessions WHERE id = ?", vec![SqlValue::Text(id.clone())], ) .expect("the conversation"); assert_eq!(row.text("kind"), Some("conversation")); assert_eq!(row.int("host_owned"), Some(1)); assert_eq!(row.text("chosen_by"), Some("owner")); assert!( row.text("requested_device_id").is_none(), "any Mac — a conversation is the project's own, not work placed on a machine" ); assert_eq!(row.text("title"), Some("Cotton — conversation")); let prompt = row.text("prompt").expect("the standing prompt").to_string(); assert!(prompt.contains(&id), "the conversation is told which row it is"); assert!(prompt.contains("create_session"), "{prompt}"); } /// RULE: a project's conversation is born with the project's repository, the same one its threads carry. // Without it the Mac that claims the conversation has no folder to start the // agent in and closes it `failed` ("this session names no repository"), while // the phone goes on showing the owner's first message as waiting. #[test] fn a_conversation_carries_the_projects_repository_as_its_threads_do() { let s = harness_with_token(); seed( &s.h, vec![project_op( &s.h, "project-1", "cotton", &["https://git.example.test/owner/thing", "https://git.example.test/owner/other"], )], ); let conversation = call_tool( &s.h, &s.secret, "open_project_conversation", json!({ "project": "cotton" }), ); let thread = call_tool( &s.h, &s.secret, "create_session", json!({ "project": "cotton", "prompt": "the thread" }), ); for answer in [&conversation, &thread] { let id = answer["id"].as_str().expect("the row"); assert_eq!( repo_of(&s.h, id).as_deref(), Some("https://git.example.test/owner/thing"), "{answer}" ); } // A project with no repository leaves it null — there is none to carry. let bare = with_project(); let conversation = call_tool( &bare.h, &bare.secret, "open_project_conversation", json!({ "project": "cotton" }), ); let id = conversation["id"].as_str().expect("the row"); assert_eq!(repo_of(&bare.h, id), None); } fn repo_of(h: &Harness, id: &str) -> Option { one( h, "SELECT repo_url FROM cotton_sessions WHERE id = ?", vec![SqlValue::Text(id.to_string())], ) .and_then(|row| row.text("repo_url").map(str::to_string)) } #[test] fn list_sessions_answers_a_conversations_threads_and_says_what_each_row_is() { let s = with_project(); let conversation = call_tool( &s.h, &s.secret, "open_project_conversation", json!({ "project": "cotton" }), ); let parent = conversation["id"].as_str().expect("the row").to_string(); let child = call_tool( &s.h, &s.secret, "create_session", json!({ "project": "cotton", "prompt": "the thread", "parentSessionId": parent }), ); let child_id = child["id"].as_str().expect("the row").to_string(); // A standalone, opened by nobody. call_tool( &s.h, &s.secret, "create_session", json!({ "project": "cotton", "prompt": "on its own" }), ); let threads = call_tool( &s.h, &s.secret, "list_sessions", json!({ "parent": parent }), ); let rows = threads["sessions"].as_array().expect("the list"); assert_eq!(rows.len(), 1, "one conversation's threads, and nothing else"); assert_eq!(rows[0]["id"], json!(child_id)); assert_eq!(rows[0]["kind"], json!("thread")); assert_eq!(rows[0]["parentSessionId"], json!(parent)); assert_eq!(rows[0]["tasksDone"], json!(0)); assert_eq!(rows[0]["tasksTotal"], json!(0)); let conversations = call_tool( &s.h, &s.secret, "list_sessions", json!({ "kind": "conversation" }), ); let rows = conversations["sessions"].as_array().expect("the list"); assert_eq!(rows.len(), 1); assert_eq!(rows[0]["id"], json!(parent)); let every = call_tool(&s.h, &s.secret, "list_sessions", json!({})); assert_eq!(every["sessions"].as_array().expect("the list").len(), 3); // A word the file does not know is refused rather than ignored. let wrong = call(&s, "list_sessions", json!({ "kind": "chat" })); assert!(wrong.is_error); assert!(wrong.text.contains("conversation, thread"), "{}", wrong.text); } #[test] fn log_session_mirrors_a_task_list_and_replaces_it_whole() { let s = harness_with_token(); log( &s, json!({ "prompts": [{ "seq": 0, "ts": LAST_ACTIVE, "text": "start" }], "tasks": [ { "seq": 0, "text": "read the design", "state": "done" }, { "seq": 1, "text": "write the migration", "state": "active" }, { "seq": 2, "text": "write the tests", "state": "open" }, ], }), ) .json(); let tasks = all( &s.h, "SELECT seq, text, state FROM cotton_session_tasks ORDER BY seq", Vec::new(), ); assert_eq!(tasks.len(), 3); assert_eq!(tasks[0].text("state"), Some("done")); assert_eq!(tasks[1].text("text"), Some("write the migration")); // THE SECOND MIRROR REPLACES THE FIRST. A task list is one value: the // agent dropped seq 2 and finished seq 1, and the row says exactly that // rather than the union of both tellings. let answer = log( &s, json!({ "tasks": [ { "seq": 0, "text": "read the design", "state": "done" }, { "seq": 1, "text": "write the migration", "state": "done" }, ], }), ) .json(); assert_eq!(answer["tasksDone"], json!(2)); assert_eq!(answer["tasksTotal"], json!(2)); let tasks = all( &s.h, "SELECT seq, state FROM cotton_session_tasks ORDER BY seq", Vec::new(), ); assert_eq!(tasks.len(), 2, "the dropped task is gone, not kept"); assert_eq!(tasks[1].text("state"), Some("done")); // AND A CALL THAT SAYS NOTHING ABOUT TASKS LEAVES THE LIST ALONE — the // Stop hook logs a turn every turn, and most of them carry no mirror. log(&s, json!({ "summary": "still going" })).json(); assert_eq!( all( &s.h, "SELECT seq FROM cotton_session_tasks ORDER BY seq", Vec::new() ) .len(), 2 ); // An empty array is a real answer: the agent has no tasks left. log(&s, json!({ "tasks": [] })).json(); assert_eq!( all( &s.h, "SELECT seq FROM cotton_session_tasks ORDER BY seq", Vec::new() ) .len(), 0 ); } /// A SESSION LOG MUST NEVER FAIL, the task mirror included. #[test] fn a_task_the_file_would_refuse_is_absorbed_rather_than_failing_the_log() { let s = harness_with_token(); let answer = log( &s, json!({ "tasks": [ { "seq": 0, "text": "x".repeat(900), "state": "open" }, { "seq": 1, "text": "a task", "state": "blocked" }, { "seq": -3, "text": "before the beginning", "state": "open" }, { "seq": 2, "text": " ", "state": "open" }, { "seq": 0, "text": "a second telling of position zero", "state": "done" }, "not a task", ], }), ); assert!(!answer.is_error, "{}", answer.text); let tasks = all( &s.h, "SELECT seq, text, state FROM cotton_session_tasks ORDER BY seq", Vec::new(), ); assert_eq!(tasks.len(), 2, "two survive: positions 0 and 1"); assert_eq!( tasks[0].text("text").expect("the text").chars().count(), 500, "truncated to the file's cap, never refused over it" ); assert_eq!( tasks[0].text("state"), Some("open"), "the FIRST telling of a position wins, exactly as a prompt's does" ); assert_eq!( tasks[1].text("state"), Some("open"), "a word the file does not know reads as `open`" ); } #[test] fn get_session_answers_the_row_its_turns_and_its_tasks() { let s = with_project(); log( &s, json!({ "project": "cotton", "summary": "did the thing", "prompts": [ { "seq": 0, "ts": LAST_ACTIVE, "role": "user", "text": "do the thing" }, { "seq": 1, "ts": LAST_ACTIVE, "role": "assistant", "text": "done" }, ], "tasks": [ { "seq": 0, "text": "the first task", "state": "done" }, { "seq": 1, "text": "the second task", "state": "active" }, ], }), ) .json(); let id = session_text(&s.h, EXTERNAL_ID, "id").expect("the session"); let answer = call_tool(&s.h, &s.secret, "get_session", json!({ "sessionId": id })); assert_eq!(answer["project"], json!("cotton")); assert_eq!(answer["summary"], json!("did the thing")); assert_eq!(answer["kind"], json!("thread")); assert_eq!(answer["parentSessionId"], Value::Null); let turns = answer["prompts"].as_array().expect("the turns"); assert_eq!(turns.len(), 2); assert_eq!(turns[0]["role"], json!("user")); assert_eq!(turns[1]["text"], json!("done")); let tasks = answer["tasks"].as_array().expect("the tasks"); assert_eq!(tasks.len(), 2, "in the agent's own order"); assert_eq!(tasks[0]["seq"], json!(0)); assert_eq!(tasks[1]["state"], json!("active")); assert_eq!(answer["tasksDone"], json!(1)); assert_eq!(answer["tasksTotal"], json!(2)); let missing = call( &s, "get_session", json!({ "sessionId": "11111111-2222-4333-8444-000000000000" }), ); assert!(missing.is_error); assert!(missing.text.contains("no session with id"), "{}", missing.text); } // ── a session's todo in another database (schema v53) ─────────────────────── /// Another database the owner holds — only ever named, never opened here. const OTHER_DATABASE: &str = "33333333-3333-4333-8333-333333333333"; /// A todo id this database does not hold. const FOREIGN_TODO: &str = "44444444-4444-4444-8444-444444444444"; fn session_todo(h: &Harness, id: &str) -> (Option, Option) { let row = one( h, "SELECT todo_id, todo_database FROM cotton_sessions WHERE id = ?", vec![SqlValue::Text(id.to_string())], ) .expect("the session"); ( row.text("todo_id").map(str::to_string), row.text("todo_database").map(str::to_string), ) } /// RULE: A session started from another database's todo stores that database beside the todo's id, and keeps the id though this database holds no such todo. #[test] fn session_started_from_another_databases_todo_keeps_its_todo_link() { let s = with_project(); let answer = call_tool( &s.h, &s.secret, "create_session", json!({ "project": "cotton", "prompt": "Pick up the team's todo.", "todoId": FOREIGN_TODO, "todoDatabase": OTHER_DATABASE, }), ); let id = answer["id"].as_str().expect("the row"); assert_eq!( session_todo(&s.h, id), (Some(FOREIGN_TODO.to_string()), Some(OTHER_DATABASE.to_string())) ); } /// RULE: A session handed a todo this database does not hold, with no database named, is refused and writes no row — todo_id is no longer a foreign key, so the handler is what refuses it; a todo this database holds is stored with no database. #[test] fn create_session_refuses_a_todo_this_database_does_not_hold() { let s = with_project(); let refused = call( &s, "create_session", json!({ "project": "cotton", "prompt": "Do the todo.", "todoId": FOREIGN_TODO }), ); assert!(refused.is_error, "{}", refused.text); assert_eq!(session_count(&s.h), 0); let todo = call_tool(&s.h, &s.secret, "create_todo", json!({ "title": "A todo here" }))["id"] .as_str() .expect("the todo") .to_string(); let own = s.h.workspace_id.clone(); let answer = call_tool( &s.h, &s.secret, "create_session", json!({ "project": "cotton", "prompt": "Do the todo.", "todoId": todo, "todoDatabase": own }), ); let id = answer["id"].as_str().expect("the row"); assert_eq!(session_todo(&s.h, id), (Some(todo), None), "naming this database is naming none"); } /// RULE: get_session answers a todo named in another database — todoId and todoDatabase — though this database holds no such todo, because the database column says where it is. #[test] fn get_session_reads_the_todo_from_its_named_database() { let s = with_project(); let answer = call_tool( &s.h, &s.secret, "create_session", json!({ "project": "cotton", "prompt": "Pick up the team's todo.", "todoId": FOREIGN_TODO, "todoDatabase": OTHER_DATABASE, }), ); let id = answer["id"].as_str().expect("the row"); let read = call_tool(&s.h, &s.secret, "get_session", json!({ "sessionId": id })); assert_eq!(read["todoId"], json!(FOREIGN_TODO)); assert_eq!(read["todoDatabase"], json!(OTHER_DATABASE)); }