Cotton code
496 lines · 24.3 KB · RustRaw
//! How one of the person's OWN DEVICES writes: through the same tool handler an//! assistant calls, over the replica, into the outbox.//!//! Design P3. This module is the whole of "one implementation of who wins"//! ([one-implementation-of-who-wins-the-same-schema-and-conflict-rule]) as a//! compiled function rather than a claim about two ports of one algorithm. One//! caller now, one body: every device writes through [`crate::phone::write`],//! whose vocabulary is the whole tool surface. (The Mac's table browser had a//! second, CLOSED registry of seventeen verbs; H3 deleted the browser and the//! registry with it — the Mac's screens are the phone's.)//!//! The difference between them is a REGISTRY, not a write path. What happens to//! the row, the op, the HLC, the version and the outbox is identical, and that//! is the point: a todo ticked on the phone and a memory kept in the Mac's//! window are stamped the same way, and the fold on the far side cannot tell//! which device authored one except by its device id.//!//! **`Ctx::phone`, never `Ctx::new` or `Ctx::for_worker`.** A person pressing a//! button is not an assistant and not a worker. Two things follow and they are//! the whole of the difference: the write names THIS DEVICE'S live row as//! `Actor::Owner` or `Actor::Member`, so history attributes it to the person//! (the op itself is stamped with the FILE's author, `_meta.author_id`,//! like every op this file mints); and NOTHING IS AUDITED, because//! `cotton_mcp_audit` answers "what did an assistant do in my database".//! `cotton-tools` owns that constructor and this module never restates its//! rules.//!//! **The queue is the store's, not this module's.** `cotton_store::mint::mint`//! is the one write path: on a file held as a replica it folds the ops AND//! queues them in the outbox in the same transaction, so nothing here queues.use std::sync::Arc;use cotton_store::driver::Driver;use cotton_store::protocol::types::CottonOp;use cotton_tools::mcp::dispatch::{handler_for, Ctx, ToolServices};use serde_json::{json, Map, Value};/// Who is writing, and with what clock.pub struct WriteInput<'a> {    pub workspace_id: &'a str,    /// The open file's own, as [`crate::shell::file::ReadFile::identity`].    pub identity: &'a cotton_store::file_identity::FileIdentity,    pub owner_id: &'a str,    /// The FILE's author string (`device:<ulid>`) — the label the `Ctx` carries    /// for a screen. The op's own stamp is `_meta.author_id`, which the store    /// reads itself; this is never the actor.    pub device_id: &'a str,    /// THIS device's own key (`cotton_devices.device_id`, the Ed25519 key) —    /// what the owner or member actor is resolved from: the live    /// row this key holds in the file. `None` on a device with no identity    /// yet, which cannot author a write (see [`owner_actor`]).    pub device_key: Option<&'a str>,    pub clock: &'a dyn cotton_tools::clock::Clock,    pub random: Arc<dyn cotton_tools::random::Random>,    /// THE VAULT, when this write is one that needs it — and `None` every other    /// time, which is almost every time.    ///    /// A device has no vault rail: the master key lives in the server's memory    /// and `ToolServices::none()` says so, which is what makes `create_secret`    /// refuse by name on a phone. The capability — never the key — is what    /// this carries, when a caller passes one.    pub vault: Option<Arc<dyn cotton_tools::rails::VaultRail>>,    /// How this process holds the file — a copy, or the file it serves. Two    /// readers: the `activity` table's one record says WHICH file is being    /// read, and the store's `mint` queues a replica's ops and not a served    /// file's. A write with `None` here is REFUSED rather than given a    /// default, because guessing it either drops a replica's ops or queues a    /// served file's.    pub held: Option<cotton_tools::rails::FileHeld>,    /// No machine serves this copy yet — a device that started alone, or a    /// database made here and not yet taken — so this device is the file's    /// writer of record ([`cotton_tools::rails::ThisFile::unserved`]).    pub unserved: bool,    /// The kit the app keeps to (`cotton_core::kit::AppKit`), `None` for the    /// whole object ([`cotton_tools::rails::ThisFile::kit`]).    pub kit: Option<Arc<cotton_core::kit::AppKit>>,    /// The existing device key used by pairing and approval; never a package-specific key.    pub tool_signer: Option<cotton_tools::mcp::dispatch::ToolSigner>,}/// Run one tool handler as this device, and hand back what it wrote.////// The handler is called DIRECTLY rather than through `call_tool`, which gates/// on a token's scopes: there is no token here, and a device the owner approved/// is not a pasted credential with a narrower grant.////// The second half of the answer is the OPS the write minted. A server has no/// use for them — it IS the file, so a folded op is the truth. A device holding/// a replica does: there, a folded op is not a sent op.pub fn run_tool(    db: &Driver,    tool: &str,    args: &Map<String, Value>,    input: &WriteInput<'_>,) -> Result<(Value, Vec<CottonOp>), String> {    let Some(handler) = handler_for(tool) else {        return Err(format!("{tool} is not implemented on this build yet"));    };    run_with_ctx(db, input, &mut |ctx| {        handler(ctx, args).map_err(|failure| failure.to_string())    })}/// [`run_tool`] for a READ tool: the same handler lookup, over/// [`read_with_ctx`], so a device with no row in the file yet still reads./// The caller refuses and rolls back any op it minted.pub fn read_tool(    db: &Driver,    tool: &str,    args: &Map<String, Value>,    input: &WriteInput<'_>,) -> Result<(Value, Vec<CottonOp>), String> {    let Some(handler) = handler_for(tool) else {        return Err(format!("{tool} is not implemented on this build yet"));    };    read_with_ctx(db, input, &mut |ctx| {        handler(ctx, args).map_err(|failure| failure.to_string())    })}/// Run a BODY as this device, over the same context a tool handler runs on.////// [`run_tool`]'s own middle, lifted out so a caller that is not one tool can/// have it. Its callers are each honest about being more than a tool call:/// [`run_tool`] itself; [`author_through_outbox`], which is the phone's row/// writes (`capture.create`, `page.save`); and — through [`read_with_ctx`],/// which shares its body and differs only in who asks a read with no device/// row — `ClientController::read_rows`, the phone's COMPOSED reads, where one/// screen's answer is several tools plus a join and every part of it should/// still run through the handlers rather than beside them/// ([`crate::phone::traffic`]).////// **The write names the owner or member at this device** ([`owner_actor`]): a/// device whose key has no live row in the file is refused before any handler/// runs.////// **The `Ctx` is COMMITTED here, before the ops are read, and that is the/// whole reason this is one body rather than two.** `Writer::upsert` and/// `Writer::delete` only QUEUE; `ops` is populated at `commit()`. A copy of/// this function that read `written_ops()` without committing would answer an/// EMPTY list for a body that staged a write through a handler relying on/// caller-commit — which `author_through_outbox` explicitly supports — so/// `read_rows`' "this read wrote nothing" check would pass silently and the/// write would be dropped on `Ctx` drop. `author_through_outbox` had the/// commit and this did not, until 4g's review; folding them is what stops the/// two from drifting again.////// Committing is safe for a READ, because `read_rows` runs the whole thing/// inside a transaction it rolls back the moment `ops` is non-empty: the/// commit is what makes the write VISIBLE to that check, and the rollback is/// what undoes it.////// The ops come back for the same reason they do above: on a device a folded op/// is not a sent op, and a caller that is supposed to have written nothing needs/// to be able to prove it.pub fn run_with_ctx(    db: &Driver,    input: &WriteInput<'_>,    body: &mut dyn FnMut(&mut Ctx<'_>) -> Result<Value, String>,) -> Result<(Value, Vec<CottonOp>), String> {    let actor = owner_actor(db, input)?;    run_as(db, input, actor, body)}/// [`run_with_ctx`] for a READ — a caller that refuses and rolls back any op/// the body mints (`ClientController::read_tool`/`read_rows` and their served/// twins).////// The one difference: a device whose key has no live row in the file — a/// serving Mac with no identity yet, a replica before its approval arrived —/// still READS its own file. A `Ctx` needs an actor to exist at all, so a read/// with no owner row is asked by the job [`SCREEN_READ_JOB`]. That is NOT a/// fallback for a write: on a replica the store refuses a job actor outright/// (`fold::actor_may_be_named_by`), and on a served file every caller of this/// function refuses and rolls back whatever the read minted, so the job never/// stamps an op that survives.pub fn read_with_ctx(    db: &Driver,    input: &WriteInput<'_>,    body: &mut dyn FnMut(&mut Ctx<'_>) -> Result<Value, String>,) -> Result<(Value, Vec<CottonOp>), String> {    let actor = match owner_row(db, input).map_err(|error| error.to_string())? {        Some(row_id) => device_actor(db, &row_id)?,        None => cotton_store::actor::Actor::Job(            cotton_store::actor::JobName::named(SCREEN_READ_JOB)                .map_err(|error| error.to_string())?,        ),    };    run_as(db, input, actor, body)}/// The job a READ with no owner row is asked by — see [`read_with_ctx`].pub const SCREEN_READ_JOB: &str = "screen-read";/// The refusal a write from a device with no row gets. A plain sentence,/// because a screen draws it.pub const NO_DEVICE_ROW: &str = "this device has no row in the file yet, so it cannot author a \                                 write — it arrives with the first pull after approval";/// The live `cotton_devices` row id this device's KEY holds, or `None` for a/// device with no key or no live row (a revoked row is not one).fn owner_row(db: &Driver, input: &WriteInput<'_>) -> cotton_store::Result<Option<String>> {    let Some(key) = input.device_key.filter(|key| !key.is_empty()) else {        return Ok(None);    };    let row = cotton_tools::devices::FileDevices::new(db).row_for(key)?;    Ok(row.filter(|row| row.revoked_at.is_none()).map(|row| row.id))}/// Who asks a write at this screen: the owner or admitted member at this/// device, according to the live row its key holds in the file. A device with/// no key or no live row is REFUSED, never handed a job actor: a write the/// file cannot attribute to an admitted device cannot be authored here.pub fn owner_actor(    db: &Driver,    input: &WriteInput<'_>,) -> Result<cotton_store::actor::Actor, String> {    let Some(row_id) = owner_row(db, input).map_err(|error| error.to_string())? else {        return Err(NO_DEVICE_ROW.to_string());    };    device_actor(db, &row_id)}fn device_actor(db: &Driver, row_id: &str) -> Result<cotton_store::actor::Actor, String> {    use cotton_store::actor::{Actor, DeviceId};    let device = DeviceId::in_file(db, row_id).map_err(|error| error.to_string())?;    let member = db.get("SELECT person_key FROM cotton_devices WHERE id = ?", &[row_id.to_string().into()])        .map_err(|error| error.to_string())?        .is_some_and(|row| row.text("person_key").is_some_and(|key| !key.trim().is_empty()));    if member {        Actor::member(db, device).map_err(|error| error.to_string())    } else {        Ok(Actor::Owner(device))    }}/// The one body under [`run_with_ctx`] and [`read_with_ctx`].fn run_as(    db: &Driver,    input: &WriteInput<'_>,    actor: cotton_store::actor::Actor,    body: &mut dyn FnMut(&mut Ctx<'_>) -> Result<Value, String>,) -> Result<(Value, Vec<CottonOp>), String> {    let held = match input.held {        Some(cotton_tools::rails::FileHeld::Replica) => cotton_store::mint::Held::Replica,        Some(cotton_tools::rails::FileHeld::Served) => cotton_store::mint::Held::Served,        None => {            return Err("this write does not say how the file is held — a replica queues its \                        ops and a served file does not, so it is refused rather than guessed"                .to_string())        }    };    // The capabilities a device cannot supply — `documents`, `media`,    // `meaning` — are all absent here, and the handlers that need    // one refuse out loud rather than half-working. That is already their    // contract; this is simply the honest bag for a caller that has none of    // them.    let services = ToolServices {        vault: input.vault.clone(),        this_file: input.held.map(|held| cotton_tools::rails::ThisFile {            held,            // A serving Mac with no identity yet reads under an empty id.            device_id: Some(input.device_id.to_string()).filter(|id| !id.is_empty()),            unserved: input.unserved,            kit: input.kit.clone(),        }),        tool_signer: input.tool_signer.clone(),        ..ToolServices::none()    };    let mut ctx = Ctx::phone(        db,        input.identity,        input.owner_id,        input.device_id,        actor,        held,        input.clock.now(),        Arc::clone(&input.random),        &services,    );    // The local app authenticates its device key against this file above.    // Engine views use the same reader identity as a signed remote call;    // without it a local Storage root cannot recognize its own device.    if let Some(key) = input.device_key {        ctx = ctx.signed_by(key);    }    let answer = body(&mut ctx)?;    // Idempotent: a body that already committed staged nothing more, and one    // that did not is minted here rather than being lost when the `Ctx` drops    // — folded, and on a replica queued, by the store's `mint`. Either way the    // ops are read AFTER the fold.    ctx.commit().map_err(|failure| failure.to_string())?;    let ops = ctx.written_ops().to_vec();    Ok((answer, ops))}/// Run one tool against a REPLICA: write the row and queue the op. Nothing more.////// The row and its op land TOGETHER or neither does. The handler mints through/// the tool surface's own writer — which is right, because the row it writes/// has to look exactly like the server's — and the store's `mint`, asked with/// `Held::Replica`, folds the row AND queues its op in one transaction: a row/// folded into a replica with no op beside it would be a write that can never/// leave this device, and the one write path is what rules that out. The/// transaction here nests as a savepoint around the handler's own.////// **The push is not here, and must never come back here.** The file is the/// truth, the screen is a view of the file, and the network is a background/// process: a write commits, answers, and the SYNC LOOP carries the op/// (`ClientController::write` wakes it). Until 2026-09-24 this function took a/// `push` closure and ran it — an HTTP round trip with a 60 s ceiling — while/// its caller held the replica's mutex, the same mutex every `read.*` on the/// phone takes. Every screen read after any edit queued behind that request,/// and the `data` event that redraws the screen was not emitted until the/// request returned. A write that waits on the network is a write that makes/// the phone look broken exactly when the Mac is asleep.////// So **a write does not fail because the server is unreachable**, and it does/// not wait to find out: the answer says how many ops are queued, the loop's/// own status (`SyncStatus::pending`) says how many are still waiting, and/// refusing the write because the home Mac is asleep would throw away/// something the person already did. Guard: `client_tests.rs`'s "a write/// never asks the transport", `authoring_tests.rs`'s envelope tests.pub fn write_through_outbox(    db: &Driver,    tool: &str,    args: &Map<String, Value>,    input: &WriteInput<'_>,) -> Result<Value, String> {    let (answer, ops) = db        .transaction(|db| {            // The commit inside `run_tool` already queued the ops: `mint`            // queues a replica's own writes.            run_tool(db, tool, args, input).map_err(cotton_store::StoreError::refused)        })        .map_err(|error| error.to_string())?;    Ok(queued_answer(answer, &ops))}/// The envelope both callers answer in.////// The tool's own answer is NESTED rather than merged, so a handler that one/// day answers a `queued` of its own cannot silently overwrite the outbox's/// report of the same name. `rail`, `queued` and `tables` are this layer's/// three words; each caller adds the one field that names what it called/// (`tool` for the tool rail, `method` for a row write).////// **There is no `pushed` and no `notPushed`, on purpose.** A write hands its/// op to the sync loop and answers; whether the op has LEFT is a fact the loop/// owns and reports through `SyncStatus::pending`, never a count this envelope/// could truthfully carry. The two words used to be here, filled by an inline/// push, and a screen reading `notPushed` was reading a sentence about a/// request that should never have run on its thread.////// **`tables` is the invalidation** (design P5). The replica IS the cache, so/// there is nothing to expire — what a screen needs to know is which tables/// moved, and it comes from the ops the write actually minted rather than from/// re-reading `_ops`. That is the same rule the PULL half holds for the same/// reason it was written down: deriving it from the log meant no tick moved and/// no reply appeared until the screen was re-opened (2026-08-26).pub fn queued_answer(answer: Value, ops: &[CottonOp]) -> Value {    json!({        "answer": answer,        "rail": "client",        "queued": ops.len(),        "tables": tables_touched(ops),        "rows": rows_touched(ops),    })}/// Whether a write's envelope ([`queued_answer`]) left anything in the outbox/// for the sync loop to carry. A write that minted no op has nothing to send,/// so it asks for no pass: `vault::take_own_key` runs after every pass that/// brought rows, each pass's heartbeat on the device row brings rows to the/// next, and its empty write woke the loop every time, so a signed-in phone/// synced back to back for as long as it was open (iPhone sealed-tables walk/// of Todos, 16 Nov 2026: five dials a second, the app never at rest). An/// envelope that does not say counts as carrying.pub fn carries(answer: &serde_json::Map<String, Value>) -> bool {    answer.get("queued").and_then(Value::as_u64).is_none_or(|queued| queued > 0)}/// How many rows a write names on its `data` event before it names only/// their tables: a bulk write reads every list over them again.pub const MOST_ROWS_NAMED: usize = 128;/// Every row these ops moved, `{table, id, kind}` once each, in the order/// they were written (`kind` the last op's, `upsert` or `delete`) — null/// past [`MOST_ROWS_NAMED`]: a reader that kept a list patches it for these/// rows alone (`shell_list`), and reads it whole when none are named.pub fn rows_touched(ops: &[CottonOp]) -> Value {    let mut rows: Vec<(String, String, &'static str)> = Vec::new();    for op in ops {        match rows.iter_mut().find(|(table, id, _)| table == &op.table && id == &op.row_id) {            Some(row) => row.2 = op.kind.as_str(),            None => rows.push((op.table.clone(), op.row_id.clone(), op.kind.as_str())),        }        if rows.len() > MOST_ROWS_NAMED { return Value::Null; }    }    Value::Array(rows.into_iter().map(|(table, id, kind)| json!({"table": table, "id": id, "kind": kind})).collect())}/// The BODY's own answer, lifted back out of the envelope.////// **A phone METHOD answers its own shape; the envelope is `write`'s alone.**/// That is one rule with two readers and this is where it is written down,/// beside the function that puts the envelope on.////// `write` is the tool rail: the app asks for a tool by name, gets no shape it/// declared, and reads `tables` off the answer to know what moved/// (`WriteAnswer`, `apps/cotton/Sources/CottonKit/Boundary.swift`). Every OTHER/// method on the bus is a named door with a shape the boundary declares/// (`MeetingCreated` is one, `PagesSaved` another) — and a screen that had to/// reach through `answer` to find it would be reading a wrapper it never asked/// for, in a key the boundary's own table does not list.////// **Nothing is lost by lifting it.** `tables` is not the invalidation for/// these callers: [`crate::shell::client::ClientController::write_rows`] emits/// the `data` event carrying `tables` ITSELF, before it answers, so the/// re-read has already been asked for by the time the caller sees this.////// An answer that is not an object passes straight through — a body that/// answered a bare value was never wrapped in the first place.pub fn own_answer(answer: Value) -> Value {    match answer.get("answer") {        Some(body) => body.clone(),        None => answer,    }}/// Every table these ops moved, once each, in the order they were written.////// Order preserved rather than sorted: a screen that redraws in the order the/// write happened is redrawing in the order the person will read it.pub fn tables_touched(ops: &[CottonOp]) -> Vec<String> {    let mut tables: Vec<String> = Vec::new();    for op in ops {        if !tables.iter().any(|seen| seen == &op.table) {            tables.push(op.table.clone());        }    }    tables}#[cfg(test)]#[path = "authoring_tests.rs"]mod tests;// ─────────────────────────────────────────────────────────────────────────────// The same write path, without a tool handler in the middle (4p §3).// ─────────────────────────────────────────────────────────────────────────────/// Author as this device, over the ROW WRITER rather than through a tool.////// **This is not a second write path and it must never become one.** Everything/// below the body is [`write_through_outbox`]'s, function for function: the/// same `Ctx::phone` (the owner at this device, no audit row), the same/// `Writer`, the same one transaction around the fold and the queue, the/// same [`queued_answer`] envelope with `tables` as the invalidation, and the/// same absence of a push — the loop carries the op. The only difference is/// WHO fills the writer — a tool handler there, the caller's own closure here.////// WHY IT HAS TO EXIST. Four of the phone's methods write rows that the tool/// surface deliberately has no verb for, and each absence is a WRITTEN REASON/// rather than a gap:////// * a capture — `create_thought` is a refusal in `crates/cotton-core/src/primitives.rs`///   ("a thought is something the person said"), so an assistant has no way to///   put words in the person's mouth;/// * a photo, a video or a document the person just picked — the record row///   goes in beside a `_media` ledger row on this device, and no tool can write///   a ledger row because the ledger is device-local and never synced;/// * dictation corpus rows — only the app records what the person said;/// * saved pages — the share sheet authors them, and create_page is refused.////// A tool invented for any of these would be a tool an assistant could then/// call, which is exactly what these refusals are for. So the phone/// writes the row itself — through the one write path there is.pub fn author_through_outbox(    db: &Driver,    input: &WriteInput<'_>,    body: &mut dyn FnMut(&mut Ctx<'_>) -> Result<Value, String>,) -> Result<Value, String> {    let (answer, ops) = db        .transaction(|db| {            // ONE body, shared with `run_tool` and with the composed reads:            // the `Ctx`, the absent rails, the commit and the op read all live            // in `run_with_ctx`. A second copy of them here is how the commit            // came to be in one and not the other. The commit's `mint` queued            // the ops; nothing here queues them again.            run_with_ctx(db, input, body).map_err(cotton_store::StoreError::refused)        })        .map_err(|error| error.to_string())?;    Ok(queued_answer(answer, &ops))}