Cotton code
457 lines · 27.2 KB · RustRaw
//! The rest of what a walk needs to look at: documents in every state a//! filed paper can be in, the email cases beyond a plain thread, saved pages,//! the names of what the vault holds, and coding sessions.//!//! A secret is sealed only when the caller hands in the household's vault//! (`seed_household_sealed`; `cotton-headless seed` founds one first): the//! vault's key is the server's, never the generator's, and without it the//! rows are names with nothing sealed, which is a state the vault itself has.//!//! WHAT IS NOT HERE, because nothing honest can be written without it://! an article's text (the serving Mac pulls it in from the address, and these//! addresses are example ones nothing answers at), and an email's HTML (the//! archive keeps text).use crate::synthetic::paper;use crate::synthetic::picture::Scene;use sha2::{Digest, Sha256};use super::{call, iso, object, refused, Household};use crate::mcp::handlers::common::{insert_row, update_row};use crate::mcp::handlers::emails::ingest::ingest_emails;use crate::mcp::handlers::emails::senders::block_sender;use crate::mcp::handlers::emails::state::update_email;use crate::mcp::handlers::projects::write::link_to_project;use crate::mcp::handlers::records_2::sessions::log_session;use chrono::Duration;use cotton_core::media::keys::message_media_key;use cotton_store::protocol::derived_id;use cotton_store::{Result, StoreError};use serde_json::{json, Value};/// Every table written here, for the household's recount.pub(super) const TABLES: &[&str] = &[    "cotton_mcp_tokens",    "cotton_documents",    "cotton_emails",    "cotton_email_threads",    "cotton_blocked_senders",    "cotton_secrets",    "cotton_secret_placements",    "cotton_sessions",    "cotton_prompts",    "cotton_session_messages",    "cotton_memory_projects",    "cotton_money_transactions",];/// A Mac that is nobody's: a session or a placement that names it is never/// picked up, because no machine holds its key.const NOBODYS_MAC: &str = "device:synthetic-mac";/// `(title, file name, mime, type, issuer, pages, days back, state)`.type Paper = (&'static str, &'static str, &'static str, &'static str, Option<&'static str>, i64, i64, &'static str);impl Household<'_> {    /// Invented assistants for Disconnect and both Remove states. These hashes    /// have no generated token behind them; the seed never creates a usable secret.    pub(super) fn write_assistants(&mut self) -> Result<()> {        let env = &self.env;        let at = env.now - Duration::days(60);        for (i, name, expired, disconnected) in [            (0, "Example planning assistant", false, false),            (1, "Example retired assistant", false, true),            (2, "Example expired assistant", true, false),        ] {            let id = derived_id::derived_id("cotton_mcp_tokens", &[env.workspace_id, "synthetic-assistant", name]);            env.once(at, |ctx| {                let args = object(json!({                    "owner_user_id": env.owner_id, "name": name,                    "token_hash": format!("{:064x}", i + 1), "scopes": "[\"read\"]",                    "created_at": iso(at),                    "expires_at": expired.then(|| iso(at + Duration::days(30))),                }));                insert_row(ctx, "cotton_mcp_tokens", &id, args).map_err(refused("assistant"))?;                ctx.commit().map_err(refused("assistant"))            })?;            if disconnected {                env.once(at + Duration::days(15), |ctx| {                    let writer = ctx.writer().map_err(refused("assistant"))?;                    let by = writer.actor().to_wire();                    writer.revoke("cotton_mcp_tokens", &id, "revoked", None, None, &by)?;                    ctx.commit().map_err(refused("assistant"))                })?;            }            self.counts.add("cotton_mcp_tokens", 1);        }        Ok(())    }    /// `cotton_documents` patches in the documents    /// pipeline's FINISHED shapes — ready, locked, failed; never processing,    /// which a served household's worker would pick up and fail for want of    /// bytes.    pub(super) fn write_documents(&mut self) -> Result<()> {        let env = &self.env;        let projects = &self.projects;        let papers: [Paper; 10] = [            ("Passport", "passport-scan.pdf", "application/pdf", "id", None, 2, 400, "ready"),            ("Driving licence", "licence.jpg", "image/jpeg", "id", None, 1, 380, "ready"),            ("Hardware shop receipt", "receipt-0412.jpg", "image/jpeg", "receipt", Some("Quarry Lane Hardware"), 1, 9, "ready"),            ("Tenancy agreement", "tenancy-agreement.pdf", "application/pdf", "legal", Some("Harbour Lettings"), 6, 300, "ready"),            ("Kitchen quote", "quote-kitchen.pdf", "application/pdf", "invoice", Some("Larkspur Joinery"), 3, 30, "ready"),            ("Home insurance schedule", "schedule.pdf", "application/pdf", "insurance", Some("Meridian Mutual"), 4, 120, "ready"),            ("Boiler manual", "boiler-manual.pdf", "application/pdf", "manual", None, 48, 500, "ready"),            ("Ferry tickets", "tickets.pdf", "application/pdf", "ticket", Some("Harbour Ferries"), 1, 4, "ready"),            ("Tax summary", "tax-summary.pdf", "application/pdf", "tax", None, 0, 14, "locked"),            ("Old insurance scan", "scan0007.pdf", "application/pdf", "other", None, 0, 60, "failed"),        ];        env.once(env.now, |ctx| {            for (title, name, mime, doc_type, issuer, pages, back, state) in papers {                ctx.now = env.now - Duration::days(back);                let sha = env.hex(64);                let id = derived_id::document_id(env.file.namespace(), &sha);                let ext = name.rsplit('.').next().unwrap_or("pdf");                let mut row = object(json!({                    "title": title, "original_name": name, "mime": mime,                    "byte_size": env.rng().between(30_000, 3_000_000), "sha256": sha,                    "storage_path": cotton_core::media::keys::document_original_key(env.file.id(), &id, ext),                    "status": state, "status_changed_at": iso(ctx.now), "doc_type": doc_type,                    "source": if back % 2 == 0 { "app" } else { "share" },                }));                if let Some(issuer) = issuer {                    row.insert("issuer".into(), Value::from(issuer));                }                match state {                    // A password nobody has given yet.                    "locked" => {                        row.insert("error_code".into(), Value::from("password_required"));                    }                    "failed" => {                        row.insert("failed_stage".into(), Value::from("extract"));                        row.insert("error_code".into(), Value::from("nothing_to_read"));                    }                    _ => {                        row.insert("page_count".into(), Value::from(pages));                        row.insert("summary".into(), Value::from(env.sentences(1, 2)));                        row.insert("document_date".into(), Value::from(super::day(ctx.now - Duration::days(2))));                        // What the reader found worth showing beside the summary.                        if matches!(doc_type, "invoice" | "receipt") {                            row.insert(                                "facts".into(),                                json!({ "total_minor": 1_250 * (i64::from(pages) + 3), "currency": "EUR", "invoice_number": format!("INV-{:04}", back) }),                            );                        }                    }                }                insert_row(ctx, "cotton_documents", &id, row).map_err(refused("document"))?;                ctx.commit().map_err(refused("document"))?;                if title == "Kitchen quote" || title == "Tenancy agreement" {                    if let Some(slug) = projects.first() {                        let args = object(json!({ "project": slug, "records": [{ "kind": "document", "id": id }] }));                        call("document in a project", link_to_project(ctx, &args))?;                    }                }            }            Ok(())        })    }    /// `ingest_emails` for a long thread between several people, mail with    /// attachments (their bytes stored, as a chat's are) and a newsletter;    /// `update_email {starred | inbox: false | bin | read: false}`;    /// `block_sender`.    pub(super) fn write_email_shapes(&mut self) -> Result<()> {        let env = &self.env;        let people = &self.people;        if people.len() < 4 {            return Ok(());        }        let me = json!({ "email": super::OWNER_EMAIL, "name": "Me" });        let them = |n: usize| json!({ "email": people[n].email, "name": people[n].name });        let mut emails: Vec<Value> = Vec::new();        // Eleven messages, four people, somebody copied in half-way.        for n in 0..11usize {            let sent = env.now - Duration::days(6) + Duration::hours(5 * n as i64);            let (from, to) = if n % 4 == 3 { (me.clone(), vec![them(0), them(1)]) } else { (them(n % 3), vec![me.clone(), them((n + 1) % 3)]) };            let mut email = json!({                "threadKey": "synthetic-long-thread",                "subject": if n == 0 { "The hall booking for the spring fair".to_string() } else { "Re: The hall booking for the spring fair".to_string() },                "sentAt": iso(sent), "body": env.sentences(1, 4), "from": from, "to": to,                "messageId": format!("<synthetic-long-{n}@example.com>"),            });            if n >= 5 {                email["cc"] = json!([them(3)]);            }            emails.push(email);        }        // Each attachment's bytes really there, content-addressed under its        // conversation's folder the way a chat's media is (`message_media_key`)        // and handed to the media sink, so the phone's Fetch delivers it.        let namespace = env.file.namespace();        let stored = |key: &str, name: &str, bytes: &[u8], mime: &str, ext: &str| -> Result<Value> {            let thread = derived_id::derived_id("cotton_email_threads", &[namespace.as_str(), key]);            let object = message_media_key(env.file.id(), &thread, &hex::encode(Sha256::digest(bytes)), ext);            self.put(&object, bytes)?;            Ok(json!({ "name": name, "mime": mime, "size": bytes.len(), "key": object }))        };        let picture = |n: u32| Scene::draw(env.rng()).png(320 + n * 8, 240);        let quote = paper::pdf("Quote 0412", &["Clearing the side bed and laying the path: two days.", "Materials as listed, delivered on the Monday.", "Valid for thirty days."]);        let directions = paper::pdf("Directions", &["From the station, left onto the high street.", "Past the church, second right by the green gate.", "Park on the lane; the hall is the low building at the end."]);        let attached = [            ("synthetic-attached-quote", "Your quote, as promised", 3, Value::Array(vec![                stored("synthetic-attached-quote", "Quote 0412.pdf", &quote, "application/pdf", "pdf")?,            ])),            ("synthetic-attached-photos", "Photos from Saturday", 2, Value::Array(vec![                stored("synthetic-attached-photos", "IMG_2201.png", &picture(0), "image/png", "png")?,                stored("synthetic-attached-photos", "IMG_2202.png", &picture(1), "image/png", "png")?,                stored("synthetic-attached-photos", "Directions.pdf", &directions, "application/pdf", "pdf")?,            ])),        ];        for (key, subject, back, attachments) in attached {            emails.push(json!({                "threadKey": key, "subject": subject, "sentAt": iso(env.now - Duration::days(back)),                "body": env.sentences(2, 4), "from": them(1), "to": [me.clone()], "attachments": attachments,                "messageId": format!("<{key}@example.com>"),            }));        }        for (key, subject, from, back) in [            ("synthetic-starred", "Keys are with the neighbour at number 9", them(2), 8),            ("synthetic-archived", "Thank you for coming", them(3), 20),            ("synthetic-binned", "A survey about your recent visit", json!({ "email": "survey@visits.example.org", "name": "Visitor Survey" }), 5),            ("synthetic-unread-1", "Can you do Thursday instead?", them(0), 0),            ("synthetic-unread-2", "Minutes of the last meeting", them(1), 1),        ] {            emails.push(json!({                "threadKey": key, "subject": subject, "sentAt": iso(env.now - Duration::days(back) - Duration::hours(2)),                "body": env.sentences(1, 3), "from": from, "to": [me.clone()], "messageId": format!("<{key}@example.com>"),            }));        }        // Two RECORDS from services, typed as they land (the reader reads the        // subject and body): a receipt — the thread a person records as a        // transaction — and a ticket — the one added to the calendar. The        // newest mail, so the first page of the list shows both.        for (key, subject, body, from) in [            ("synthetic-receipt", "Your receipt from Quay Street Grocer",                "Order number: QS-20817\nPaid on 11 Oct 2026\nTotal: €42.50",                json!({ "email": "receipts@quaystreet.example.org", "name": "Quay Street Grocer" })),            ("synthetic-ticket", "E-ticket: Harbour Ferry to Larkspur Point",                "Booking reference: HF7Q21\nDate of journey: 24 Oct 2026",                json!({ "email": "tickets@harbourferry.example.org", "name": "Harbour Ferry" })),        ] {            emails.push(json!({                "threadKey": key, "subject": subject, "sentAt": iso(env.now - Duration::minutes(30)),                "body": body, "from": from, "to": [me.clone()], "messageId": format!("<{key}@example.org>"),            }));        }        for n in 0..3 {            emails.push(json!({                "threadKey": format!("synthetic-newsletter-{n}"), "subject": format!("This week's offers, issue {}", 40 + n),                "sentAt": iso(env.now - Duration::days(7 * (n + 1))), "body": env.sentences(2, 5),                "from": { "email": "offers@letters.example.org", "name": "Larkspur Offers" }, "to": [me.clone()],                "messageId": format!("<synthetic-newsletter-{n}@letters.example.org>"),            }));        }        env.once(env.now, |ctx| {            let out = call("email", ingest_emails(ctx, &object(json!({ "emails": emails }))))?;            let threads = out.get("threads").and_then(Value::as_array).cloned().unwrap_or_default();            let thread = |subject: &str| -> Result<String> {                threads                    .iter()                    .find(|thread| thread.get("subject").and_then(Value::as_str) == Some(subject))                    .and_then(|thread| thread.get("threadId").and_then(Value::as_str))                    .map(str::to_string)                    .ok_or_else(|| StoreError::refused(format!("synthetic household: email: no thread came back for {subject:?}")))            };            for (subject, change) in [                ("Keys are with the neighbour at number 9", json!({ "starred": true })),                ("Thank you for coming", json!({ "inbox": false })),                ("A survey about your recent visit", json!({ "bin": true })),                ("Can you do Thursday instead?", json!({ "read": false })),                ("Minutes of the last meeting", json!({ "read": false })),                ("The hall booking for the spring fair", json!({ "read": false, "starred": true })),            ] {                let mut args = object(change);                args.insert("threadId".into(), Value::from(thread(subject)?));                call("email state", update_email(ctx, &args))?;            }            call("blocked sender", block_sender(ctx, &object(json!({ "address": "offers@letters.example.org" }))))?;            Ok(())        })    }    /// `cotton_secrets` and `cotton_secret_placements` patches: one of each    /// kind the vault keeps, as NAMES — see the module note — and a key placed    /// on a Mac that is nobody's (applied once, and one still to apply).    ///    /// With a vault rail each row carries a SEALED invented value, so the    /// seeded login, card and note open on a phone with Show and Copy like    /// one the person made (the walk read "Add password" on every seeded    /// secret, with nothing to show). Without one the rows are bare.    pub(super) fn write_secrets(&mut self) -> Result<()> {        use cotton_core::vault::SecretPayload;        let env = &self.env;        env.once(env.now - Duration::days(150), |ctx| {            let mut key = None;            for (kind, name, site, username, service, hint, payload) in [                ("login", "Harbour Mutual online", Some("harbourmutual.example.com"), Some("me@example.com"), None, None,                    SecretPayload::Login { password: "tide-and-tackle-42".into(), notes: None, totp: None, urls: None }),                ("login", "Allotment society forum", Some("forum.allotments.example.org"), Some("plot-22"), None, None,                    SecretPayload::Login { password: "plot22-shed-key".into(), notes: None, totp: None, urls: None }),                ("api_key", "Weather feed", None, None, Some("example-weather"), Some("9f3c"),                    SecretPayload::ApiKey { key: "wf_live_7c1e2a9f3c".into(), notes: None }),                ("api_key", "Map tiles", None, None, Some("example-maps"), Some("a01d"),                    SecretPayload::ApiKey { key: "mt_9b3d7e2a01d".into(), notes: None }),                ("card", "Everyday debit card", None, None, None, Some("4417"),                    SecretPayload::Card { number: "4556 7375 8689 4417".into(), holder: Some("A Walker".into()), expiry: Some("11/27".into()), cvv: None, notes: None }),                ("identity", "Passport", None, None, None, None,                    SecretPayload::Identity { number: "P0123456".into(), id_type: Some("passport".into()), holder: Some("A Walker".into()), issued: None, expires: None, country: None, notes: None }),                ("note", "Wi-fi at the allotment shed", None, None, None, None,                    SecretPayload::Note { body: "Network AllotmentNet, password gardengate22.".into() }),                ("document", "Tax summary password", None, None, None, None,                    SecretPayload::Document { password: "autumn-leaves".into() }),            ] {                let id = ctx.new_uuid();                let mut row = object(json!({ "kind": kind, "name": name }));                for (column, value) in [("site", site), ("username", username), ("service", service), ("hint", hint)] {                    if let Some(value) = value {                        row.insert(column.into(), Value::from(value));                    }                }                if kind == "card" {                    row.insert("expires_at".into(), Value::from(iso(env.now + Duration::days(400))));                }                if let Some(vault) = ctx.services.vault.clone() {                    let (sealed, hint) = crate::mcp::handlers::secrets::seal_payload(vault.as_ref(), &id, &payload)                        .map_err(|failure| cotton_store::StoreError::Refused(failure.to_string()))?;                    row.insert("value_enc".into(), Value::from(sealed.value_enc));                    row.insert("vmk_version".into(), Value::from(i64::from(sealed.vmk_version)));                    row.insert("hint".into(), Value::from(hint));                }                insert_row(ctx, "cotton_secrets", &id, row).map_err(refused("secret"))?;                if service == Some("example-weather") {                    key = Some(id);                }            }            ctx.commit().map_err(refused("secret"))?;            let Some(key) = key else { return Ok(()) };            for (path, format, env_name, applied) in [                ("~/.config/example-weather/token", "raw", None, true),                ("~/projects/garden/.env", "env", Some("WEATHER_TOKEN"), false),            ] {                let mut row = object(json!({ "secret_id": key, "device_id": NOBODYS_MAC, "path": path, "mode": 384, "format": format }));                if let Some(env_name) = env_name {                    row.insert("env_name".into(), Value::from(env_name));                }                if applied {                    row.insert("applied_at".into(), Value::from(iso(env.now - Duration::days(100))));                    row.insert("applied_hash".into(), Value::from(env.hex(64)));                }                let id = ctx.new_uuid();                insert_row(ctx, "cotton_secret_placements", &id, row).map_err(refused("secret placement"))?;            }            ctx.commit().map_err(refused("secret placement"))        })    }    /// `log_session {tool, externalId, machine, prompts, tasks, …}` for the    /// conversation; where a session stands (`state`, what it waits on, how    /// it ended) is the session host's to write, so those are patches — and    /// each names [`NOBODYS_MAC`], so no machine takes one up. NEVER queued:    /// a queued session is a job for the first Mac that sees it.    pub(super) fn write_sessions(&mut self) -> Result<()> {        let env = &self.env;        let Some(project) = self.projects.first() else { return Ok(()) };        // `(external id, tool, title, hours back, how it stands)`.        let sessions = [            ("synthetic-session-ended", "claude-code", "Fix the rota export", 30, "ended"),            ("synthetic-session-waiting", "claude-code", "Add the seed swap page", 2, "waiting"),            ("synthetic-session-question", "codex", "Tidy the plot map", 5, "question"),            ("synthetic-session-failed", "claude-code", "Upgrade the build", 52, "failed"),            ("synthetic-session-idle", "claude-code", "Write the autumn newsletter", 1, "idle"),        ];        env.once(env.now, |ctx| {            for (external, tool, title, back, standing) in sessions {                let started = env.now - Duration::hours(back);                let last = (started + Duration::minutes(42)).min(env.now);                ctx.now = last;                let turns = [                    ("user", format!("{title}. Start from the failing check and keep the change small.")),                    ("assistant", "I read the check and the file it points at. The export skips anyone whose plot number has a letter in it; I will fix the parser and add a case for it.".to_string()),                    ("user", "Good. Run the tests before you push.".to_string()),                    ("assistant", "All 41 pass. The change is one function and one test.".to_string()),                ];                let prompts: Vec<Value> = turns                    .iter()                    .enumerate()                    .map(|(seq, (role, text))| json!({ "seq": seq, "role": role, "text": text, "ts": iso(started + Duration::minutes(9 * seq as i64)) }))                    .collect();                let args = object(json!({                    "tool": tool, "externalId": external, "machine": "Example Mac", "title": title,                    "startedAt": iso(started), "lastActiveAt": iso(last), "turnCount": 2, "project": project,                    "repoUrl": "https://git.example.com/household/allotment-site", "branch": "main", "cwd": "~/projects/allotment-site",                    "model": "synthetic", "summary": "Found the cause, changed one function, added a test.",                    "prompts": prompts,                    "tasks": [                        { "seq": 0, "text": "Read the failing check", "state": "done" },                        { "seq": 1, "text": "Fix the parser", "state": if standing == "ended" { "done" } else { "active" } },                        { "seq": 2, "text": "Open the pull request", "state": if standing == "ended" { "done" } else { "open" } },                    ],                }));                let out = call("session", log_session(ctx, &args))?;                let Some(session) = out.get("sessionId").and_then(Value::as_str).map(str::to_string) else {                    return Err(StoreError::refused("synthetic household: session answered no sessionId"));                };                let mut marks = object(json!({ "host_owned": true, "device_id": NOBODYS_MAC, "permission_mode": "ask" }));                let mut mark = |column: &str, value: Value| marks.insert(column.to_string(), value);                match standing {                    "ended" => {                        mark("state", Value::from("ended"));                        mark("ended_at", Value::from(iso(last)));                        mark("exit_code", Value::from(0));                        mark("last_line", Value::from("Pushed, and the checks are green."));                    }                    "failed" => {                        mark("state", Value::from("failed"));                        mark("ended_at", Value::from(iso(last)));                        mark("exit_code", Value::from(1));                        mark("error", Value::from("The agent stopped: its sign-in on that Mac had expired."));                    }                    "waiting" => {                        mark("state", Value::from("waiting"));                        mark("waiting_kind", Value::from("permission"));                        mark("waiting_ref", Value::from("synthetic-permission-1"));                        mark("last_line", Value::from("May I run `npm install` in ~/projects/allotment-site?"));                    }                    "question" => {                        mark("state", Value::from("waiting"));                        mark("waiting_kind", Value::from("question"));                        mark("last_line", Value::from("Two plots share the number 14. Which one keeps it?"));                    }                    _ => {                        mark("state", Value::from("idle"));                        mark("last_line", Value::from("Draft written. Say when to send it."));                    }                }                update_row(ctx, "cotton_sessions", &session, marks).map_err(refused("session state"))?;                ctx.commit().map_err(refused("session state"))?;                // What it asked its owner, and what it reported when done.                let message = match standing {                    "question" => Some(("question", "Two plots share the number 14. Which one keeps it?", "open")),                    "ended" => Some(("report", "The rota export is fixed and pushed; one function and one test.", "done")),                    _ => None,                };                if let Some((kind, body, status)) = message {                    let mut row = object(json!({                        "to_kind": "owner", "from_kind": "session", "from_session_id": session, "kind": kind, "body": body, "status": status,                    }));                    if status == "done" {                        row.insert("done_at".into(), Value::from(iso(last)));                    }                    let id = ctx.new_uuid();                    insert_row(ctx, "cotton_session_messages", &id, row).map_err(refused("session message"))?;                    ctx.commit().map_err(refused("session message"))?;                }            }            Ok(())        })    }}