Cotton code
841 lines · 35.7 KB · RustRaw
//! HOW A SESSION IS BORN — the one function every opener goes through.//!//! ## Why this is here and not in the caller//!//! It used to live in `cotton-ffi` (`phone/session_queue.rs`), because the//! phone was the only thing that could ask for a session. It is not any more://! a project's CONVERSATION opens threads over MCP (`create_session`), and the//! MCP handlers live in this crate. Two copies of "what a queued session row//! looks like" would be two queues that could disagree, so there is one//! [`write_session`] and the FFI's `session.create` is a thin caller of it.//!//! It is in `cotton-tools` rather than `cotton-core` for the reason the//! dependency graph gives: the birth is a WRITE through a `Ctx` — the reader,//! the writer, the clock and the uuid source — and `Ctx` is this crate's.//! `cotton-core` depends on `cotton-store` alone and cannot see it. What DID//! go to core is the part that is pure: the standing prompt's template//! (`cotton_core::rules::conversation_prompt`).//!//! ## What the phone may write, and what it may not//!//! `starting`, `running`, `failed`, `claimed_at`, `started_at`, `external_id`,//! `hold_reason` and `error` belong to the Mac that takes the row and to the//! dispatcher. An opener writes `queued` once and, while the row is still//! `queued`, `withdrawn` — LWW settles nothing here because the two writers//! never touch the same column at the same time: a withdrawal races only a//! claim, and a Mac that claimed a row the owner withdrew in the same second//! starts a session the owner then sees on the list, which is the honest//! outcome.//!//! ## The conversation//!//! [`ensure_conversation`] is the second entry point, and the only place a row//! with `kind = 'conversation'` is written. One per project, host-owned, on//! any Mac, opened with the standing prompt. Its id is DERIVED from the//! project (`protocol::derived_id::project_conversation_id`), so two devices//! asking at once arrive at the SAME row and the per-column fold merges them —//! where two minted uuids would be one row and one rejection parked for ever//! against the partial unique index.//!//! "A conversation has a project" is enforced HERE, at the birth, and not by a//! CHECK: a synced row arrives as a fragment, one op per column stamp, so a//! CHECK spanning `kind` and `project_id` is exactly what a synced table may//! not carry (`cotton-store/tests/no_cross_column_checks.rs`).use serde_json::{json, Map, Value};use cotton_core::rules::conversation_prompt::{conversation_prompt, conversation_title};use cotton_core::rules::session_model::OFFERED_MODELS;use cotton_store::link_rule::FileKind;use cotton_store::protocol::derived_id::project_conversation_id;use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{insert_row, maybe_row, now_iso, update_row, utf16_clip};use crate::mcp::read_db::{Filter, Query};/// The first prompt's ceiling — the same as a session message body's.pub const SESSION_PROMPT_MAX: usize = 8000;/// The title's ceiling — `claude --name` shows it in a prompt box.pub const SESSION_TITLE_MAX: usize = 140;/// How much of a prompt becomes a title when the owner gave none.////// EIGHTY, and the FIRST LINE only: a card shows one line, and a title made of/// a whole paragraph is a card that says nothing at a glance. The owner's own/// `title` outranks this, always.pub const TITLE_FROM_PROMPT_MAX: usize = 80;/// What kind of session a row is — `cotton_sessions.kind` (schema v31).#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pub enum SessionKind {    /// A project's ONE standing conversation: what the owner talks to, never    /// withdrawn    /// by the phone, and the thing that opens threads.    Conversation,    /// Everything else — a session the owner started from the app, or one a    /// conversation opened to do a piece of work.    #[default]    Thread,}impl SessionKind {    #[must_use]    pub fn as_str(self) -> &'static str {        match self {            SessionKind::Conversation => "conversation",            SessionKind::Thread => "thread",        }    }    /// The word as the file spells it, or `None` for anything else.    #[must_use]    pub fn parse(value: &str) -> Option<SessionKind> {        match value {            "conversation" => Some(SessionKind::Conversation),            "thread" => Some(SessionKind::Thread),            _ => None,        }    }}#[derive(Debug, Default, Clone)]pub struct CreateArgs {    /// The DEVICE the work is placed on — a key the owner admitted. **`None` is    /// "any Mac"**, which is the ordinary case: the dispatcher picks one and    /// writes `chosen_by = 'dispatcher'`.    pub device_id: Option<String>,    pub account: Option<String>,    /// The project's SLUG, which is what a screen and an assistant both hold.    pub project_slug: Option<String>,    /// The project by its ID, which is what a record's link holds: a todo's    /// page hands its own `project` over as it reads it ("Hand to an agent").    /// The slug wins when both are named.    pub project_id: Option<String>,    /// The todo this session was handed. The session carries the link; nothing    /// changes on the todo row, and completing it stays the owner's    /// ([manual-items-become-cotton-todos]).    pub todo_id: Option<String>,    /// The database `todo_id` is in when it is not this one (schema v53): a    /// session started from a project's todo lives in the personal database    /// and names the todo where it is.    pub todo_database: Option<String>,    pub tool: String,    pub model: Option<String>,    pub title: Option<String>,    pub prompt: String,    pub branch: Option<String>,    /// `None` takes the household's own default — see [`write_session`].    pub permission_mode: Option<String>,    /// What this row IS (schema v31). Everything the owner starts and    /// everything a conversation opens is a [`SessionKind::Thread`];    /// [`ensure_conversation`] is the only caller that says otherwise.    pub kind: SessionKind,    /// The CONVERSATION that opened this one (schema v31), where one did.    ///    /// A tool call carries no session identity, so a conversation names itself    /// explicitly — it is told its own row id in the standing prompt.    pub parent_session_id: Option<String>,}/// The agents the Code tool hosts. The session row's own CHECK says the same/// thing; this is where a caller hears it as a sentence.pub const SESSION_TOOLS: [&str; 2] = ["claude-code", "codex"];/// How a session opens. `bypass` is the DEFAULT and it is a setting, not a/// hard-coded choice ([sessions-start-in-bypass-permissions-mode-by-default-it-s-a-sett]).pub const PERMISSION_MODES: [&str; 2] = ["bypass", "ask"];/// Parse and refuse — the sentence a caller reads, and nothing else.////// The refusal is a plain `String` rather than either caller's error type:/// `cotton-ffi` wraps it in a `MethodError` and the MCP handler in a/// `ToolFailure`, and the SENTENCE is the same either way, which is the point/// of there being one validator.pub fn validate_create(request: &Value) -> Result<CreateArgs, String> {    let tool = optional(request, "tool").unwrap_or_else(|| "claude-code".to_string());    if !SESSION_TOOLS.contains(&tool.as_str()) {        return Err(format!(            "`tool` is one of {} — not `{tool}`",            SESSION_TOOLS.join(", ")        ));    }    let permission_mode = optional(request, "permissionMode");    if let Some(mode) = &permission_mode {        if !PERMISSION_MODES.contains(&mode.as_str()) {            return Err(format!(                "`permissionMode` is one of {} — not `{mode}`",                PERMISSION_MODES.join(", ")            ));        }    }    let model = optional(request, "model");    if let Some(model) = &model {        if !OFFERED_MODELS.iter().any(|(id, _)| id == model) {            return Err(format!(                "`model` is one of {} — not `{model}`",                OFFERED_MODELS                    .iter()                    .map(|(id, _)| *id)                    .collect::<Vec<_>>()                    .join(", ")            ));        }    }    let branch = optional(request, "branch");    if let Some(branch) = &branch {        let clean = branch            .chars()            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '/' | '-'));        if !clean || branch.starts_with('-') || branch.contains("/-") || branch.contains("..") {            return Err(                "`branch` is a name git accepts — letters, digits, `.`, `_`, `/`, `-`, not \                 starting with `-`"                    .to_string(),            );        }    }    // The prompt MAY be empty here: the agent then comes up listening for an    // instruction rather than with one to work on. `create_session` over MCP    // refuses one, because a thread opened with nothing to do is a Mac holding    // a terminal nobody is at.    let prompt = request        .get("prompt")        .and_then(Value::as_str)        .unwrap_or_default()        .trim()        .to_string();    Ok(CreateArgs {        device_id: optional(request, "deviceId"),        account: optional(request, "account"),        project_slug: optional(request, "projectSlug"),        project_id: optional(request, "projectId"),        todo_id: optional(request, "todoId"),        todo_database: optional(request, "todoDatabase"),        tool,        model,        title: optional(request, "title").map(|title| utf16_clip(&title, SESSION_TITLE_MAX)),        prompt: utf16_clip(&prompt, SESSION_PROMPT_MAX),        branch,        permission_mode,        kind: SessionKind::Thread,        parent_session_id: optional(request, "parentSessionId"),    })}/// The title a card shows for a session the owner gave no title to.////// The prompt's FIRST LINE, clipped to [`TITLE_FROM_PROMPT_MAX`]. `None` for a/// prompt with nothing in it, because "" on a card reads as a bug and the copy/// already has a word for a session with no title of its own.#[must_use]pub fn title_from_prompt(prompt: &str) -> Option<String> {    let first = prompt.lines().next().unwrap_or_default().trim();    if first.is_empty() {        return None;    }    Some(utf16_clip(first, TITLE_FROM_PROMPT_MAX))}fn optional(request: &Value, field: &str) -> Option<String> {    request        .get(field)        .and_then(Value::as_str)        .map(str::trim)        .filter(|value| !value.is_empty())        .map(str::to_string)}/// The project's FIRST repository url — the one a session about that project/// is started in. One reading for every opener: a conversation that carried/// none while its threads carried one was started in no folder at all.fn first_repo(repos: Option<&Value>) -> Option<String> {    // `repos` is a JSON column: one read path hands it back decoded (an    // array), another as the text the file holds. Both are the same list.    let repos = match repos {        Some(Value::String(raw)) => serde_json::from_str::<Value>(raw).unwrap_or(Value::Null),        Some(other) => other.clone(),        None => Value::Null,    };    repos        .as_array()        .and_then(|list| list.iter().find_map(|item| item.as_str().map(str::to_string)))}/// THE ONE BIRTH. Every opener — the phone's `session.create`, the MCP/// `create_session`, [`ensure_conversation`] — writes its row here.pub fn write_session(ctx: &mut Ctx<'_>, args: &CreateArgs) -> Result<Value, String> {    // The project carries the repo: its FIRST repo url is what the Mac resolves    // to a checkout. A project with none leaves `repo_url` null and the client    // falls back to its default checkout.    let mut repo_url: Option<String> = None;    let mut project_id: Option<String> = None;    if let Some(slug) = &args.project_slug {        let project = maybe_row(            ctx,            &Query::on("cotton_memory_projects")                .columns(&["id", "repos"])                .eq("slug", slug.clone()),        )        .map_err(|failure| failure.to_string())?        .ok_or_else(|| format!("no project with slug {slug}"))?;        project_id = project            .get("id")            .and_then(Value::as_str)            .map(str::to_string);        repo_url = first_repo(project.get("repos"));    } else if let Some(id) = &args.project_id {        let project = maybe_row(            ctx,            &Query::on("cotton_memory_projects")                .columns(&["id", "repos"])                .eq("id", id.clone()),        )        .map_err(|failure| failure.to_string())?        .ok_or_else(|| format!("no project with id {id}"))?;        project_id = Some(id.clone());        repo_url = first_repo(project.get("repos"));    }    let handed = check_todo(ctx, args)?;    // A CONVERSATION HAS A PROJECT, and that is settled here rather than by a    // CHECK — see the module note.    if args.kind == SessionKind::Conversation && project_id.is_none() {        return Err("a conversation belongs to a project — name one".to_string());    }    let id = match args.kind {        // Derived, so two devices opening one project's conversation land on        // one row rather than on a rejection.        SessionKind::Conversation => project_conversation_id(            ctx.file.namespace(),            project_id.as_deref().unwrap_or_default(),        ),        SessionKind::Thread => ctx.new_uuid(),    };    // A HANDED TODO IS THE PROMPT when the caller wrote none: its title, and    // its notes under it — the one place the words a todo starts a session    // with are composed, whoever hands it over.    match handed.filter(|_| args.prompt.is_empty()) {        Some(todo) => {            let mut args = args.clone();            args.prompt = utf16_clip(&todo_prompt(&todo.title, todo.notes.as_deref()), SESSION_PROMPT_MAX);            write_session_row(ctx, &args, &id, project_id, repo_url)        }        None => write_session_row(ctx, args, &id, project_id, repo_url),    }}/// The prompt a handed todo starts with: its title, and its notes under it/// where there are any. Anything more is said on the session's page.#[must_use]pub fn todo_prompt(title: &str, notes: Option<&str>) -> String {    let mut parts = vec![title.trim()];    if let Some(notes) = notes.map(str::trim).filter(|notes| !notes.is_empty()) {        parts.push(notes);    }    parts.join("\n\n")}/// The todo a session is handed, as this database holds it.struct HandedTodo {    title: String,    notes: Option<String>,}/// The database a session's todo is in, when it is not this one. Naming this/// very database is the same as naming none.fn todo_database<'a>(ctx: &Ctx<'_>, args: &'a CreateArgs) -> Option<&'a str> {    args.todo_database        .as_deref()        .filter(|database| *database != ctx.workspace_id)}/// THE TODO A SESSION IS HANDED IS ONE THAT EXISTS. `todo_id` is a soft/// reference since schema v53 (it may name a todo in another database), so no/// foreign key refuses an unknown id any more and this does: a todo in this/// database must be here, and one in another database is named by/// `todoDatabase`, which only the personal database — where sessions live —/// may write. Whether that other database holds the todo is the tools' door's/// to check, inside the token's reach; this file cannot read it.////// Answers the todo when this database holds it, so its words can be the/// prompt; one in another database is answered as none.fn check_todo(ctx: &Ctx<'_>, args: &CreateArgs) -> Result<Option<HandedTodo>, String> {    let Some(todo_id) = &args.todo_id else {        if args.todo_database.is_some() {            return Err("todoDatabase names the database of a todoId — name the todo too".to_string());        }        return Ok(None);    };    if todo_database(ctx, args).is_some() {        let kind = ctx.file_kind().map_err(|failure| failure.to_string())?;        if kind != FileKind::Personal {            return Err(                "a session lives in the personal database, so only it can name a todo in another \                 database"                    .to_string(),            );        }        return Ok(None);    }    let found = maybe_row(        ctx,        &Query::on("cotton_todos")            .columns(&["id", "title", "notes"])            .eq("id", todo_id.clone())            .filter(Filter::IsNull("trashed_at".to_string())),    )    .map_err(|failure| failure.to_string())?;    let Some(todo) = found else {        return Err(format!(            "no todo with id {todo_id} in this database — a todo in another database is named \             with todoDatabase"        ));    };    let text = |column: &str| todo.get(column).and_then(Value::as_str).map(str::to_string);    Ok(Some(HandedTodo { title: text("title").unwrap_or_default(), notes: text("notes") }))}/// The patch itself, with the id already decided.fn write_session_row(    ctx: &mut Ctx<'_>,    args: &CreateArgs,    id: &str,    project_id: Option<String>,    repo_url: Option<String>,) -> Result<Value, String> {    // THE HOUSEHOLD'S OWN DEFAULT, unless the caller said otherwise. The    // setting exists so a person decides once; a caller that omits the field    // must get what they chose rather than what this file hard-codes.    let permission_mode = match &args.permission_mode {        Some(mode) => mode.clone(),        None => household_permission_default(ctx),    };    let now = now_iso(ctx);    let mut patch = Map::new();    patch.insert("project_id".to_string(), or_null(project_id));    patch.insert("todo_id".to_string(), or_null(args.todo_id.clone()));    patch.insert(        "todo_database".to_string(),        or_null(todo_database(ctx, args).map(str::to_string)),    );    // The Mac the OWNER named, kept as the request even after the dispatcher    // has placed the row: "I asked for mac-b" and "it is on mac-b" are different    // facts, and a card that conflated them could not say a placement moved.    patch.insert(        "requested_device_id".to_string(),        or_null(args.device_id.clone()),    );    patch.insert("device_id".to_string(), or_null(args.device_id.clone()));    patch.insert("account".to_string(), or_null(args.account.clone()));    patch.insert("tool".to_string(), Value::from(args.tool.clone()));    patch.insert("model".to_string(), or_null(args.model.clone()));    patch.insert(        "title".to_string(),        or_null(            args.title                .clone()                .or_else(|| title_from_prompt(&args.prompt)),        ),    );    patch.insert("prompt".to_string(), Value::from(args.prompt.clone()));    patch.insert("repo_url".to_string(), or_null(repo_url));    patch.insert("branch".to_string(), or_null(args.branch.clone()));    patch.insert("permission_mode".to_string(), Value::from(permission_mode));    // Version 31 — what this row is, and which conversation opened it.    patch.insert("kind".to_string(), Value::from(args.kind.as_str()));    patch.insert(        "parent_session_id".to_string(),        or_null(args.parent_session_id.clone()),    );    // The owner picked the Mac, or nobody has yet. The dispatcher writes    // `dispatcher` on the row it places itself.    //    // A CONVERSATION IS ALWAYS THE OWNER'S, whatever Mac it lands on: it is    // opened because a person opened the project, so `chosen_by` says `owner`    // even though `requested_device_id` is NULL (any Mac).    patch.insert(        "chosen_by".to_string(),        if args.device_id.is_some() || args.kind == SessionKind::Conversation {            Value::from("owner")        } else {            Value::Null        },    );    patch.insert("state".to_string(), Value::from("queued"));    patch.insert("state_at".to_string(), Value::from(now.clone()));    // NOT NULL on the row, and the only honest answer for a session nothing has    // done yet: it was last touched when it was asked for.    patch.insert("last_active_at".to_string(), Value::from(now));    // A session Cotton will host, rather than one found in an agent's own    // transcript.    patch.insert("host_owned".to_string(), Value::Bool(true));    // Everything the Mac and the dispatcher own, left alone — see the module    // note.    patch.insert("claimed_at".to_string(), Value::Null);    patch.insert("started_at".to_string(), Value::Null);    patch.insert("ended_at".to_string(), Value::Null);    patch.insert("exit_code".to_string(), Value::Null);    patch.insert("external_id".to_string(), Value::Null);    patch.insert("hold_reason".to_string(), Value::Null);    patch.insert("report_message_id".to_string(), Value::Null);    patch.insert("error".to_string(), Value::Null);    insert_row(ctx, "cotton_sessions", id, patch).map_err(|failure| failure.to_string())?;    Ok(json!({        "id": id,        "state": "queued",        "kind": args.kind.as_str(),        "parentSessionId": or_null(args.parent_session_id.clone()),    }))}/// A project's standing conversation — the existing row, or a new one.////// IDEMPOTENT, and idempotent under a race: the id is derived from the/// project, so the second caller writes the same row rather than a second one./// The answer carries `created` so a caller can say which happened.pub fn ensure_conversation(ctx: &mut Ctx<'_>, project_id: &str) -> Result<Value, String> {    let project = maybe_row(        ctx,        &Query::on("cotton_memory_projects")            .columns(&["id", "slug", "name", "repos"])            .eq("id", project_id.to_string()),    )    .map_err(|failure| failure.to_string())?    .ok_or_else(|| format!("no project with id {project_id}"))?;    let slug = project        .get("slug")        .and_then(Value::as_str)        .unwrap_or_default()        .to_string();    let name = project        .get("name")        .and_then(Value::as_str)        .filter(|name| !name.is_empty())        .unwrap_or(&slug)        .to_string();    let id = project_conversation_id(ctx.file.namespace(), project_id);    // The row this project already has — by the DERIVED id, which is the one    // an earlier caller would have used, and then by the column, which is what    // catches a conversation minted before the id was derived.    let existing = maybe_row(        ctx,        &Query::on("cotton_sessions")            .columns(&["id", "state", "kind", "last_active_at"])            .eq("project_id", project_id.to_string())            .eq("kind", "conversation".to_string()),    )    .map_err(|failure| failure.to_string())?;    if let Some(row) = existing {        let found = row            .get("id")            .and_then(Value::as_str)            .unwrap_or(&id)            .to_string();        return Ok(json!({            "id": found,            "state": row.get("state").cloned().unwrap_or(Value::Null),            "kind": "conversation",            "created": false,        }));    }    let args = CreateArgs {        // ANY MAC. A conversation is not work placed on a machine the owner        // picked; it is what the owner talks to about the project, and the        // dispatcher puts it        // on whichever Mac is free.        device_id: None,        project_slug: Some(slug.clone()),        tool: "claude-code".to_string(),        // The standing prompt names the row it is about, which is why the id        // is minted before the row is written rather than by the insert.        prompt: conversation_prompt(&slug, &name, &id),        title: Some(utf16_clip(&conversation_title(&name), SESSION_TITLE_MAX)),        kind: SessionKind::Conversation,        ..CreateArgs::default()    };    // The project's repository, as a thread of it carries: the Mac starts the    // conversation in that checkout, and the dispatcher places it only on a    // Mac that has one.    let repo_url = first_repo(project.get("repos"));    let mut answer = write_session_row(ctx, &args, &id, Some(project_id.to_string()), repo_url)?;    if let Some(object) = answer.as_object_mut() {        object.insert("created".to_string(), Value::Bool(true));        // A conversation has no parent, and a null the caller has to read        // around is worse than an absent key.        object.remove("parentSessionId");    }    Ok(answer)}/// The household's `session_permission_default`, or `bypass` where no/// workspace row answers — the column's own default, said once here.fn household_permission_default(ctx: &mut Ctx<'_>) -> String {    maybe_row(        ctx,        &Query::on("cotton_workspaces")            .columns(&["id", "session_permission_default"])            .eq("id", ctx.workspace_id.to_string()),    )    .ok()    .flatten()    .and_then(|row| {        row.get("session_permission_default")            .and_then(Value::as_str)            .map(str::to_string)    })    .filter(|mode| PERMISSION_MODES.contains(&mode.as_str()))    .unwrap_or_else(|| "bypass".to_string())}/// `session.withdraw` — take back a session no Mac has started yet.pub fn write_withdraw(ctx: &mut Ctx<'_>, id: &str) -> Result<Value, String> {    let row = maybe_row(        ctx,        &Query::on("cotton_sessions")            .columns(&["id", "state", "external_id", "kind"])            .eq("id", id.to_string()),    )    .map_err(|failure| failure.to_string())?    .ok_or_else(|| format!("no session with id {id}"))?;    let state = row        .get("state")        .and_then(Value::as_str)        .unwrap_or_default()        .to_string();    let spawned = row        .get("external_id")        .and_then(Value::as_str)        .is_some_and(|id| !id.is_empty());    // A CONVERSATION IS NEVER WITHDRAWN. It is what the owner talks to and    // the process behind it is disposable: ending one is what the helper's    // idle rule does, and "take this back before a Mac picks it up" has no    // meaning for a row that is meant to be picked up again and again.    if row.get("kind").and_then(Value::as_str) == Some("conversation") {        return Err(            "a project's conversation is not withdrawn — it is what the owner talks to about \             the project, and the process behind it ends on its own"                .to_string(),        );    }    // `starting` IS withdrawable, but only before the agent exists: a row the    // helper has already answered for has a process behind it, and taking that    // row back would leave an agent running with nothing naming it.    let withdrawable = state == "queued" || (state == "starting" && !spawned);    if !withdrawable {        return Err(format!(            "the session is already {state}; only one nobody has started can be withdrawn"        ));    }    let now = now_iso(ctx);    let mut patch = Map::new();    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));    // It is not waiting for a Mac any more, so the sentence saying why it was    // would be the wrong thing on the card.    patch.insert("hold_reason".to_string(), Value::Null);    update_row(ctx, "cotton_sessions", id, patch).map_err(|failure| failure.to_string())?;    Ok(json!({ "id": id, "state": "withdrawn" }))}/// **WHETHER A SESSION CAN BE PICKED UP WHERE IT STOPPED.** Pure, so every arm/// is a test.////// Four facts, and each is a reason on its own:////// * **It is over.** `ended` or `failed` — a session that is still going does///   not need resuming, and one that is `queued` has not started./// * **Cotton started it.** `host_owned = 0` is somebody's own terminal that///   this Mac merely watched; nothing here can restart a process it never///   owned./// * **There is an agent session to continue.** `external_id` is the id///   `claude --resume` / `codex resume` is given. A row that never got one is a///   row whose agent never existed — see [`can_restart`] for what that row///   can do instead./// * **There is a Mac to do it on.** **The transcript lives on ONE Mac** — the///   agent's own record under its config directory, which nothing syncs — so a///   resume is placed on the Mac the session ran on or it is not placed at all.pub fn can_resume(    state: &str,    host_owned: bool,    external_id: Option<&str>,    device_id: Option<&str>,) -> bool {    matches!(state, "ended" | "failed")        && host_owned        && external_id.is_some_and(|id| !id.is_empty())        && device_id.is_some_and(|id| !id.is_empty())}/// **WHETHER A SESSION THAT NEVER BEGAN CAN BE ASKED FOR AGAIN.** Pure, so/// every arm is a test.////// A `failed` row whose `external_id` is empty is a session whose agent was/// never spawned: the claim closed it over a folder, a clone or a login/// (`cotton_client::session_host::executor::fail` hands the id back on/// exactly that path). There is no transcript to carry on from, so it is not/// a resume — but there is nothing lost either, and the whole of what the/// owner asked for (the prompt, the project, the Mac they named) is still on/// the row. A restart is that row queued again for the dispatcher to place/// afresh, on whichever Mac can take it NOW rather than the one that could/// not then.////// Only a `failed` row: an `ended` one with no agent id is a row some older/// build closed without ever recording one, and nothing here knows what it/// was. And only one Cotton hosts, for [`can_resume`]'s reason.pub fn can_restart(state: &str, host_owned: bool, external_id: Option<&str>) -> bool {    state == "failed" && host_owned && !external_id.is_some_and(|id| !id.is_empty())}/// Whether `session.resume` will take this row at all — a resume where there/// is an agent to continue, a restart where there never was one. THE ONE/// SPELLING the phone's Resume button reads (`canResume` on every session/// row) and the method refuses by, so the verb offered and the refusal given/// can never disagree.pub fn can_carry_on(    state: &str,    host_owned: bool,    external_id: Option<&str>,    device_id: Option<&str>,) -> bool {    can_resume(state, host_owned, external_id, device_id)        || can_restart(state, host_owned, external_id)}pub fn write_resume(ctx: &mut Ctx<'_>, id: &str) -> Result<Value, String> {    let row = maybe_row(        ctx,        &Query::on("cotton_sessions")            .columns(&[                "id",                "state",                "external_id",                "host_owned",                "device_id",                "requested_device_id",                "kind",                "project_id",            ])            .eq("id", id.to_string()),    )    .map_err(|failure| failure.to_string())?    .ok_or_else(|| format!("no session with id {id}"))?;    let state = row        .get("state")        .and_then(Value::as_str)        .unwrap_or_default()        .to_string();    let external = row.get("external_id").and_then(Value::as_str);    let device = row.get("device_id").and_then(Value::as_str);    let host_owned = row        .get("host_owned")        .is_some_and(|value| value.as_bool() == Some(true) || value.as_i64() == Some(1));    let now = now_iso(ctx);    let mut patch = Map::new();    patch.insert("state".to_string(), Value::from("queued"));    patch.insert("state_at".to_string(), Value::from(now.clone()));    patch.insert("last_active_at".to_string(), Value::from(now));    if can_resume(&state, host_owned, external, device) {        let device = device.unwrap_or_default().to_string();        // **THE MAC IT RAN ON, NAMED.** The transcript is on that machine and        // nowhere else, so this is not a placement the dispatcher may        // reconsider.        patch.insert(            "requested_device_id".to_string(),            Value::from(device.clone()),        );        patch.insert("device_id".to_string(), Value::from(device));        patch.insert("chosen_by".to_string(), Value::from("owner"));        // `external_id` IS NOT TOUCHED — see this function's own note.    } else if can_restart(&state, host_owned, external) {        // **A RESTART IS A FRESH PLACEMENT.** The row failed on a Mac before        // any agent ran there, and the Mac it failed on is the last one to        // try again first: the owner's own ask (`requested_device_id`) is        // kept, and `device_id` goes back to it — a named Mac, or NULL for        // "any", which is what the dispatcher's picking rule reads — so the        // session lands where it can start NOW. `machine` is the placement's        // name for the card and goes with it; the dispatcher writes both        // back when it places the row.        let asked = row            .get("requested_device_id")            .and_then(Value::as_str)            .filter(|asked| !asked.is_empty())            .map(str::to_string);        patch.insert("chosen_by".to_string(), or_null(asked.clone().map(|_| "owner".to_string())));        patch.insert("machine".to_string(), Value::Null);        patch.insert("device_id".to_string(), or_null(asked));    } else {        return Err(resume_refusal(&state, host_owned, external));    }    // A CONVERSATION FOLLOWS ITS PROJECT'S REPOSITORY at every start, not only    // at birth: the row is one per project and lives for ever, and the    // project's `repos` is a field a person edits. A conversation born before    // the project had a repository (or before the birth wrote one) would    // otherwise be claimed into no folder at all, every time — which is the    // failure the restart above exists to undo.    if row.get("kind").and_then(Value::as_str) == Some(SessionKind::Conversation.as_str()) {        if let Some(project_id) = row.get("project_id").and_then(Value::as_str) {            patch.insert(                "repo_url".to_string(),                or_null(project_repo(ctx, project_id)?),            );        }    }    // EVERY MARK OF THE LAST ENDING COMES OFF. A card that says how a session    // ended while it is going again is the wrong fact on the one line a person    // reads.    patch.insert("ended_at".to_string(), Value::Null);    patch.insert("exit_code".to_string(), Value::Null);    patch.insert("error".to_string(), Value::Null);    patch.insert("hold_reason".to_string(), Value::Null);    patch.insert("claimed_at".to_string(), Value::Null);    patch.insert("waiting_kind".to_string(), Value::Null);    patch.insert("waiting_ref".to_string(), Value::Null);    update_row(ctx, "cotton_sessions", id, patch).map_err(|failure| failure.to_string())?;    Ok(json!({ "id": id, "state": "queued" }))}/// The project's first repository, by the project's id — [`first_repo`] over/// the row, for a caller that holds an id rather than a slug.fn project_repo(ctx: &mut Ctx<'_>, project_id: &str) -> Result<Option<String>, String> {    let project = maybe_row(        ctx,        &Query::on("cotton_memory_projects")            .columns(&["id", "repos"])            .eq("id", project_id.to_string()),    )    .map_err(|failure| failure.to_string())?;    Ok(project.as_ref().and_then(|project| first_repo(project.get("repos"))))}/// Why a resume was refused, in the one sentence the phone shows.fn resume_refusal(state: &str, host_owned: bool, external_id: Option<&str>) -> String {    if !matches!(state, "ended" | "failed") {        return format!("the session is {state}; only one that has ended can be resumed");    }    if !host_owned {        return "this session was started in a terminal, not by Cotton, so Cotton cannot resume it"            .to_string();    }    if !external_id.is_some_and(|id| !id.is_empty()) {        // Only an `ended` row reaches here: a `failed` one with no agent id is        // restarted rather than refused (`can_restart`).        return "this session never reached an agent, so there is nothing to carry on from"            .to_string();    }    "the Mac this session ran on is not recorded, and its transcript is only on that Mac"        .to_string()}fn or_null(value: Option<String>) -> Value {    value.map_or(Value::Null, Value::from)}#[cfg(test)]#[path = "session_birth_tests.rs"]mod tests;