Cotton code
1746 lines · 74.1 KB · RustRaw
//! `log_session` and `list_sessions` — the sessions block of//! `packages/server/src/mcp/records.ts` (lines ~7384-7647).//!//! A SESSION LOG MUST NEVER FAIL. The Stop hook advances its cursor only on//! success, so a call that refuses is resent every turn and fails every turn://! the session records nothing further, for ever, and the hook is mute by//! design. That is why every cap here TRUNCATES rather than refusing, why a//! blank prompt is skipped rather than rejected, and why a `seq` that already//! exists is a no-op rather than a failed call.//!//! REDACT, THEN CLIP — never the other way round. Three of `redact_secrets`'//! rules LENGTHEN their match (`Bearer <8 chars>` → `Bearer//! [redacted:bearer]` is 15 → 24), so a value already at the cap grows past it//! and the row's CHECK refuses the whole call; and clipping first can cut a//! token in half, leaving a fragment no rule matches at the tail. The//! validator does it on the way in and [`redacted_to_fit`] does it again at//! the write, so the guarantee belongs to the WRITE rather than to one//! caller's argument parsing.use crate::mcp::writer::Retract;use std::collections::{BTreeMap, HashSet};use cotton_core::rules::memory_briefing::normalize_repo_url;use cotton_core::transforms::redact::redact_secrets;use cotton_store::protocol::derived_id::{    prompt_id as derived_prompt_id, session_id as derived_session_id,    session_task_id as derived_task_id,};use cotton_store::search::to_match_query;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::common::{    bounded_limit, fail, flag, insert_row, iso_of_ms, iso_timestamp, maybe_row, now_iso,    optional_string, or_null, parse_ms, project_filter, require_string, rows, text, update_row,    ProjectFilter, Valid,};use crate::mcp::handlers::records_2::memory::{memory_projects, MemoryProject};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Order, Query};use crate::session_echo::{absorbing, DeliveredMessage, TYPED_KINDS};const SESSION_COLUMNS: &[&str] = &[    "id",    "project_id",    "tool",    "external_id",    "machine",    "device_id",    "account",    "repo_url",    "branch",    "cwd",    "started_at",    "last_active_at",    "ended_at",    "summary",    "title",    "model",    "shipped",    "turn_count",    "prompt_count",    "transcript_ref",    // Version 14 — what the session is DOING, as the agent's own hooks report    // it through the session host.    "state",    "state_at",    "waiting_kind",    "waiting_ref",    "last_line",    // Whether a session host OWNS this session's terminal, or it was adopted    // from an agent's own transcript. An adopted row has no terminal, no stop    // and no permission to answer, so a screen that draws it beside a hosted    // one has to be able to tell them apart.    "host_owned",    // Version 23 — the launch, folded in. A `queued` row is a session nobody    // has started yet: `prompt` is what it will open with,    // `requested_device_id` is the Mac the owner asked for (NULL = any Mac)    // and `hold_reason` is the written sentence saying why it is still here.    "prompt",    "requested_device_id",    "chosen_by",    "hold_reason",    "error",    "todo_id",    // Version 53 — the database `todo_id` is in when it is not this one.    "todo_database",    // Version 31 — the project conversation. `kind` says whether this row IS    // a project's standing conversation or one of the threads it opens, and    // `parent_session_id` names the conversation that opened it.    "kind",    "parent_session_id",];/// `cotton_session_tasks` — a session's mirrored task list.pub const SESSION_TASKS_TABLE: &str = "cotton_session_tasks";/// The three words a task list has (schema v31).const TASK_STATES: &[&str] = &["open", "active", "done"];/// A task's text cap, mirrored from the row's CHECK — truncated to, never/// refused over, for the reason the module note gives.const TASK_TEXT_MAX: usize = 500;/// `SESSION_TOOLS` — which agent tool a session ran in. `other` is the seam/// for a tool with no adapter yet.const SESSION_TOOLS: &[&str] = &[    "claude-code",    "codex",    "kimi",    "gemini",    "opencode",    "other",];/// What a session IS (schema v31) — the file's own CHECK, said here as a/// sentence a caller reads.pub const SESSION_KINDS: &[&str] = &["conversation", "thread"];/// `TURN_ROLES` — who said a turn (schema v37).const TURN_ROLES: &[&str] = &["user", "assistant"];/// Size caps mirrored from the sessions/prompts CHECKs — the server truncates/// to these rather than refusing.const SESSION_SUMMARY_MAX: usize = 2000;const SESSION_TITLE_MAX: usize = 140;const PROMPT_TEXT_MAX: usize = 8000;const SESSION_MODEL_MAX: usize = 80;// ── the shipped links ───────────────────────────────────────────────────────/// PR and commit links — what a session recap says it shipped.////// The TypeScript's `SHIPPED_URL_RE` with the `g` flag; the pattern is ported/// as-is, and the lazy `+?` before `/(?:pull|commit)/` is load-bearing (a URL/// with two `/pull/` segments must match at the first).fn shipped_in(summary: Option<&str>) -> Vec<String> {    static PATTERN: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {        regex::Regex::new(            r#"https?://github\.com/[^\s()<>\[\]"']+?/(?:pull|commit)/[^\s()<>\[\]"'.,;]+"#,        )        .expect("a valid pattern")    });    let Some(summary) = summary else {        return Vec::new();    };    let mut seen: Vec<String> = Vec::new();    for found in PATTERN.find_iter(summary) {        let url = found.as_str().to_string();        if !seen.contains(&url) {            seen.push(url);        }    }    seen}/// Which project a session belongs on: an explicit slug wins; otherwise the/// one active project listing the repo; `None` when none or several match —/// the phone can reassign.fn session_project(    projects: &[MemoryProject],    project: Option<&str>,    repo_url: Option<&str>,) -> Result<Option<String>, ToolFailure> {    if let Some(slug) = project {        let refs: Vec<crate::mcp::handlers::common::ProjectRef> = projects            .iter()            .map(|project| crate::mcp::handlers::common::ProjectRef {                id: project.id.clone(),                slug: project.slug.clone(),                status: project.status.clone(),            })            .collect();        return crate::mcp::handlers::common::resolve_project(&refs, Some(slug));    }    let Some(repo_url) = repo_url else {        return Ok(None);    };    let active: Vec<MemoryProject> = projects        .iter()        .filter(|project| project.status == "active")        .cloned()        .collect();    let matched = cotton_core::rules::memory_briefing::projects_for_repo(&active, repo_url);    Ok((matched.len() == 1).then(|| matched[0].id.clone()))}/// Redact, THEN clip to the column's CHECK — never the other way round. See/// the module note.fn redacted_to_fit(value: &str, max: usize) -> String {    let safe = redact_secrets(value);    utf16_clip(&safe, max)}/// `String.prototype.slice(0, max)` — UTF-16 code units, because that is what/// a JavaScript length is and what the column's CHECK was written against.fn utf16_clip(value: &str, max: usize) -> String {    let units: Vec<u16> = value.encode_utf16().collect();    if units.len() <= max {        return value.to_string();    }    String::from_utf16_lossy(&units[..max])}/// Is this call a session coming BACK? True only when the row already carries/// an `ended_at` and the call's `lastActiveAt` is strictly later than it — a/// session logging activity after its own end is, by definition, not over. A/// late call that lands at or before the end (a retried Stop hook, an out-of/// order push) leaves the stamp alone.////// NEVER A HOST-OWNED ROW. The helper owns a hosted session's life —/// `queued → starting → running|idle|waiting → ended`, and/// `session_birth::write_resume` is the one way back to `queued` — and this/// branch clears `ended_at` WITHOUT touching `state`. On a hosted row that is/// a half-alive card: `state = 'ended'` with no end stamp, which/// `list_sessions` shows as running and `can_resume` will not resume. A/// late hook arriving after the helper ended the session still moves/// `last_active_at`; the END is the helper's to say, or an explicit `endedAt`/// on the call.fn reopens(row: &Map<String, Value>, last_active_at: &str) -> bool {    if flag(row, "host_owned") {        return false;    }    match (        text(row, "ended_at").as_deref().and_then(parse_ms),        parse_ms(last_active_at),    ) {        (Some(ended), Some(active)) => active > ended,        _ => false,    }}// ── log_session ─────────────────────────────────────────────────────────────/// Which DEVICE this call came from — proved, never guessed (v13).////// The caller's own credential device id, and only when it still names a LIVE/// row in this database's device list. Two "no"s and both are deliberate:////// - a caller with no device identity answers NULL. The MCP transport///   authenticates a token, so an assistant logging a session genuinely does///   not know which device it is, and `machine` — a hostname the caller typed —///   is the only thing it can say. Matching that string to a device NAME would///   be a guess written into the file, and a guessed hostname already costs the///   owner a phantom row — which is what v14 retired `cotton_machines` over./// - a REVOKED key answers NULL too. The row survives revocation on purpose, so///   a device that was cut off is still in `list_devices` — but attributing new///   work to it would say a key that may no longer open this database is///   opening it.fn caller_device_id(ctx: &mut Ctx<'_>) -> Result<Option<String>, ToolFailure> {    let Some(device_id) = ctx.caller_device.map(str::to_string) else {        return Ok(None);    };    let row = maybe_row(        ctx,        &Query::on("cotton_devices")            .columns(&["device_id"])            .eq("device_id", device_id.clone())            .filter(Filter::IsNull("revoked_at".to_string())),    )?;    Ok(row.map(|_| device_id))}/// How long a claimed session may sit with no id before a hook naming this/// machine stops being the same session.////// FIVE MINUTES. The executor claims the row, asks the helper to spawn, and the/// agent's SessionStart hook fires within seconds of the process existing; a/// cold Mac reading a few hundred megabytes off disk is the slow end of that,/// and the spawn itself gives up after thirty seconds/// (`cotton_client::session_host::executor::SPAWN_ANSWER_MS`). Five minutes is/// far past both, and short enough that a session started BY HAND an hour later/// cannot be mistaken for the queued one.pub const ADOPT_A_CLAIM_WITHIN_MS: i64 = 5 * 60 * 1_000;/// The row this call is almost certainly about, where `(tool, external_id)`/// matched nothing.////// **What this is for.** The Mac claims a queued session and the claim now/// carries the agent's own session id, so the ordinary case never reaches here./// Two cases do: Codex mints its id itself and the row cannot carry one until/// the helper answers, and the Mac's write can simply be late — the pass wakes/// the sync, but a Mac that lost the network for a minute still has the agent/// running and talking. In both, a `log_session` that created a row would/// create a TWIN: two cards for one session, `host_owned = 0` on the one the/// phone shows, so no Terminal tab and no Stop — which is exactly what the/// owner saw on 2026-09-22.////// **This is the FALLBACK, not the mechanism.** A session Cotton started says/// which row it is: the helper knows the row id before it spawns the agent and/// puts it in the agent's environment, so the hooks name it — see/// [`named_row`]. This is what is left for a session started BY HAND, or by an/// agent whose environment lost the variable, and it only ever fires for a/// caller that signs with a device key. **The MCP transport authenticates a/// TOKEN and sets no `caller_device`** (`crate::mcp::dispatch`), and the hooks/// authenticate with a token, so for the hooks themselves this never fires —/// which is exactly why naming the row had to replace guessing it.////// **What makes it safe to adopt.** All five together, and none of them alone:/// the row is on THIS DEVICE (a caller with no device identity adopts/// nothing), it is `host_owned` — Cotton started it — its state is `starting`/// or `running`, it has NO id yet, and it was claimed within/// [`ADOPT_A_CLAIM_WITHIN_MS`]. The newest claim wins, which is the only/// ordering that can be wrong, and is wrong only for two sessions claimed on/// one Mac inside the same five minutes with neither id written — while the/// executor claims and spawns them one at a time.fn adoptable_here(    ctx: &mut Ctx<'_>,    args: &LogSessionArgs,    device_id: Option<&str>,) -> Result<Option<Map<String, Value>>, ToolFailure> {    let Some(device_id) = device_id else {        // No device identity: `machine` is a hostname the caller typed, and        // adopting a row on the strength of a string is how a phantom session        // becomes a real one.        return Ok(None);    };    let Some(since) = parse_ms(&args.last_active_at).map(|ms| iso_of_ms(ms - ADOPT_A_CLAIM_WITHIN_MS))    else {        return Ok(None);    };    maybe_row(        ctx,        &Query::on("cotton_sessions")            .columns(SESSION_COLUMNS)            .eq("tool", args.tool.clone())            .eq("device_id", device_id.to_string())            .eq("host_owned", 1_i64)            .filter(Filter::In(                "state".to_string(),                vec![                    SqlValue::Text("starting".to_string()),                    SqlValue::Text("running".to_string()),                ],            ))            .filter(Filter::IsNull("external_id".to_string()))            .filter(Filter::Gte("claimed_at".to_string(), SqlValue::Text(since)))            .order_by("claimed_at", Order::Desc)            .limit(1),    )}/// The row the caller NAMED — and a name that matches NOTHING is an ERROR.////// **This is how a session Cotton started stays one row.** The phone creates/// the row `queued`; the Mac's executor claims it and asks the helper to spawn/// the agent — and it knows `cotton_sessions.id` the whole time, long before/// any hook can fire. So the helper puts that id in the agent's environment/// (`COTTON_SESSION_ROW_ID`), the agent's hooks pass it back as `sessionId`,/// and this call lands on the row the owner is already looking at. No race, no/// hostname match, no device key: the id IS the proof, because the only way a/// caller can know a live row's uuid is that the helper told it.////// **Why it is not enough to match the claim.** The twin of 2026-09-22 was/// made in the seconds between the Mac claiming a row and that claim REACHING/// the server: the SessionStart hook goes straight to the server and is/// routinely first. In that window the server's copy of the row is still/// `queued`, with no `external_id`, no `machine` and `host_owned` not yet/// written — so neither the state, nor the device, nor `host_owned` can be a/// condition here without putting the hole straight back. What IS required:/// the row exists, it is the same TOOL, and its id is free.////// **`(tool, external_id)` is checked FIRST, always.** That pair is the table's/// UNIQUE index. A named row whose id is free, while another row already holds/// this agent's id, would be a write the index refuses — a rejected op that/// parks for ever. So a stale or inherited `COTTON_SESSION_ROW_ID` (a second/// agent started by hand inside a hosted session's own terminal, which/// inherits its environment) costs nothing: its own row is found by its own id/// and this never runs. For the same reason a named row that already carries a/// DIFFERENT agent's id is declined rather than refused — two agents cannot/// share a row, and a refusal here would mute a session's log for ever, which/// is the one thing this module may never do.fn named_row(    ctx: &mut Ctx<'_>,    args: &LogSessionArgs,) -> Result<Option<Map<String, Value>>, ToolFailure> {    let Some(row_id) = args.session_row_id.as_deref() else {        return Ok(None);    };    let Some(row) = maybe_row(        ctx,        &Query::on("cotton_sessions")            .columns(SESSION_COLUMNS)            .eq("id", row_id.to_string()),    )?    else {        // A NAME THAT MATCHES NOTHING IS AN ERROR — the one refusal this        // module allows, and the module note's "never fail" is why it has to        // be. A caller that names a row is a caller that KNOWS which row it        // is, so an id naming none of them is a caller mistaken about its own        // identity: on 2026-09-25 a truncated id (`b337176a`, the first eight        // characters of a uuid) fell through to `(tool, external_id)`, found        // the adopted twin and stamped ITS `last_active_at` — the hosted row        // the caller meant looked dead while the session was running. Rows are        // named by their FULL id; a prefix is not a name. Silence here is        // worse than a refusal, because the refusal is a sentence the caller        // can fix and the silence is a card that lies.        return Err(ToolFailure::new(format!(            "no such session: {row_id} — sessionId is a session's full row id, never a prefix"        )));    };    if text(&row, "tool").as_deref() != Some(args.tool.as_str()) {        // A `claude-code` hook cannot write its id onto a `codex` row.        return Ok(None);    }    match text(&row, "external_id") {        None => Ok(Some(row)),        Some(existing) if existing == args.external_id => Ok(Some(row)),        // A row that is NOT this caller's FALLS THROUGH, on purpose: it is        // declined here and `(tool, external_id)` decides. A resumed session        // under a NEW agent id inherits the old `COTTON_SESSION_ROW_ID` from        // the terminal it runs in, and its own row — the one its own id is on        // — must still take the turn. Only "no row at all" is an error.        Some(_) => Ok(None),    }}/// The TWIN, and the row it was all along.////// Before the hooks carried `sessionId`, a hosted session's first call reached/// the server unnamed, matched nothing and MADE A SECOND ROW — adopted/// (`host_owned = 0`), no terminal, no Stop — and every later turn landed on/// it. [`named_row`] closed that hole for sessions starting now; the pairs/// ALREADY SPLIT stay split, and the half that matters is the worse off of the/// two: the hosted row has no `external_id`, which is precisely what/// `session_birth::can_resume` requires, so the owner's Resume button never/// appears for the session it is about.////// So the next `log_session` NAMING the hosted row puts the two back together./// The conditions are deliberately narrow: the row holding this agent's id is/// ADOPTED, the named row is a DIFFERENT row of the SAME tool, it is/// HOST-OWNED, and its `external_id` is free. A named row nobody hosts, one of/// another tool, one already logging another agent — each keeps today's/// behaviour, because a fold moves a row under the owner's eyes and the only/// one worth doing is the one that hands a session its terminal back.fn foldable_named(    twin: &Map<String, Value>,    named: Option<&Map<String, Value>>,) -> Option<Map<String, Value>> {    if flag(twin, "host_owned") {        // A host-owned row holding this id IS the session. Nothing to fold.        return None;    }    let named = named?;    if text(named, "id") == text(twin, "id") {        // The caller named the very row its id is on — the ordinary update.        return None;    }    if !flag(named, "host_owned") || text(named, "external_id").is_some() {        return None;    }    Some(named.clone())}/// What the fold carried across, for the rest of the call to finish.#[derive(Debug, Default)]struct Folded {    /// The twin's title, where the named row had none.    title: Option<String>,    /// The seqs the moved turns now sit at on the named row.    seqs: Vec<i64>,}/// Move the twin's id, title and turns onto the row it was, and withdraw it.////// ONE TRANSACTION — every change here is queued on the same writer/// `log_session` commits once, at the end — and THE ORDER INSIDE IT IS/// LOAD-BEARING. `UNIQUE (tool, external_id)` admits one row per agent/// session, so the id comes OFF the twin here, before the caller's own patch/// puts it ON the named row through the `external_id IS NULL` branch. The/// other way round is a write the index refuses, and a refused `log_session`/// is a session that records nothing further, for ever.////// THE TWIN IS WITHDRAWN, NEVER DELETED: it is a row the owner may have been/// looking at, and `error` says in words where its session went. `host_owned`/// is not touched — it was adopted, and that stays true of it.fn fold_twin(    ctx: &mut Ctx<'_>,    twin: &Map<String, Value>,    named: &Map<String, Value>,) -> Result<Folded, ToolFailure> {    let twin_id = text(twin, "id").unwrap_or_default();    let named_id = text(named, "id").unwrap_or_default();    let now = now_iso(ctx);    // THE CLEAR FIRST — see this function's own note.    let mut patch = Map::new();    patch.insert("external_id".to_string(), Value::Null);    patch.insert("state".to_string(), Value::from("withdrawn"));    patch.insert("state_at".to_string(), Value::from(now.clone()));    patch.insert("ended_at".to_string(), Value::from(now));    patch.insert(        "error".to_string(),        Value::from(format!("folded into the session it was: {named_id}")),    );    update_row(ctx, "cotton_sessions", &twin_id, patch)?;    // The turns, RE-SEQUENCED after whatever the named row already has. A    // prompt's id is DERIVED from `(session, seq)` and `UNIQUE (session_id,    // seq)` holds, so a moved turn is a new row and the twin's copy goes. In    // the case this exists for the named row has no turns at all and the seqs    // come across unchanged.    let mut seq = rows(        ctx,        &Query::on("cotton_prompts")            .columns(&["seq"])            .eq("session_id", named_id.clone())            .order_by("seq", Order::Desc)            .limit(1),    )?    .first()    .and_then(|row| row.get("seq").and_then(Value::as_i64))    .unwrap_or(-1);    let moving = rows(        ctx,        &Query::on("cotton_prompts")            .columns(&["id", "seq", "ts", "role", "text", "project_id"])            .eq("session_id", twin_id.clone())            .order_by("seq", Order::Asc),    )?;    let mut seqs = Vec::with_capacity(moving.len());    for prompt in &moving {        seq += 1;        let mut patch = Map::new();        patch.insert("session_id".to_string(), Value::from(named_id.clone()));        patch.insert(            "project_id".to_string(),            or_null(text(prompt, "project_id")),        );        patch.insert("seq".to_string(), Value::from(seq));        patch.insert(            "ts".to_string(),            Value::from(text(prompt, "ts").unwrap_or_default()),        );        patch.insert(            "role".to_string(),            Value::from(text(prompt, "role").unwrap_or_else(|| "user".to_string())),        );        patch.insert(            "text".to_string(),            Value::from(text(prompt, "text").unwrap_or_default()),        );        insert_row(            ctx,            "cotton_prompts",            &derived_prompt_id(&named_id, seq),            patch,        )?;        if let Some(id) = text(prompt, "id") {            ctx.writer()?.retract("cotton_prompts", &id, Retract::Machine("rekey"));        }        seqs.push(seq);    }    Ok(Folded {        // The card is read by its title, so the twin's is kept where the row        // it folds into has none of its own.        title: match (text(named, "title"), text(twin, "title")) {            (None, title) => title,            (Some(_), _) => None,        },        seqs,    })}pub fn log_session(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_log_session(args)?;    let device_id = caller_device_id(ctx)?;    let projects = memory_projects(ctx)?;    let resolved_project =        session_project(&projects, args.project.as_deref(), args.repo_url.as_deref())?;    let summary = args        .summary        .as_deref()        .map(|summary| redacted_to_fit(summary, SESSION_SUMMARY_MAX));    let repo_url = args.repo_url.as_deref().map(normalize_repo_url);    // THE NAME IS RESOLVED FIRST — before `(tool, external_id)` is even asked.    // `named_row` refuses an id that names no row, and it has to do so from    // here: a call whose `sessionId` is wrong would otherwise be a perfectly    // ordinary update of whatever the pair matched, which is the shape of the    // 2026-09-25 truncated id.    let named = named_row(ctx, &args)?;    let mut folded = Folded::default();    let existing = match maybe_row(        ctx,        &Query::on("cotton_sessions")            .columns(SESSION_COLUMNS)            .eq("tool", args.tool.clone())            .eq("external_id", args.external_id.clone()),    )? {        // A row already holds this agent's id — ordinarily the session itself.        // Where it is an adopted TWIN of the row this call NAMES, the two go        // back together first and the named row is what the call goes on to        // update (`foldable_named`).        Some(twin) => match foldable_named(&twin, named.as_ref()) {            Some(named) => {                folded = fold_twin(ctx, &twin, &named)?;                Some(named)            }            None => Some(twin),        },        // Nothing matches this id — which is what a TWIN is made of. The row        // the caller NAMED first (see `named_row`: the helper told the agent        // which row it is), then the guess from the claim (`adoptable_here`),        // which only a device-signed caller ever gets.        None => match named {            Some(row) => Some(row),            None => adoptable_here(ctx, &args, device_id.as_deref())?,        },    };    let session_id: String;    let project_id: Option<String>;    match &existing {        Some(row) => {            session_id = text(row, "id").unwrap_or_default();            // The owner's reassignment on the phone outranks the repo: only an            // explicit slug, or a project for a session that had none, moves            // it.            project_id = if args.project.is_some() {                resolved_project.clone()            } else {                text(row, "project_id").or_else(|| resolved_project.clone())            };            let mut patch = Map::new();            patch.insert(                "last_active_at".to_string(),                Value::from(args.last_active_at.clone()),            );            patch.insert("project_id".to_string(), or_null(project_id.clone()));            // The machine follows the call. The hooks send the same hostname            // every turn, so for them this is a no-op; for a session that            // first logged itself under a name it guessed it is the re-home            // that leaves no phantom behind.            patch.insert("machine".to_string(), Value::from(args.machine.clone()));            // THE ADOPTED ROW LEARNS THE ID. A row matched by `(tool,            // external_id)` already has this value; one `adoptable_here` found            // has none, and this is the write that stops the next turn opening            // a second card.            if text(row, "external_id").is_none() {                patch.insert(                    "external_id".to_string(),                    Value::from(args.external_id.clone()),                );            }            // The DEVICE only when this call proved one. A session logged            // before v13, or by a caller with no device identity, keeps its            // NULL rather than having one written over it by a later turn that            // knows no more than the first did.            if let Some(device_id) = &device_id {                patch.insert("device_id".to_string(), Value::from(device_id.clone()));            }            // Each call is one turn unless the caller counts for itself.            patch.insert(                "turn_count".to_string(),                Value::from(args.turn_count.unwrap_or_else(|| {                    row.get("turn_count").and_then(Value::as_i64).unwrap_or(0) + 1                })),            );            if let Some(started_at) = &args.started_at {                patch.insert("started_at".to_string(), Value::from(started_at.clone()));            }            if let Some(ended_at) = &args.ended_at {                patch.insert("ended_at".to_string(), Value::from(ended_at.clone()));            } else if reopens(row, &args.last_active_at) {                // A RESUMED SESSION. The SessionEnd hook stamps `ended_at`                // when the session is killed; `claude --resume` brings the                // same external id back and the Stop hook logs turns again,                // carrying no `endedAt`. Activity AFTER the end is the proof                // that the end is stale — without this the row stays ended for                // ever though the session is demonstrably alive. A HOST-OWNED                // row is never reopened here; see [`reopens`].                patch.insert("ended_at".to_string(), Value::Null);            }            if let Some(repo_url) = &repo_url {                patch.insert("repo_url".to_string(), Value::from(repo_url.clone()));            }            if let Some(branch) = &args.branch {                patch.insert("branch".to_string(), Value::from(branch.clone()));            }            if let Some(cwd) = &args.cwd {                patch.insert("cwd".to_string(), Value::from(cwd.clone()));            }            // WHAT A FOLD CARRIES OVER. The twin's title, and only where this            // row had none — an explicit rename below still outranks it.            if let Some(title) = &folded.title {                patch.insert("title".to_string(), Value::from(title.clone()));            }            if let Some(title) = &args.title {                patch.insert("title".to_string(), Value::from(title.clone()));            }            // The latest model wins: a session can be switched mid-run, and            // the row says what is answering now.            if let Some(model) = &args.model {                patch.insert(                    "model".to_string(),                    Value::from(utf16_clip(model, SESSION_MODEL_MAX)),                );            }            // The first prompt becomes the title, ONCE. The Stop hook cannot            // know whether this session already has one, so it sends the line            // every turn and the server decides — which is also why `title`            // stays a separate parameter: a rename is deliberate and outranks            // this.            if let Some(title_if_empty) = &args.title_if_empty {                if text(row, "title").is_none() && folded.title.is_none() {                    patch.insert("title".to_string(), Value::from(title_if_empty.clone()));                }            }            if let Some(summary) = &summary {                // The latest recap wins, and what it says it shipped comes                // with it.                patch.insert("summary".to_string(), Value::from(summary.clone()));                patch.insert(                    "shipped".to_string(),                    Value::Array(                        shipped_in(Some(summary))                            .into_iter()                            .map(Value::from)                            .collect(),                    ),                );            }            if let Some(transcript_ref) = &args.transcript_ref {                patch.insert(                    "transcript_ref".to_string(),                    Value::from(transcript_ref.clone()),                );            }            update_row(ctx, "cotton_sessions", &session_id, patch)?;        }        None => {            // DERIVED from the pair the table is UNIQUE on, never minted: two            // servers can both hear about one agent session — the hook through            // one, the bus through the other — and a uuid apiece is two rows            // the index refuses to hold, after which every later `log_session`            // patch of the losing id is a write that can never land. See            // `cotton_store::protocol::derived_id::session_id`.            session_id = derived_session_id(&args.tool, &args.external_id);            project_id = resolved_project.clone();            let mut patch = Map::new();            patch.insert("project_id".to_string(), or_null(project_id.clone()));            patch.insert("tool".to_string(), Value::from(args.tool.clone()));            patch.insert(                "external_id".to_string(),                Value::from(args.external_id.clone()),            );            patch.insert("machine".to_string(), Value::from(args.machine.clone()));            patch.insert("device_id".to_string(), or_null(device_id.clone()));            patch.insert("repo_url".to_string(), or_null(repo_url.clone()));            patch.insert("branch".to_string(), or_null(args.branch.clone()));            patch.insert("cwd".to_string(), or_null(args.cwd.clone()));            patch.insert(                "started_at".to_string(),                Value::from(                    args.started_at                        .clone()                        .unwrap_or_else(|| args.last_active_at.clone()),                ),            );            patch.insert(                "last_active_at".to_string(),                Value::from(args.last_active_at.clone()),            );            patch.insert("ended_at".to_string(), or_null(args.ended_at.clone()));            patch.insert("summary".to_string(), or_null(summary.clone()));            patch.insert(                "title".to_string(),                or_null(args.title.clone().or_else(|| args.title_if_empty.clone())),            );            patch.insert(                "model".to_string(),                or_null(                    args.model                        .as_deref()                        .map(|model| utf16_clip(model, SESSION_MODEL_MAX)),                ),            );            patch.insert(                "shipped".to_string(),                Value::Array(                    shipped_in(summary.as_deref())                        .into_iter()                        .map(Value::from)                        .collect(),                ),            );            patch.insert(                "turn_count".to_string(),                Value::from(args.turn_count.unwrap_or(1)),            );            patch.insert("prompt_count".to_string(), Value::from(0));            patch.insert(                "transcript_ref".to_string(),                or_null(args.transcript_ref.clone()),            );            insert_row(ctx, "cotton_sessions", &session_id, patch)?;        }    }    // Turns — the owner's prompts and the assistant's replies (v37): only    // seqs the session does not have yet (the hook may resend).    let mut have: HashSet<i64> = rows(        ctx,        &Query::on("cotton_prompts")            .columns(&["seq"])            .eq("session_id", session_id.clone()),    )?    .iter()    .filter_map(|row| row.get("seq").and_then(Value::as_i64))    .collect();    // The turns a FOLD just moved onto this row are queued, not yet folded, so    // the read above cannot see them: without this a hook resending one would    // write a second copy and `prompt_count` would count the turn twice.    have.extend(folded.seqs.iter().copied());    let mut unique: BTreeMap<i64, LogSessionPrompt> = BTreeMap::new();    for prompt in &args.prompts {        if have.contains(&prompt.seq) {            continue;        }        unique.entry(prompt.seq).or_insert_with(|| prompt.clone());    }    // A reply the phone sent, typed into the terminal by the Mac, comes back in    // the transcript as the owner's own turn. The phone's message row is    // already on the session page, so that turn is not written a second time    // (`crate::session_echo`, the same question the Mac's mirror asks). A    // message absorbs at most one turn: only messages sent after the session's    // last kept turn before this one are candidates, and after the one the    // previous turn of that window absorbed. Worked out from the turns on disk    // and in this call, so a resend gets the same answer.    if unique.values().any(|prompt| prompt.role == "user") {        let typed_kinds = TYPED_KINDS            .iter()            .map(|kind| SqlValue::from(kind.to_string()))            .collect();        let delivered: Vec<DeliveredMessage> = rows(            ctx,            &Query::on("cotton_session_messages")                .columns(&["id", "body", "created_at"])                .eq("to_kind", "session".to_string())                .eq("to_session_id", session_id.clone())                .filter(Filter::In("kind".to_string(), typed_kinds))                .filter(Filter::Ne(                    "status".to_string(),                    SqlValue::from("withdrawn".to_string()),                ))                .order_by("created_at", Order::Asc)                .order_by("id", Order::Asc),        )?        .iter()        .filter_map(|row| {            Some(DeliveredMessage {                id: text(row, "id")?,                body: text(row, "body")?,                created_at: text(row, "created_at")?,            })        })        .collect();        if !delivered.is_empty() {            // Every kept turn by seq: the ones on disk, then this call's as            // they are kept.            let mut kept: BTreeMap<i64, String> = rows(                ctx,                &Query::on("cotton_prompts")                    .columns(&["seq", "ts"])                    .eq("session_id", session_id.clone()),            )?            .iter()            .filter_map(|row| Some((row.get("seq")?.as_i64()?, text(row, "ts")?)))            .collect();            // The message the previous turn absorbed, and the kept turn it            // was absorbed after — `past` holds only inside that window.            let mut past: Option<(Option<i64>, DeliveredMessage)> = None;            let mut echoes: Vec<i64> = Vec::new();            for (seq, prompt) in &unique {                let before = kept                    .range(..*seq)                    .next_back()                    .map(|(at, ts)| (*at, ts.clone()));                let window = before.as_ref().map(|(at, _)| *at);                if prompt.role == "user" {                    let same_window = past                        .as_ref()                        .filter(|(opened, _)| *opened == window)                        .map(|(_, message)| message);                    if let Some(message) = absorbing(                        &prompt.text,                        before.as_ref().map(|(_, ts)| ts.as_str()),                        same_window,                        &delivered,                    ) {                        past = Some((window, message.clone()));                        echoes.push(*seq);                        continue;                    }                }                kept.insert(*seq, prompt.ts.clone());            }            for seq in echoes {                unique.remove(&seq);            }        }    }    for prompt in unique.values() {        // `UNIQUE (session_id, seq)`, and the hook may resend a turn through a        // different server: DERIVED, so the second telling of one prompt is the        // same row rather than a rejection that never clears.        let id = derived_prompt_id(&session_id, prompt.seq);        let mut patch = Map::new();        patch.insert("session_id".to_string(), Value::from(session_id.clone()));        patch.insert("project_id".to_string(), or_null(project_id.clone()));        patch.insert("seq".to_string(), Value::from(prompt.seq));        patch.insert("ts".to_string(), Value::from(prompt.ts.clone()));        patch.insert("role".to_string(), Value::from(prompt.role.clone()));        patch.insert(            "text".to_string(),            Value::from(redacted_to_fit(&prompt.text, PROMPT_TEXT_MAX)),        );        insert_row(ctx, "cotton_prompts", &id, patch)?;    }    // THE TASK LIST, replaced whole (schema v31). `None` says nothing about    // tasks and leaves the list alone; a list REPLACES it.    //    // Replace, not delete-then-insert: the ids are derived from    // `(session, seq)`, so a task that survives the edit is the SAME row and    // deleting it first would put a delete and an upsert of one row id in one    // batch. What goes is what the new list does not name.    let mut tasks_total = 0_i64;    let mut tasks_done = 0_i64;    if let Some(tasks) = &args.tasks {        let existing: Vec<String> = rows(            ctx,            &Query::on(SESSION_TASKS_TABLE)                .columns(&["id", "session_id"])                .eq("session_id", session_id.clone()),        )?        .iter()        .filter_map(|row| text(row, "id"))        .collect();        let mut keep: HashSet<String> = HashSet::new();        for task in tasks {            let id = derived_task_id(&session_id, task.seq);            keep.insert(id.clone());            let mut patch = Map::new();            patch.insert("session_id".to_string(), Value::from(session_id.clone()));            patch.insert("seq".to_string(), Value::from(task.seq));            patch.insert("text".to_string(), Value::from(task.text.clone()));            patch.insert("state".to_string(), Value::from(task.state.clone()));            if existing.contains(&id) {                update_row(ctx, SESSION_TASKS_TABLE, &id, patch)?;            } else {                insert_row(ctx, SESSION_TASKS_TABLE, &id, patch)?;            }            tasks_total += 1;            if task.state == "done" {                tasks_done += 1;            }        }        for id in existing.iter().filter(|id| !keep.contains(*id)) {            ctx.writer()?.retract(SESSION_TASKS_TABLE, id, Retract::Relation);        }    }    let prompt_count = (have.len() + unique.len()) as i64;    let previous_count = existing        .as_ref()        .and_then(|row| row.get("prompt_count").and_then(Value::as_i64));    if previous_count != Some(prompt_count) {        let mut patch = Map::new();        patch.insert("prompt_count".to_string(), Value::from(prompt_count));        update_row(ctx, "cotton_sessions", &session_id, patch)?;    }    ctx.commit()?;    let mut out = Map::new();    out.insert("sessionId".to_string(), Value::from(session_id));    out.insert("promptCount".to_string(), Value::from(prompt_count));    out.insert("inserted".to_string(), Value::from(unique.len() as i64));    if args.tasks.is_some() {        out.insert("tasksDone".to_string(), Value::from(tasks_done));        out.insert("tasksTotal".to_string(), Value::from(tasks_total));    }    Ok(Value::Object(out))}// ── list_sessions ───────────────────────────────────────────────────────────fn session_out(row: &Map<String, Value>, projects: &[MemoryProject]) -> Map<String, Value> {    let mut out = Map::new();    out.insert("id".to_string(), or_null(text(row, "id")));    out.insert("tool".to_string(), or_null(text(row, "tool")));    out.insert("externalId".to_string(), or_null(text(row, "external_id")));    out.insert("machine".to_string(), or_null(text(row, "machine")));    // The device this session PROVED it ran on, or null where nothing proved    // one — never the machine name dressed up as a device.    out.insert("deviceId".to_string(), or_null(text(row, "device_id")));    out.insert("account".to_string(), or_null(text(row, "account")));    out.insert(        "project".to_string(),        or_null(text(row, "project_id").and_then(|id| {            projects                .iter()                .find(|project| project.id == id)                .map(|project| project.slug.clone())        })),    );    out.insert("repoUrl".to_string(), or_null(text(row, "repo_url")));    out.insert("branch".to_string(), or_null(text(row, "branch")));    out.insert("startedAt".to_string(), or_null(text(row, "started_at")));    out.insert(        "lastActiveAt".to_string(),        or_null(text(row, "last_active_at")),    );    out.insert("endedAt".to_string(), or_null(text(row, "ended_at")));    out.insert("title".to_string(), or_null(text(row, "title")));    out.insert("model".to_string(), or_null(text(row, "model")));    out.insert("summary".to_string(), or_null(text(row, "summary")));    out.insert(        "shipped".to_string(),        Value::Array(            row.get("shipped")                .and_then(Value::as_array)                .map(|items| {                    items                        .iter()                        .filter(|entry| entry.is_string())                        .cloned()                        .collect()                })                .unwrap_or_default(),        ),    );    out.insert(        "turnCount".to_string(),        Value::from(row.get("turn_count").and_then(Value::as_i64).unwrap_or(0)),    );    out.insert(        "promptCount".to_string(),        Value::from(row.get("prompt_count").and_then(Value::as_i64).unwrap_or(0)),    );    out.insert(        "transcriptRef".to_string(),        or_null(text(row, "transcript_ref")),    );    // What it is doing right now, and what it is waiting on. NULL for every    // session logged before the Code tool and for every session no session host    // owns — which is the honest answer, not "starting".    out.insert("state".to_string(), or_null(text(row, "state")));    out.insert("stateAt".to_string(), or_null(text(row, "state_at")));    out.insert("waitingKind".to_string(), or_null(text(row, "waiting_kind")));    // The permission it is waiting on, so a reader can tell an answer on its    // way to THIS permission from one sent for an earlier one.    out.insert("waitingRef".to_string(), or_null(text(row, "waiting_ref")));    // The tail of the last assistant turn, at most 280 characters — enough for    // a card to say what the session last said, and never the transcript.    out.insert("lastLine".to_string(), or_null(text(row, "last_line")));    // Through `flag` and never `as_i64`: `host_owned` is an INTEGER column that    // the read path decodes by its `Codec::Bool` spec, so it arrives as a JSON    // BOOLEAN here and as a number elsewhere — and an `as_i64` over the boolean    // reads `true` as absent, which would call every hosted session adopted.    out.insert("hostOwned".to_string(), Value::Bool(flag(row, "host_owned")));    // The queue, on the one object (v23). A `queued` session has no agent    // behind it yet, so what a card can say about it is what the owner asked    // for and what has stopped it: the prompt, the Mac they named (or none,    // which is "any Mac"), who chose the one it is on, and the SENTENCE the    // dispatcher wrote when it could not place it.    out.insert("prompt".to_string(), or_null(text(row, "prompt")));    out.insert(        "requestedDeviceId".to_string(),        or_null(text(row, "requested_device_id")),    );    out.insert("chosenBy".to_string(), or_null(text(row, "chosen_by")));    out.insert("holdReason".to_string(), or_null(text(row, "hold_reason")));    // The sentence a `failed` session carries — why it never began.    out.insert("error".to_string(), or_null(text(row, "error")));    out.insert("todoId".to_string(), or_null(text(row, "todo_id")));    out.insert("todoDatabase".to_string(), or_null(text(row, "todo_database")));    // Version 31 — what this row is, and which conversation opened it. `kind`    // is NOT NULL on the file, so the fallback is the column's own default    // rather than a null a caller would have to read around.    out.insert(        "kind".to_string(),        Value::from(text(row, "kind").unwrap_or_else(|| "thread".to_string())),    );    out.insert(        "parentSessionId".to_string(),        or_null(text(row, "parent_session_id")),    );    out}/// One session's mirrored task list, in the agent's own order.pub fn session_tasks(    ctx: &mut Ctx<'_>,    session_id: &str,) -> Result<Vec<Map<String, Value>>, ToolFailure> {    let mut found = rows(        ctx,        &Query::on(SESSION_TASKS_TABLE)            .columns(&["id", "session_id", "seq", "text", "state"])            .eq("session_id", session_id.to_string()),    )?;    found.sort_by_key(|row| row.get("seq").and_then(Value::as_i64).unwrap_or_default());    Ok(found        .iter()        .map(|row| {            let mut out = Map::new();            out.insert(                "seq".to_string(),                Value::from(row.get("seq").and_then(Value::as_i64).unwrap_or_default()),            );            out.insert("text".to_string(), or_null(text(row, "text")));            out.insert(                "state".to_string(),                Value::from(text(row, "state").unwrap_or_else(|| "open".to_string())),            );            out        })        .collect())}/// `(done, total)` per session, for the sessions named — what a card draws as/// "4/6".////// ONE read for the whole page rather than one per row: a list of two hundred/// sessions is a list somebody scrolls, and two hundred queries behind it is/// the shape of a screen that stops being usable at the size it matters.fn task_counts(    ctx: &mut Ctx<'_>,    session_ids: &[String],) -> Result<BTreeMap<String, (i64, i64)>, ToolFailure> {    let mut counts: BTreeMap<String, (i64, i64)> = BTreeMap::new();    if session_ids.is_empty() {        return Ok(counts);    }    let found = rows(        ctx,        &Query::on(SESSION_TASKS_TABLE)            .columns(&["id", "session_id", "state"])            .filter(Filter::In(                "session_id".to_string(),                session_ids                    .iter()                    .map(|id| SqlValue::Text(id.clone()))                    .collect(),            )),    )?;    for row in &found {        let Some(id) = text(row, "session_id") else {            continue;        };        let entry = counts.entry(id).or_insert((0, 0));        entry.1 += 1;        if text(row, "state").as_deref() == Some("done") {            entry.0 += 1;        }    }    Ok(counts)}pub fn list_sessions(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_list_sessions(args)?;    let projects = memory_projects(ctx)?;    let refs: Vec<crate::mcp::handlers::common::ProjectRef> = projects        .iter()        .map(|project| crate::mcp::handlers::common::ProjectRef {            id: project.id.clone(),            slug: project.slug.clone(),            status: project.status.clone(),        })        .collect();    // AN ARCHIVED PROJECT'S SESSIONS ARE STILL ITS OWN. `project_filter`    // resolves active projects only, which is right for filing something new    // and wrong for reading what was filed: an archived project keeps its page,    // and that page's Sessions section asks this list by the slug.    let filter = match args.project.as_deref() {        Some(slug) if slug != crate::mcp::handlers::common::NO_PROJECT_FILTER => {            match refs.iter().find(|project| project.slug == slug) {                Some(project) => ProjectFilter::Project(project.id.clone()),                None => project_filter(&refs, Some(slug))?,            }        }        other => project_filter(&refs, other)?,    };    // `q` searches what the owner typed: FTS over the prompts, folded to the    // sessions that hit, each with its matching snippets.    let mut hits_by_session: Option<Vec<(String, Vec<Value>)>> = None;    if let Some(q) = &args.q {        let mut hits: Vec<(String, Vec<Value>)> = Vec::new();        if let Some(matcher) = to_match_query(q) {            let found = ctx                .db()                .all(                    "SELECT p.session_id AS session_id, p.seq AS seq,\n                \                     snippet(fts_prompts, -1, '', '', '…', 12) AS snippet\n           FROM \                     fts_prompts\n           JOIN cotton_prompts p ON p.rowid = \                     fts_prompts.rowid\n          WHERE fts_prompts MATCH ? AND p.workspace_id = \                     ?\n          ORDER BY bm25(fts_prompts), p.seq ASC\n          LIMIT ?",                    &[                        SqlValue::Text(matcher),                        SqlValue::Text(ctx.workspace_id.to_string()),                        SqlValue::Integer(args.limit * 10),                    ],                )                .map_err(|error| ToolFailure::new(error.to_string()))?;            for row in &found {                let Some(session_id) = row.text("session_id").map(str::to_string) else {                    continue;                };                let mut hit = Map::new();                hit.insert(                    "seq".to_string(),                    Value::from(row.int("seq").unwrap_or_default()),                );                hit.insert(                    "snippet".to_string(),                    Value::from(row.text("snippet").unwrap_or_default()),                );                match hits.iter_mut().find(|(id, _)| *id == session_id) {                    Some((_, bucket)) => {                        if bucket.len() < 5 {                            bucket.push(Value::Object(hit));                        }                    }                    None => hits.push((session_id, vec![Value::Object(hit)])),                }            }        }        if hits.is_empty() {            let mut out = Map::new();            out.insert("sessions".to_string(), Value::Array(Vec::new()));            return Ok(Value::Object(out));        }        hits_by_session = Some(hits);    }    let mut query = Query::on("cotton_sessions").columns(SESSION_COLUMNS);    match &filter {        ProjectFilter::Every => {}        ProjectFilter::NoProject => {            // A session whose project is gone is filed under none.            query = query.filter(Filter::SoftAbsent("project_id".to_string()));        }        ProjectFilter::Project(id) => query = query.eq("project_id", id.clone()),    }    if let Some(machine) = &args.machine {        query = query.eq("machine", machine.clone());    }    // Version 31 — a conversation's THREADS, and the conversations themselves.    if let Some(parent) = &args.parent {        query = query.eq("parent_session_id", parent.clone());    }    if let Some(kind) = &args.kind {        query = query.eq("kind", kind.clone());    }    // The window, by the column that says when the session last DID anything.    // `last_active_at` and not `ended_at`: a session still running has no end,    // and one that ended inside the window is exactly what a screen asking for    // "the last week" means to draw.    if let Some(since) = &args.since {        query = query.filter(Filter::Gte(            "last_active_at".to_string(),            SqlValue::Text(since.clone()),        ));    }    if let Some(hits) = &hits_by_session {        query = query.filter(Filter::In(            "id".to_string(),            hits.iter()                .map(|(id, _)| SqlValue::Text(id.clone()))                .collect(),        ));    }    // THE PAGE AFTER THE ONE A CALLER ALREADY HOLDS — a keyset over the    // order below, so a session that shares its last activity with the row a    // page stopped on is neither skipped nor read twice.    if let Some(cursor) = &args.cursor {        query = query.filter(Filter::KeysetBefore {            column: "last_active_at".to_string(),            value: SqlValue::Text(cursor.last_active_at.clone()),            tie_column: "id".to_string(),            tie: SqlValue::Text(cursor.id.clone()),        });    }    let query = query        .order_by("last_active_at", Order::Desc)        .order_by("id", Order::Desc)        .limit(args.limit);    let found = rows(ctx, &query)?;    // A FULL PAGE may have more behind it; a short one is the end. The handle    // is the last row's own place in the order, so the next page starts    // exactly after it.    let next_cursor = (found.len() as i64 == args.limit)        .then(|| found.last())        .flatten()        .and_then(|row| {            Some(SessionCursor {                last_active_at: text(row, "last_active_at")?,                id: text(row, "id")?,            })        });    let ids: Vec<String> = found.iter().filter_map(|row| text(row, "id")).collect();    let counts = task_counts(ctx, &ids)?;    let sessions: Vec<Value> = found        .iter()        .map(|row| {            let id = text(row, "id").unwrap_or_default();            let mut out = session_out(row, &projects);            // "4/6" — zero and zero for a session that mirrored no list, which            // is what a card draws nothing for.            let (done, total) = counts.get(&id).copied().unwrap_or((0, 0));            out.insert("tasksDone".to_string(), Value::from(done));            out.insert("tasksTotal".to_string(), Value::from(total));            if let Some(hits) = &hits_by_session {                out.insert(                    "hits".to_string(),                    Value::Array(                        hits.iter()                            .find(|(session_id, _)| *session_id == id)                            .map(|(_, bucket)| bucket.clone())                            .unwrap_or_default(),                    ),                );            }            Value::Object(out)        })        .collect();    let mut out = Map::new();    out.insert("sessions".to_string(), Value::Array(sessions));    if let Some(cursor) = next_cursor {        out.insert("nextCursor".to_string(), Value::from(cursor.encode()));    }    Ok(Value::Object(out))}/// Where a page of `list_sessions` stopped: the last row's place in the/// list's own order — `last_active_at` descending, `id` descending as the/// tiebreak.////// A caller never reads it: it travels as the base64url of its JSON, versioned,/// so the day the order changes an old handle is refused rather than quietly/// answering the wrong page.#[derive(Debug, Clone, PartialEq, Eq)]pub struct SessionCursor {    pub last_active_at: String,    pub id: String,}impl SessionCursor {    /// The handle a caller passes back as `cursor`.    pub fn encode(&self) -> String {        use base64::Engine;        let payload = serde_json::json!({ "v": 1, "key": self.last_active_at, "id": self.id });        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload.to_string())    }    fn decode(raw: &str) -> Option<SessionCursor> {        use base64::Engine;        let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD            .decode(raw)            .ok()?;        let payload: Value = serde_json::from_slice(&bytes).ok()?;        if payload.get("v").and_then(Value::as_i64) != Some(1) {            return None;        }        Some(SessionCursor {            last_active_at: payload.get("key")?.as_str()?.to_string(),            id: payload.get("id")?.as_str()?.to_string(),        })    }}// ── the validators ──────────────────────────────────────────────────────────#[derive(Debug, Clone)]pub struct LogSessionPrompt {    pub seq: i64,    pub ts: String,    pub role: String,    pub text: String,}/// One entry of a session's mirrored task list (schema v31).#[derive(Debug, Clone)]pub struct LogSessionTask {    pub seq: i64,    pub text: String,    pub state: String,}#[derive(Debug, Clone)]pub struct LogSessionArgs {    pub tool: String,    pub external_id: String,    /// `cotton_sessions.id` — the row this session IS, where the caller was    /// told it. See [`named_row`].    pub session_row_id: Option<String>,    pub machine: String,    pub last_active_at: String,    pub prompts: Vec<LogSessionPrompt>,    pub repo_url: Option<String>,    pub branch: Option<String>,    pub cwd: Option<String>,    pub project: Option<String>,    pub started_at: Option<String>,    pub ended_at: Option<String>,    pub title: Option<String>,    pub title_if_empty: Option<String>,    pub summary: Option<String>,    pub model: Option<String>,    pub turn_count: Option<i64>,    pub transcript_ref: Option<String>,    /// The agent's own task list, mirrored (schema v31).    ///    /// `None` is "this call says nothing about tasks" and leaves the list    /// alone; `Some(list)` REPLACES it whole, an empty list included — a task    /// list is one value, and a patch of it would draw a task the agent has    /// dropped.    pub tasks: Option<Vec<LogSessionTask>>,}/// Redact, THEN truncate rather than refuse — the validator's half of the/// rule the module note states. Absent stays absent.fn clipped(value: Option<String>, max: usize) -> Option<String> {    value.map(|value| {        let safe = redact_secrets(&value);        utf16_clip(&safe, max)    })}fn validate_log_session(args: &Map<String, Value>) -> Valid<LogSessionArgs> {    let tool = match require_string(args, "tool") {        Some(tool) if SESSION_TOOLS.contains(&tool.as_str()) => tool,        _ => return fail(format!("tool must be one of {}", SESSION_TOOLS.join(", "))),    };    let Some(external_id) = require_string(args, "externalId") else {        return fail("externalId is required — the tool's own session id");    };    let Some(machine) = require_string(args, "machine") else {        return fail("machine is required — this machine's hostname");    };    let Some(last_active_at) = require_string(args, "lastActiveAt")        .as_deref()        .and_then(iso_timestamp)    else {        return fail("lastActiveAt must be an ISO-8601 timestamp");    };    let stamp = |key: &str| -> Valid<Option<String>> {        match optional_string(args, key) {            None => Ok(None),            Some(raw) => match iso_timestamp(&raw) {                Some(value) => Ok(Some(value)),                None => fail(format!("{key} must be an ISO-8601 timestamp")),            },        }    };    let started_at = stamp("startedAt")?;    let ended_at = stamp("endedAt")?;    let turn_count = match args.get("turnCount") {        None => None,        Some(value) => match value.as_i64().filter(|count| *count >= 0) {            Some(count) if value.as_f64().is_some_and(|raw| raw.fract() == 0.0) => Some(count),            _ => return fail("turnCount must be a non-negative integer"),        },    };    let mut prompts: Vec<LogSessionPrompt> = Vec::new();    match args.get("prompts") {        None | Some(Value::Null) => {}        Some(Value::Array(entries)) => {            for entry in entries {                let Some(prompt) = entry.as_object() else {                    return fail("each prompt must be { seq, ts, text }");                };                let seq = match prompt.get("seq") {                    Some(value) => match value.as_i64().filter(|seq| *seq >= 0) {                        Some(seq) if value.as_f64().is_some_and(|raw| raw.fract() == 0.0) => seq,                        _ => return fail("prompt.seq must be a non-negative integer"),                    },                    None => return fail("prompt.seq must be a non-negative integer"),                };                let Some(ts) = prompt                    .get("ts")                    .and_then(Value::as_str)                    .and_then(iso_timestamp)                else {                    return fail("prompt.ts must be an ISO-8601 timestamp");                };                let Some(raw_text) = prompt.get("text").and_then(Value::as_str) else {                    return fail("prompt.text must be a string");                };                let role = match prompt.get("role") {                    None => "user".to_string(),                    Some(Value::String(role)) if TURN_ROLES.contains(&role.as_str()) => {                        role.clone()                    }                    Some(_) => {                        return fail(format!(                            "prompt.role must be one of {}",                            TURN_ROLES.join(", ")                        ))                    }                };                // Blank prompts carry nothing and the file refuses them;                // skipping one is the honest outcome for a hook that must                // never fail.                let text = redacted_to_fit(raw_text, PROMPT_TEXT_MAX);                if text.trim().is_empty() {                    continue;                }                prompts.push(LogSessionPrompt {                    seq,                    ts,                    role,                    text,                });            }        }        Some(_) => return fail("prompts must be an array"),    }    // THE TASK LIST, absorbed rather than refused — A SESSION LOG MUST NEVER    // FAIL, and the hook that sends this is the one that cannot be told it was    // wrong. A task past the cap is truncated, a word the file does not know    // is read as `open`, a position below zero is dropped, and the FIRST    // telling of a position wins, exactly as a prompt's does.    let tasks = match args.get("tasks") {        None | Some(Value::Null) => None,        Some(Value::Array(entries)) => {            let mut seen: BTreeMap<i64, LogSessionTask> = BTreeMap::new();            for entry in entries {                let Some(task) = entry.as_object() else {                    continue;                };                let Some(seq) = task                    .get("seq")                    .and_then(Value::as_i64)                    .filter(|seq| *seq >= 0)                else {                    continue;                };                let Some(raw_text) = task.get("text").and_then(Value::as_str) else {                    continue;                };                let text = redacted_to_fit(raw_text, TASK_TEXT_MAX);                if text.trim().is_empty() {                    continue;                }                let state = task                    .get("state")                    .and_then(Value::as_str)                    .filter(|state| TASK_STATES.contains(state))                    .unwrap_or("open")                    .to_string();                seen.entry(seq).or_insert(LogSessionTask { seq, text, state });            }            Some(seen.into_values().collect())        }        // Not an array is not a list, and a hook that sent one is a hook whose        // NEXT call still has to land.        Some(_) => None,    };    Ok(LogSessionArgs {        tool,        external_id,        // NEVER a refusal, whatever it holds: a session that named a row this        // database does not have still has a session to log. An empty string        // is an absent variable spelled out by a hook, and means the same.        session_row_id: optional_string(args, "sessionId").filter(|id| !id.trim().is_empty()),        machine,        last_active_at,        prompts,        repo_url: optional_string(args, "repoUrl"),        branch: optional_string(args, "branch"),        cwd: optional_string(args, "cwd"),        project: optional_string(args, "project"),        started_at,        ended_at,        title: clipped(optional_string(args, "title"), SESSION_TITLE_MAX),        title_if_empty: clipped(optional_string(args, "titleIfEmpty"), SESSION_TITLE_MAX),        summary: clipped(optional_string(args, "summary"), SESSION_SUMMARY_MAX),        model: clipped(optional_string(args, "model"), SESSION_MODEL_MAX),        turn_count,        transcript_ref: optional_string(args, "transcriptRef"),        tasks,    })}#[derive(Debug, Clone)]pub struct ListSessionsArgs {    pub limit: i64,    pub project: Option<String>,    pub machine: Option<String>,    pub q: Option<String>,    pub since: Option<String>,    /// A conversation's id — its THREADS, and nothing else (schema v31).    pub parent: Option<String>,    /// `conversation` or `thread` (schema v31).    pub kind: Option<String>,    /// The page to read, from the previous page's `nextCursor`.    pub cursor: Option<SessionCursor>,}fn validate_list_sessions(args: &Map<String, Value>) -> Valid<ListSessionsArgs> {    // A WINDOW, and it is refused rather than ignored when it is not an    // instant: a caller asking for "the last week" and silently being handed    // every session that ever ran is the failure this parameter exists to    // stop. Normalised through `iso_timestamp` so the comparison against    // `last_active_at` — which is stored in that one spelling — is the    // lexicographic one SQLite will actually make.    let since = match args.get("since") {        None | Some(Value::Null) => None,        Some(Value::String(value)) => match iso_timestamp(value) {            Some(parsed) => Some(parsed),            None => return fail("since must be an ISO 8601 timestamp"),        },        Some(_) => return fail("since must be an ISO 8601 timestamp"),    };    let cursor = match optional_string(args, "cursor") {        None => None,        Some(raw) => match SessionCursor::decode(&raw) {            Some(cursor) => Some(cursor),            // A cursor is this tool's own handle, so a bad one is a caller            // error and never a silently-restarted list: reading page one            // again would hand back rows the caller already holds.            None => {                return fail(                    "cursor is not one list_sessions handed out — pass nextCursor from the \                     previous page exactly as it came, or drop it to start the list again",                )            }        },    };    Ok(ListSessionsArgs {        cursor,        since,        // TWENTY by default, MAX_LIST at most. The default is unchanged and        // is what an assistant asking "what happened elsewhere" wants; the        // ceiling was raised from fifty because the owner's own sessions log is        // `listSessions`' `options.limit ?? 200` and filters the pool it has        // loaded rather than querying again, so anything past the limit is not        // merely off the page — it is unsearchable.        limit: bounded_limit(args, 20, crate::mcp::handlers::common::MAX_LIST),        project: optional_string(args, "project"),        machine: optional_string(args, "machine"),        q: optional_string(args, "q"),        parent: optional_string(args, "parent"),        // REFUSED rather than ignored, the same rule `since` follows: a caller        // asking for the conversations and being handed every session is a        // silent lie to the one caller asking the narrowest question.        kind: match optional_string(args, "kind") {            None => None,            Some(kind) if SESSION_KINDS.contains(&kind.as_str()) => Some(kind),            Some(kind) => {                return fail(format!(                    "kind is one of {} — not `{kind}`",                    SESSION_KINDS.join(", ")                ))            }        },    })}#[cfg(test)]mod tests {    use super::*;    #[test]    fn shipped_in_keeps_each_link_once_and_in_order() {        let summary = "shipped https://github.com/a/b/pull/12 and \                       https://github.com/a/b/commit/abc, then \                       https://github.com/a/b/pull/12 again.";        assert_eq!(            shipped_in(Some(summary)),            vec![                "https://github.com/a/b/pull/12".to_string(),                "https://github.com/a/b/commit/abc".to_string(),            ]        );        assert!(shipped_in(None).is_empty());    }    /// A row as `reopens` reads one: its end stamp, and who owns its life.    fn ended_row(ended_at: Option<&str>, host_owned: bool) -> Map<String, Value> {        let mut row = Map::new();        row.insert("ended_at".to_string(), or_null(ended_at.map(str::to_string)));        row.insert(            "host_owned".to_string(),            Value::from(i64::from(host_owned)),        );        row    }    #[test]    fn only_activity_strictly_after_the_end_reopens_a_session() {        let end = "2026-09-08T09:00:00.000Z";        // A row that never ended has nothing to reopen.        assert!(!reopens(&ended_row(None, false), "2026-09-08T09:00:00.001Z"));        // Strictly later, to the millisecond.        assert!(reopens(            &ended_row(Some(end), false),            "2026-09-08T09:00:00.001Z"        ));        assert!(!reopens(&ended_row(Some(end), false), end));        assert!(!reopens(            &ended_row(Some(end), false),            "2026-09-08T08:59:59.999Z"        ));        // An instant neither side can read decides nothing.        assert!(!reopens(            &ended_row(Some("not a date"), false),            "2026-09-08T09:00:00.001Z"        ));        assert!(!reopens(&ended_row(Some(end), false), "not a date"));    }    #[test]    fn a_host_owned_row_is_never_reopened_by_a_late_hook() {        // The same activity that reopens an adopted row leaves a hosted one        // alone: the helper says when a session Cotton started is over.        let end = "2026-09-08T09:00:00.000Z";        let later = "2026-09-08T09:05:00.000Z";        assert!(reopens(&ended_row(Some(end), false), later));        assert!(!reopens(&ended_row(Some(end), true), later));    }    #[test]    fn a_clip_counts_utf16_code_units() {        // An astral emoji is TWO units, so a cap of 3 keeps one whole emoji        // and one half — which `from_utf16_lossy` writes as U+FFFD.        let units = |value: &str| value.encode_utf16().count();        assert_eq!(units("🌱🌱"), 4);        assert_eq!(utf16_clip("abc", 10), "abc");        assert_eq!(units(&utf16_clip("🌱🌱", 3)), 3);    }}