Cotton code
1182 lines · 51.8 KB · RustRaw
//! The writing itself, one function per kind, in the order the links run://! people and places first (messages, transactions and events point at them),//! projects before memories, procedures and journal pages (they file under a//! slug), accounts before transactions and statements.//!//! EVERY FUNCTION WRITES THROUGH `Ctx` — a handler where one exists, the//! writer's stamped patches (`insert_row`) where none does — and rebuilds the//! `Ctx` per chunk so the HLC and `created_at` follow the invented date rather//! than the run's. Each kind is PLANNED first (every random draw that shapes a//! row), sorted by its date, and then written in chunks of [`CHUNK`] rows, one//! transaction each.//!//! A REFUSAL IS AN ERROR. Handlers take JSON maps, so a renamed column or a//! tightened validator fails here at run time, loudly, naming the kind — the//! small run in this module's test is the guard. Where a handler's refusal is//! about the INPUT rather than the schema (a memory project's briefing budget),//! the input is varied — the entry goes to the next project — rather than the//! refusal being swallowed.//!//! COUNTS ARE EXACT OR ABSENT: a table is counted only where every row in it//! came from a write this module made and can count (so a side-effect table,//! like the claim accounts `record_transaction` mints per person, is left out).use cotton_core::messages::MessageMedia;use crate::mcp::handlers::tables::groups::create_group;use super::{names, Counts, MediaSink, Plan, SeededRandom};use crate::mcp::dispatch::{Ctx, ToolResult, ToolServices};use crate::mcp::handlers::common::{insert_row, iso_of_ms};use crate::mcp::handlers::emails::ingest::ingest_emails;use crate::mcp::handlers::money::accounts::create_money_account;use crate::mcp::handlers::projects::write::{create_project, link_to_project};use crate::mcp::handlers::records_1::events::create_event;use crate::mcp::handlers::records_1::notes::{append_journal, create_note};use crate::mcp::handlers::records_1::people::create_person;use crate::mcp::handlers::records_1::todos::{complete_todo, create_todo};use crate::mcp::handlers::records_2::memory::remember;use crate::mcp::handlers::records_2::money::record_transaction;use crate::mcp::protocol::ToolFailure;use crate::messages::sink::queue_changes;use chrono::{DateTime, Datelike, Duration, TimeZone, Utc};use cotton_core::constants::{MessageChannel, MessageDirection, MessageOrigin};use cotton_core::messages::apply_message_write::{    apply_message_write, ApplyMessageWriteError, MessageWriteInput, MessageWriteThread,};use cotton_store::file_identity::FileIdentity;use cotton_store::protocol::derived_id;use cotton_store::{Driver, Result, StoreError};use serde_json::{json, Map, Value};use std::collections::{BTreeSet, HashMap};use std::sync::Arc;mod everyday;mod ledger;mod pictures;mod rest;mod talk;/// The job every synthetic write is made as.pub const SYNTHETIC_JOB: &str = "synthetic";/// The byline synthetic writes carry (`job:<name>`).pub const SYNTHETIC_LABEL: &str = "job:synthetic";/// Rows per transaction (and per rebuilt `Ctx`).const CHUNK: usize = 500;/// The owner's own address on every email he sends or receives.const OWNER_EMAIL: &str = "me@example.com";/// What does not change while a household is written: the file, who it is/// for, the seed, the plan. Split from [`Household`]'s growing state so a/// `Ctx` (which borrows this) and the counts (which change) can live side by/// side.struct Env<'a> {    db: &'a Driver,    file: &'a FileIdentity,    workspace_id: &'a str,    owner_id: &'a str,    plan: &'a Plan,    random: Arc<SeededRandom>,    services: ToolServices,    statement_pages: Arc<super::statement_pages::RecordedPages>,    now: DateTime<Utc>,    /// Where generated pictures are put, when the caller has somewhere.    media: Option<MediaSink<'a>>,}impl Env<'_> {    /// A context dated `at`. Rebuilt per chunk rather than per row: the    /// writer's HLC clock is set at construction, and a chunk of rows sharing    /// one is right.    ///    /// The WRITER's clock is never later than `now`, though the rows may be    /// dated after it (this morning's edition in a house whose morning has    /// not come yet): a receipt stamped ahead of the seed's `now` is ahead of    /// the wall clock, and every stamp after it in the file inherits it, so a    /// joined phone's edits of those rows folded as stale or split a row's    /// columns (`seed_now`).    fn ctx_at(&self, at: DateTime<Utc>) -> Ctx<'_> {        let mut ctx = self.ctx_stamped(at.min(self.now));        ctx.now = at;        ctx    }    fn ctx_stamped(&self, at: DateTime<Utc>) -> Ctx<'_> {        fn no_audit(_: &str, _: &str) {}        Ctx::for_worker(            self.db,            self.file,            self.owner_id,            crate::mcp::writer::job(SYNTHETIC_JOB),            SYNTHETIC_LABEL,            at,            self.random.clone(),            &self.services,            &no_audit,        )    }    fn rng(&self) -> &SeededRandom {        &self.random    }    /// One transaction and one `Ctx` dated `at` — for the handful of rows a    /// shape is made of, where [`chunked`]'s list of like items does not fit.    fn once<T>(&self, at: DateTime<Utc>, f: impl FnOnce(&mut Ctx<'_>) -> Result<T>) -> Result<T> {        self.db.transaction(|_| {            let mut ctx = self.ctx_at(at);            f(&mut ctx)        })    }    /// `days` from now (negative: ago) at `hour:minute` UTC.    fn day_at(&self, days: i64, hour: u32, minute: u32) -> DateTime<Utc> {        let day = self.now.date_naive() + Duration::days(days);        Utc.from_utc_datetime(&day.and_hms_opt(hour, minute, 0).expect("a time of day"))    }    /// An instant between `years` ago and now, deterministic.    fn moment(&self) -> DateTime<Utc> {        let span_days = i64::from(self.plan.years) * 365;        let days = self.rng().between(0, span_days);        let seconds = self.rng().between(6 * 3600, 23 * 3600);        self.now - Duration::days(days) - Duration::seconds(seconds)    }    /// Mostly the past, sometimes the coming weeks — what a calendar or a todo    /// list holds.    fn moment_around(&self) -> DateTime<Utc> {        if self.rng().chance(15) {            let days = self.rng().between(0, 60);            let minutes = self.rng().between(8 * 60, 20 * 60);            let day = self.now.date_naive() + Duration::days(days);            Utc.from_utc_datetime(&day.and_hms_opt(0, 0, 0).expect("midnight"))                + Duration::minutes(minutes)        } else {            self.moment()        }    }    /// `len` lowercase hex characters off the seed — an invented sha.    fn hex(&self, len: usize) -> String {        let mut out = String::with_capacity(len + 16);        while out.len() < len {            out.push_str(&format!("{:016x}", self.rng().next_u64()));        }        out.truncate(len);        out    }    fn sentences(&self, lo: i64, hi: i64) -> String {        let n = self.rng().between(lo, hi);        (0..n)            .map(|_| *self.rng().pick(names::SENTENCES))            .collect::<Vec<_>>()            .join(" ")    }}/// The seed's one long note: Markdown of about 1,500 words in six sections,/// with a list and a quote, its paragraphs cycled from the sentence list.fn long_note() -> String {    let mut next = names::SENTENCES.iter().cycle();    let mut paragraph = |sentences: usize| (0..sentences).filter_map(|_| next.next().copied()).collect::<Vec<_>>().join(" ");    let mut out = String::from("# Moving house: the whole plan\n\n");    for (n, heading) in ["Why now", "What we are looking for", "The money", "Who does what", "The week of the move", "After we land"].iter().enumerate() {        out.push_str(&format!("## {heading}\n\n"));        for _ in 0..3 {            out.push_str(&paragraph(7));            out.push_str("\n\n");        }        if n == 1 {            out.push_str("- Two bedrooms and a room to work in\n- Ten minutes' walk to a station\n- Light in the kitchen in the morning\n- A place for the bikes\n\n");        }        if n == 3 {            out.push_str("> Pack the kettle last and unpack it first.\n\n");        }    }    out.trim_end().to_string()}/// `2026-10-01T09:00:00.000Z` — the spelling `now_iso` writes.fn iso(at: DateTime<Utc>) -> String {    iso_of_ms(at.timestamp_millis())}fn day(at: DateTime<Utc>) -> String {    at.format("%Y-%m-%d").to_string()}fn object(value: Value) -> Map<String, Value> {    match value {        Value::Object(map) => map,        _ => Map::new(),    }}/// A handler's refusal as the store's error, naming the kind it stopped.fn refused(kind: &'static str) -> impl Fn(ToolFailure) -> StoreError {    move |failure| StoreError::refused(format!("synthetic household: {kind}: {}", failure.message()))}fn call(kind: &'static str, result: ToolResult) -> Result<Map<String, Value>> {    result.map(object).map_err(refused(kind))}fn id_of(kind: &'static str, out: &Map<String, Value>) -> Result<String> {    out.get("id")        .and_then(Value::as_str)        .map(str::to_string)        .ok_or_else(|| StoreError::refused(format!("synthetic household: {kind} answered no id")))}/// Write `items` in chunks of [`CHUNK`], one transaction and one `Ctx` each,/// with `ctx.now` moved to each item's own instant.fn chunked<T>(    env: &Env<'_>,    counts: &mut Counts,    items: &[T],    at: impl Fn(&T) -> DateTime<Utc>,    mut each: impl FnMut(&mut Ctx<'_>, &T, &mut Counts) -> Result<()>,) -> Result<()> {    for chunk in items.chunks(CHUNK) {        env.db.transaction(|_| {            let mut ctx = env.ctx_at(at(&chunk[0]));            for item in chunk {                ctx.now = at(item);                each(&mut ctx, item, counts)?;            }            Ok(())        })?;    }    Ok(())}/// One person as the later kinds need them.struct Person {    id: String,    name: String,    first: String,    phone_digits: String,    email: String,}pub struct Household<'a> {    env: Env<'a>,    counts: Counts,    // What the later kinds link to, in creation order so a pick is deterministic.    people: Vec<Person>,    /// Project slugs.    projects: Vec<String>,    /// `(id, kind)` of the real accounts.    /// `(id, kind, currency)`, in [`names::ACCOUNTS`] order.    accounts: Vec<(String, &'static str, &'static str)>,    /// The newest pictured photos' record ids, for the rows that show a picture.    photos: Vec<String>,    /// A few transaction ids, for the evidence a statement does not give.    transactions: Vec<String>,    /// The photos of each of `pictures::MOMENTS`, for the albums.    moments: Vec<Vec<String>>,    /// The statements' documents, oldest first.    statement_documents: Vec<String>,}impl<'a> Household<'a> {    /// The vault the secrets are sealed with, when the seeder has one.    pub(crate) fn sealing(mut self, vault: Option<Arc<dyn crate::rails::VaultRail>>) -> Self {        self.env.services.vault = vault;        self    }    pub fn new(        db: &'a Driver,        file: &'a FileIdentity,        owner_id: &'a str,        plan: &'a Plan,        seed: u64,        now: DateTime<Utc>,        media: Option<MediaSink<'a>>,    ) -> Self {        // Only this invented household gets recorded page fixtures. Ordinary        // headless/server ToolServices remain without a renderer and refuse.        let statement_pages = Arc::new(super::statement_pages::RecordedPages::default());        let mut services = ToolServices::none();        services.statement_visual = Some(statement_pages.clone());        Household {            env: Env {                db,                file,                workspace_id: file.id().as_str(),                owner_id,                plan,                random: Arc::new(SeededRandom::new(seed)),                services,                statement_pages,                now,                media,            },            counts: Counts::default(),            people: Vec::new(),            projects: Vec::new(),            accounts: Vec::new(),            photos: Vec::new(),            transactions: Vec::new(),            statement_documents: Vec::new(),            moments: Vec::new(),        }    }    pub fn write(mut self) -> Result<Counts> {        self.write_kit()?;        self.write_settings()?;        self.write_people()?;        if self.drawn("project")? { self.write_projects()?; }        if self.drawn("memory")? { self.write_memories()?; }        self.write_procedures()?;        self.write_todos()?;        self.write_notes()?;        // A shared database holds none of the personal-only tables (mail,        // messages, calls, money, moods, journal, sessions): the fold refuses        // them there, so the plan leaves those steps out.        let personal = !self.env.plan.shared;        if personal {            if self.drawn("assistant")? { self.write_assistants()?; }            if self.drawn("journal")? { self.write_journal()?; }        }        self.write_events()?;        if personal {            self.write_messages()?;            self.write_emails()?;            // Money is an engine over its own typed tables (72nd amendment:            // an engine never reads a definition), so its rows are written            // whether or not a tool draws them.            self.write_money()?;            self.write_transactions()?;            self.write_statements()?;            self.write_evidence()?;        }        self.write_photos()?;        // THE SHAPES — a fixed handful of each pattern real data has and the        // scaled kinds above do not make (a repeating todo, an invitation, an        // archived note …). Not scaled by the plan: a walk needs one of each        // to look at, whatever the size.        self.write_todo_shapes()?;        self.write_event_shapes()?;        self.write_note_shapes()?;        if personal {            self.write_message_shapes()?;            if self.drawn("call")? { self.write_calls()?; }            self.write_stories()?;        }        self.write_people_shapes()?;        self.write_media_shapes()?;        if self.drawn("document")? { self.write_documents()?; }        if personal {            self.write_email_shapes()?;        }        self.write_secrets()?;        if personal {            if self.drawn("session")? { self.write_sessions()?; }        }        self.recount()?;        self.counts.statement_pages = self.env.statement_pages.figures();        Ok(self.counts)    }    /// Every table a shape wrote into, counted FROM THE FILE: a shape's    /// handler writes rows of its own (a repeating todo's occurrences, a    /// draft's scene copies), so the only exact count is the file's.    fn recount(&mut self) -> Result<()> {        for table in everyday::TABLES.iter().chain(ledger::TABLES).chain(talk::TABLES).chain(pictures::TABLES).chain(rest::TABLES) {            let n = self                .env                .db                .get(&format!("SELECT count(*) AS n FROM {table}"), &[])?                .and_then(|row| row.int("n"))                .unwrap_or_default();            self.counts.set(table, n as usize);        }        Ok(())    }    /// The start of the household's history — what the one-off rows    /// (settings, projects, accounts) are dated.    fn founded(&self) -> DateTime<Utc> {        self.env.now - Duration::days(i64::from(self.env.plan.years) * 365 + 7)    }    /// `cotton_news_settings {timezone}` so dated todos, all-day events and    /// `occurredOn` defaults have a zone to read. Via `insert_row`.    /// Does a tool in this file draw `table`? A household writes only into    /// the tables its tools draw: a table no tool draws is no tool's records.    fn drawn(&self, table: &str) -> Result<bool> {        let ctx = self.env.ctx_at(self.founded());        Ok(crate::mcp::handlers::tables::definition(&ctx, table).is_ok())    }    /// The household's tools: the kit tools, imported as `import_tool`    /// imports them (`crate::kit::import_kit_tools`) — a file is made with no    /// tool, and a household is given its tools on purpose.    fn write_kit(&mut self) -> Result<()> {        let at = self.founded();        let env = &self.env;        env.db.transaction(|_| {            let mut ctx = env.ctx_at(at);            crate::kit::import_kit_tools(&mut ctx).map_err(refused("kit"))?;            ctx.commit().map_err(refused("kit"))        })    }    fn write_settings(&mut self) -> Result<()> {        let zone = self.env.rng().pick(names::CITIES).3;        let at = self.founded();        let env = &self.env;        env.db.transaction(|_| {            let mut ctx = env.ctx_at(at);            let mut patch = Map::new();            patch.insert("workspace_id".into(), Value::from(env.workspace_id));            patch.insert("timezone".into(), Value::from(zone));            // NO SCHEDULE AND NO REFRESH ON OPENING: with either, a server            // holding a model key would queue an edition for the invented            // topics and dial out to harvest it. The editions here are            // written ready (`write_news`).            patch.insert("edition_times".into(), json!([]));            patch.insert("stale_refresh".into(), Value::Bool(false));            insert_row(&mut ctx, "cotton_news_settings", env.workspace_id, patch).map_err(refused("settings"))?;            ctx.commit().map_err(refused("settings"))        })?;        self.counts.add("cotton_news_settings", 1);        Ok(())    }    /// The UK numbers Ofcom keeps for drama, as E.164 digits before their last    /// three: each is a thousand numbers that parse as real and ring nobody.    const DRAMA_RANGES: [&'static str; 15] = [        "442079460", "441134960", "441144960", "441154960", "441164960", "441174960", "441184960", "441214960",        "441314960", "441414960", "441514960", "441614960", "441914980", "447700900", "441632960",    ];    /// `create_person {fullName, phones, emails, org, city, timezone, birthday, allowDuplicateName: true}`.    fn write_people(&mut self) -> Result<()> {        struct Plan1 {            at: DateTime<Utc>,            name: String,            first: String,            phone_digits: String,            email: String,            args: Map<String, Value>,        }        let env = &self.env;        let rng = env.rng();        let mut items: Vec<Plan1> = (0..env.plan.people)            .map(|n| {                let first = *rng.pick(names::FIRST_NAMES);                let last = *rng.pick(names::SURNAMES);                let name = format!("{first} {last}");                // Ofcom's drama ranges: real-shaped UK numbers that are nobody's.                let phone_digits = format!("{}{:03}", Self::DRAMA_RANGES[n / 1000 % Self::DRAMA_RANGES.len()], n % 1000);                let email = format!(                    "{}.{}{}@example.com",                    first.to_lowercase(),                    last.to_lowercase(),                    n                );                let (city, _, _, zone) = *rng.pick(names::CITIES);                let mut args = object(json!({                    "fullName": name,                    "allowDuplicateName": true,                    "city": city,                    "timezone": zone,                }));                if rng.chance(85) {                    args.insert("phones".into(), json!([format!("+{phone_digits}")]));                }                if rng.chance(70) {                    args.insert("emails".into(), json!([email]));                }                if rng.chance(40) {                    args.insert("org".into(), Value::from(*rng.pick(names::ORGS)));                }                if rng.chance(50) {                    let month = rng.between(1, 12);                    let day = rng.between(1, 28);                    let mut birthday = json!({ "month": month, "day": day });                    if rng.chance(60) {                        birthday["year"] = Value::from(rng.between(1950, 2010));                    }                    args.insert("birthday".into(), birthday);                }                Plan1 { at: env.moment(), name, first: first.to_string(), phone_digits, email, args }            })            .collect();        items.sort_by_key(|item| item.at);        let people = &mut self.people;        chunked(env, &mut self.counts, &items, |item| item.at, |ctx, item, counts| {            let out = call("person", create_person(ctx, &item.args))?;            people.push(Person {                id: id_of("person", &out)?,                name: item.name.clone(),                first: item.first.clone(),                phone_digits: item.phone_digits.clone(),                email: item.email.clone(),            });            counts.add("cotton_people", 1);            Ok(())        })    }    /// `create_project {slug, name, description}`; id = `derived_id::memory_project_id(ws, slug)`.    fn write_projects(&mut self) -> Result<()> {        let at = self.founded();        let wanted: Vec<_> = names::PROJECTS.iter().take(self.env.plan.projects).collect();        let projects = &mut self.projects;        chunked(&self.env, &mut self.counts, &wanted, |_| at, |ctx, (slug, name, description), counts| {            call(                "project",                create_project(ctx, &object(json!({ "slug": slug, "name": name, "description": description }))),            )?;            projects.push(slug.to_string());            counts.add("cotton_memory_projects", 1);            Ok(())        })    }    /// `remember {title, project, decision: {action: "add"}}` — forced, so    /// similarity never stops a write. A project whose briefing is full takes    /// no more: the entry goes to the next project, and when every project is    /// full the household simply remembers fewer things than planned.    fn write_memories(&mut self) -> Result<()> {        let env = &self.env;        let rng = env.rng();        let mut items: Vec<(DateTime<Utc>, String, usize)> = (0..env.plan.memories)            .map(|n| {                let fact = *rng.pick(names::MEMORIES);                let tail = rng                    .pick(names::MEMORY_TAILS)                    .replace("{name}", rng.pick(names::FIRST_NAMES));                (env.moment(), format!("{fact} {tail}"), n % self.projects.len().max(1))            })            .collect();        items.sort_by_key(|item| item.0);        let projects = &self.projects;        let mut full: BTreeSet<usize> = BTreeSet::new();        chunked(env, &mut self.counts, &items, |item| item.0, |ctx, (_, title, home), counts| {            for step in 0..projects.len() {                let index = (home + step) % projects.len();                if full.contains(&index) {                    continue;                }                let args = object(json!({                    "title": title,                    "project": projects[index],                    "decision": { "action": "add" },                }));                match remember(ctx, &args) {                    Ok(_) => {                        counts.add("cotton_memories", 1);                        return Ok(());                    }                    Err(failure) if failure.message().contains("-token limit") => {                        full.insert(index);                    }                    Err(failure) => return Err(refused("memory")(failure)),                }            }            Ok(())        })    }    /// `create_note {title, body: "trigger: …\n…"}` then `link_to_project {project, records: [{kind: "note", id}]}`.    fn write_procedures(&mut self) -> Result<()> {        let env = &self.env;        let at = self.founded() + Duration::days(30);        let wanted: Vec<_> = names::PROCEDURES.iter().take(env.plan.procedures).enumerate().collect();        let projects = &self.projects;        chunked(env, &mut self.counts, &wanted, |_| at, |ctx, (n, (trigger, steps)), counts| {            let when = trigger.trim_start_matches("trigger: ");            let title = format!("When {when}");            let out = call(                "procedure",                create_note(ctx, &object(json!({ "title": title, "body": format!("{trigger}\n{steps}") }))),            )?;            counts.add("cotton_notes", 1);            if !projects.is_empty() {                let slug = &projects[n % projects.len()];                call(                    "procedure link",                    link_to_project(                        ctx,                        &object(json!({ "project": slug, "records": [{ "kind": "note", "id": id_of("procedure", &out)? }] })),                    ),                )?;            }            Ok(())        })    }    /// `create_todo {title, notes?, dueAt?}`; a third completed via    /// `complete_todo {id}`; about a quarter gathered into a few todo groups    /// (`create_group {table: "todo", name, records}`), which sort todos now    /// that they carry no label.    fn write_todos(&mut self) -> Result<()> {        struct Todo {            at: DateTime<Utc>,            args: Map<String, Value>,            group: Option<&'static str>,            done_at: Option<DateTime<Utc>>,        }        let env = &self.env;        let rng = env.rng();        let mut items: Vec<Todo> = (0..env.plan.todos)            .map(|_| {                let at = env.moment();                let mut args = object(json!({                    "title": format!("{} {}", rng.pick(names::TODO_VERBS), rng.pick(names::TODO_OBJECTS)),                }));                if rng.chance(30) {                    args.insert("notes".into(), Value::from(*rng.pick(names::SENTENCES)));                }                // The same draws the label once took, so every later kind                // seeds as it did.                let group = rng.chance(25).then(|| rng.pick(names::PROJECTS).1);                if rng.chance(60) {                    let due = at + Duration::hours(rng.between(4, 24 * 30));                    args.insert("dueAt".into(), Value::from(iso(due)));                }                let done_at = rng.chance(33).then(|| {                    (at + Duration::hours(rng.between(1, 24 * 20))).min(env.now)                });                Todo { at, args, group, done_at }            })            .collect();        // Whatever the plan drew, the list's Late and Done groups each have        // work from the last few days on any seed, so both can be walked.        for (title, made, due, done) in [            ("Return the library books", 6, Some(1), None),            ("Book the boiler service", 5, Some(2), None),            ("Reply to the landlord", 8, Some(4), None),            ("Water the plants", 2, None, Some(0)),            ("Pay the window cleaner", 3, Some(1), Some(1)),            ("Post the birthday card", 4, None, Some(2)),        ] {            let at = env.now - Duration::days(made);            let mut args = object(json!({ "title": title }));            if let Some(due) = due {                args.insert("dueAt".into(), Value::from(iso(env.now - Duration::days(due) - Duration::hours(2))));            }            let done_at = done.map(|back: i64| env.now - Duration::days(back) - Duration::hours(1));            // A walk finds a household's own groups beside the projects' ones.            let group = match title {                "Book the boiler service" | "Pay the window cleaner" | "Reply to the landlord" => Some("House"),                "Water the plants" => Some("Garden"),                _ => None,            };            items.push(Todo { at, args, group, done_at });        }        items.sort_by_key(|item| item.at);        // Each group's todos, in the order the groups first gather one.        let mut groups: Vec<(&'static str, Vec<String>)> = Vec::new();        chunked(env, &mut self.counts, &items, |item| item.at, |ctx, item, counts| {            let out = call("todo", create_todo(ctx, &item.args))?;            counts.add("cotton_todos", 1);            if let Some(name) = item.group {                let id = id_of("todo", &out)?;                match groups.iter_mut().find(|(held, _)| *held == name) {                    Some((_, ids)) => ids.push(id),                    None => groups.push((name, vec![id])),                }            }            if let Some(done_at) = item.done_at {                let created = ctx.now;                ctx.now = done_at.max(created);                call("todo completion", complete_todo(ctx, &object(json!({ "id": id_of("todo", &out)? }))))?;                ctx.now = created;            }            Ok(())        })?;        if groups.is_empty() {            return Ok(());        }        env.db.transaction(|_| {            let mut ctx = env.ctx_at(env.now);            for (name, records) in &groups {                call(                    "todo group",                    create_group(&mut ctx, &object(json!({ "table": "todo", "name": name, "records": records }))),                )?;            }            Ok(())        })    }    /// `create_note {title, body}`.    fn write_notes(&mut self) -> Result<()> {        let env = &self.env;        let rng = env.rng();        let mut items: Vec<(DateTime<Utc>, Map<String, Value>)> = (0..env.plan.notes)            .map(|_| {                let mut args = object(json!({ "body": env.sentences(1, 6) }));                if rng.chance(85) {                    args.insert("title".into(), Value::from(*rng.pick(names::NOTE_TITLES)));                }                (env.moment(), args)            })            .collect();        // One long note (about 1,500 words: headings, a list, a quote) beside        // the short ones, written yesterday so it is near the top. Its words        // cycle the sentence list, drawing nothing from the seed's random        // stream, so every other record stays as it was.        items.push((env.now - Duration::days(1), object(json!({ "title": "Moving house: the whole plan", "body": long_note() }))));        items.sort_by_key(|item| item.0);        chunked(env, &mut self.counts, &items, |item| item.0, |ctx, (_, args), counts| {            call("note", create_note(ctx, args))?;            counts.add("cotton_notes", 1);            Ok(())        })    }    /// `append_journal {text, date: YYYY-MM-DD}` one page per day, some under    /// a project slug, and some days written twice (the second call appends).    fn write_journal(&mut self) -> Result<()> {        let env = &self.env;        let rng = env.rng();        let span = (i64::from(env.plan.years) * 365).max(1);        let days = env.plan.journal_days as i64;        let mut items: Vec<(DateTime<Utc>, Map<String, Value>)> = Vec::new();        for n in 0..days {            // Evenly back from yesterday, so every page is a different day.            let back = 1 + n * span / days.max(1);            let at = env.now - Duration::days(back) + Duration::hours(rng.between(-8, 10));            let mut args = object(json!({ "text": env.sentences(1, 4), "date": day(env.now - Duration::days(back)) }));            if !self.projects.is_empty() && rng.chance(25) {                args.insert("project".into(), Value::from(rng.pick(&self.projects).clone()));            }            if rng.chance(20) {                let mut again = args.clone();                again.insert("text".into(), Value::from(env.sentences(1, 2)));                items.push((at + Duration::hours(3), again));            }            items.push((at, args));        }        items.sort_by_key(|item| item.0);        chunked(env, &mut self.counts, &items, |item| item.0, |ctx, (_, args), counts| {            let out = call("journal", append_journal(ctx, args))?;            if out.get("created") == Some(&Value::Bool(true)) {                counts.add("cotton_notes", 1);            }            Ok(())        })    }    /// `create_event {title, startsAt, endsAt, location?, allDay?}` on the default calendar.    fn write_events(&mut self) -> Result<()> {        let env = &self.env;        let rng = env.rng();        let mut items: Vec<(DateTime<Utc>, Map<String, Value>)> = (0..env.plan.events)            .map(|_| {                let starts = env.moment_around();                let kind = *rng.pick(names::EVENT_KINDS);                let title = if self.people.is_empty() || rng.chance(30) {                    kind.to_string()                } else {                    format!("{kind} with {}", rng.pick(&self.people).first)                };                let mut args = object(json!({ "title": title }));                if rng.chance(8) {                    args.insert("allDay".into(), Value::Bool(true));                    args.insert("startsAt".into(), Value::from(iso(starts)));                } else {                    let ends = starts + Duration::minutes(rng.between(1, 8) * 30);                    args.insert("startsAt".into(), Value::from(iso(starts)));                    args.insert("endsAt".into(), Value::from(iso(ends)));                }                if rng.chance(20) {                    args.insert("notes".into(), Value::from(*rng.pick(names::SENTENCES)));                }                // Written a week or two before it happens, never after now.                let written = (starts - Duration::days(rng.between(1, 14))).min(env.now);                (written, args)            })            .collect();        items.sort_by_key(|item| item.0);        chunked(env, &mut self.counts, &items, |item| item.0, |ctx, (_, args), counts| {            call("event", create_event(ctx, args))?;            counts.add("cotton_events", 1);            Ok(())        })    }    /// Contacts and dm threads as patches (`msg_contact_id`, `dm_thread_id`),    /// messages through `apply_message_write` + `queue_changes`.    fn write_messages(&mut self) -> Result<()> {        let env = &self.env;        let rng = env.rng();        let threads = env.plan.message_threads.min(self.people.len());        if threads == 0 {            return Ok(());        }        // The contacts and threads, dated at the household's start.        let mut thread_ids: Vec<String> = Vec::with_capacity(threads);        let started = self.founded();        let people = &self.people[..threads];        chunked(env, &mut self.counts, people, |_| started, |ctx, person, counts| {            let contact_id = derived_id::msg_contact_id(env.file.namespace(), &person.phone_digits);            let mut contact = Map::new();            contact.insert("phone_e164".into(), Value::from(person.phone_digits.clone()));            contact.insert("display_name".into(), Value::from(person.name.clone()));            contact.insert("person_id".into(), Value::from(person.id.clone()));            insert_row(ctx, "cotton_msg_contacts", &contact_id, contact).map_err(refused("message contact"))?;            let thread_id = derived_id::dm_thread_id(env.file.namespace(), &contact_id);            let mut thread = Map::new();            thread.insert("kind".into(), Value::from("dm"));            thread.insert("contact_id".into(), Value::from(contact_id));            insert_row(ctx, "cotton_msg_threads", &thread_id, thread).map_err(refused("message thread"))?;            ctx.commit().map_err(refused("message thread"))?;            thread_ids.push(thread_id);            counts.add("cotton_msg_contacts", 1);            counts.add("cotton_msg_threads", 1);            Ok(())        })?;        // The messages: a few threads carry most of the talk, as they do.        let longest = env.plan.longest_thread.min(env.plan.messages);        let mut items: Vec<(DateTime<Utc>, usize, MessageDirection, &'static str)> = (0..env.plan.messages)            .map(|n| {                let a = rng.below(threads);                let b = rng.below(threads);                let thread = if n < longest { 0 } else { a.min(b) };                let direction = if rng.chance(50) { MessageDirection::In } else { MessageDirection::Out };                (env.moment(), thread, direction, *rng.pick(names::MESSAGE_LINES))            })            .collect();        items.sort_by_key(|item| item.0);        let mut last_at: HashMap<usize, String> = HashMap::new();        chunked(env, &mut self.counts, &items, |item| item.0, |ctx, (at, thread, direction, body), counts| {            let message_id = ctx.new_uuid();            let sent_at = iso(*at);            let thread_id = &thread_ids[*thread];            let previous = last_at.get(thread).cloned();            let input = MessageWriteInput {                body: Some(*body),                ..MessageWriteInput::new(                    MessageWriteThread {                        id: thread_id,                        workspace_id: env.workspace_id,                        last_message_at: previous.as_deref(),                    },                    &message_id,                    *direction,                    &sent_at,                    &sent_at,                )            };            let writer = ctx.writer().map_err(refused("message"))?;            apply_message_write(                |changes| queue_changes(writer, changes),                &input,            )            .map_err(|error| match error {                ApplyMessageWriteError::Refused(refusal) => {                    StoreError::refused(format!("synthetic household: message: {refusal}"))                }                ApplyMessageWriteError::Sink(refusal) => {                    StoreError::refused(format!("synthetic household: message: {refusal}"))                }            })?;            ctx.commit().map_err(refused("message"))?;            last_at.insert(*thread, sent_at);            counts.add("cotton_msg_messages", 1);            Ok(())        })?;        let at = items.last().map_or(started, |item| item.0) + Duration::minutes(1);        self.write_chat_shapes(&thread_ids[0], last_at.get(&0).cloned(), at)    }    /// The shapes an imported archive holds beside a dm's plain lines: a    /// group with seats, a message that is only a picture, the importer's    /// markers, a deleted line, and a chat with no name and no messages.    fn write_chat_shapes(&mut self, first_dm: &str, first_dm_last: Option<String>, at: DateTime<Utc>) -> Result<()> {        let env = &self.env;        let people = &self.people[..self.people.len().min(3)];        chunked(env, &mut self.counts, &[()], |_| at, |ctx, _, counts| {            let namespace = env.file.namespace();            // A number nobody named, and its chat with nothing in it.            let bare = "15550199";            let contact_id = derived_id::msg_contact_id(namespace, bare);            let mut contact = Map::new();            contact.insert("phone_e164".into(), Value::from(bare));            insert_row(ctx, "cotton_msg_contacts", &contact_id, contact).map_err(refused("message contact"))?;            let mut thread = Map::new();            thread.insert("kind".into(), Value::from("dm"));            thread.insert("contact_id".into(), Value::from(contact_id.clone()));            let empty_id = derived_id::dm_thread_id(namespace, &contact_id);            insert_row(ctx, "cotton_msg_threads", &empty_id, thread).map_err(refused("message thread"))?;            // A group, its seats the first people's contacts.            let group_id = derived_id::group_thread_id(namespace, "synthetic-weekend-plans");            let mut group = Map::new();            group.insert("kind".into(), Value::from("group"));            group.insert("title".into(), Value::from("Weekend plans"));            group.insert("external_key".into(), Value::from("synthetic-weekend-plans"));            insert_row(ctx, "cotton_msg_threads", &group_id, group).map_err(refused("message thread"))?;            let mut seats: Vec<String> = Vec::new();            for person in people {                let seat_id = ctx.new_uuid();                let mut seat = Map::new();                seat.insert("thread_id".into(), Value::from(group_id.clone()));                seat.insert(                    "contact_id".into(),                    Value::from(derived_id::msg_contact_id(namespace, &person.phone_digits)),                );                seat.insert("display_name".into(), Value::from(person.first.clone()));                insert_row(ctx, "cotton_msg_thread_participants", &seat_id, seat).map_err(refused("message seat"))?;                seats.push(seat_id);            }            ctx.commit().map_err(refused("message thread"))?;            counts.add("cotton_msg_contacts", 1);            counts.add("cotton_msg_threads", 2);            counts.add("cotton_msg_thread_participants", seats.len());            let card = format!("[attachment: {}.vcf]", people.first().map_or("Contact", |person| person.first.as_str()));            // (thread, seat, body, a picture, deleted)            let lines: Vec<(&str, Option<usize>, Option<&str>, bool, bool)> = vec![                (&group_id, Some(0), Some("who is driving on saturday?"), false, false),                (&group_id, Some(1), None, true, false),                (&group_id, None, Some("I can take four"), false, false),                (&group_id, Some(2), Some("[unsupported message]"), false, false),                (&group_id, Some(1), Some("wrong chat, sorry"), false, true),                (&group_id, Some(0), Some(card.as_str()), false, false),                (first_dm, None, None, true, false),            ];            let mut last: HashMap<&str, String> = HashMap::new();            if let Some(before) = &first_dm_last {                last.insert(first_dm, before.clone());            }            for (index, (thread_id, seat, body, picture, deleted)) in lines.iter().enumerate() {                let message_id = ctx.new_uuid();                let sent_at = iso(at + Duration::seconds(index as i64));                let media = if *picture {                    vec![MessageMedia {                        key: format!("{}/messages/{thread_id}/{message_id}.jpg", env.workspace_id),                        content_type: "image/jpeg".into(),                        ..MessageMedia::default()                    }]                } else {                    Vec::new()                };                let outbound = *thread_id == group_id.as_str() && seat.is_none();                let previous = last.get(thread_id).cloned();                let input = MessageWriteInput {                    body: *body,                    media: &media,                    channel: Some(MessageChannel::Whatsapp),                    origin: Some(MessageOrigin::Imported),                    sender_participant_id: seat.and_then(|seat| seats.get(seat)).map(String::as_str),                    deleted_at: deleted.then_some(Some(sent_at.as_str())),                    ..MessageWriteInput::new(                        MessageWriteThread {                            id: thread_id,                            workspace_id: env.workspace_id,                            last_message_at: previous.as_deref(),                        },                        &message_id,                        if outbound { MessageDirection::Out } else { MessageDirection::In },                        &sent_at,                        &sent_at,                    )                };                let writer = ctx.writer().map_err(refused("message"))?;                apply_message_write(|changes| queue_changes(writer, changes), &input).map_err(|error| match error {                    ApplyMessageWriteError::Refused(refusal) => {                        StoreError::refused(format!("synthetic household: message: {refusal}"))                    }                    ApplyMessageWriteError::Sink(refusal) => {                        StoreError::refused(format!("synthetic household: message: {refusal}"))                    }                })?;                ctx.commit().map_err(refused("message"))?;                last.insert(thread_id, sent_at);                counts.add("cotton_msg_messages", 1);            }            Ok(())        })    }    /// `ingest_emails {emails: [{threadKey, subject, sentAt, body, from: {email, name}, to: [...]}]}` in batches of 100.    fn write_emails(&mut self) -> Result<()> {        const BATCH: usize = 100;        let env = &self.env;        let rng = env.rng();        let mut emails: Vec<(DateTime<Utc>, Value)> = Vec::with_capacity(env.plan.emails);        let mut thread_keys: BTreeSet<String> = BTreeSet::new();        let mut thread = 0usize;        while emails.len() < env.plan.emails {            thread += 1;            let key = format!("synthetic-thread-{thread}");            let subject = *rng.pick(names::EMAIL_SUBJECTS);            let correspondent = if self.people.is_empty() {                (format!("{}@example.org", rng.pick(names::ORGS).to_lowercase().replace([' ', '&'], "")), None)            } else {                let person = rng.pick(&self.people);                (person.email.clone(), Some(person.name.clone()))            };            let start = env.moment();            let replies = rng.between(1, 5) as usize;            for n in 0..replies.min(env.plan.emails - emails.len()) {                let sent = (start + Duration::hours(rng.between(1, 48) * n as i64)).min(env.now);                let incoming = n % 2 == 0;                let mut them = json!({ "email": correspondent.0 });                if let Some(name) = &correspondent.1 {                    them["name"] = Value::from(name.clone());                }                let me = json!({ "email": OWNER_EMAIL, "name": "Me" });                let (from, to) = if incoming { (them, me) } else { (me, them) };                let subject = if n == 0 { subject.to_string() } else { format!("Re: {subject}") };                emails.push((                    sent,                    json!({                        "threadKey": key,                        "subject": subject,                        "sentAt": iso(sent),                        "body": env.sentences(1, 5),                        "from": from,                        "to": [to],                        "messageId": format!("<synthetic-{thread}-{n}@example.com>"),                    }),                ));            }            thread_keys.insert(key);        }        emails.sort_by_key(|item| item.0);        let batches: Vec<(DateTime<Utc>, Map<String, Value>)> = emails            .chunks(BATCH)            .map(|batch| {                let at = batch.last().map_or(env.now, |item| item.0).min(env.now);                let list: Vec<Value> = batch.iter().map(|item| item.1.clone()).collect();                (at, object(json!({ "emails": list })))            })            .collect();        chunked(env, &mut self.counts, &batches, |item| item.0, |ctx, (_, args), counts| {            let out = call("email", ingest_emails(ctx, args))?;            let added = out.get("added").and_then(Value::as_u64).unwrap_or_default();            counts.add("cotton_emails", added as usize);            Ok(())        })?;        self.counts.add("cotton_email_threads", thread_keys.len());        Ok(())    }    /// `create_money_account {name, kind, institution, numberMask}`,    /// The transactions are [`Household::write_transactions`], the statements    /// [`Household::write_statements`].    fn write_money(&mut self) -> Result<()> {        let at = self.founded();        let env = &self.env;        // Accounts exist before their transactions and statement reads.        let wanted: Vec<_> = names::ACCOUNTS.iter().take(env.plan.accounts).collect();        let accounts = &mut self.accounts;        chunked(env, &mut self.counts, &wanted, |_| at, |ctx, (name, kind, institution, mask, currency), _| {            let mut args = object(json!({ "name": name, "kind": kind, "currency": currency }));            if let Some(institution) = institution {                args.insert("institution".into(), Value::from(*institution));            }            if let Some(mask) = mask {                args.insert("numberMask".into(), Value::from(*mask));            }            let out = call("money account", create_money_account(ctx, &args))?;            accounts.push((id_of("money account", &out)?, *kind, *currency));            Ok(())        })?;        Ok(())    }    /// Generate actual and expected single rows through the public writer.    fn write_transactions(&mut self) -> Result<()> {        let env = &self.env;        let rng = env.rng();        let mut items = Vec::new();        for n in 0..env.plan.transactions {            let account = &self.accounts[rng.below(self.accounts.len())];            let at = env.moment();            let expected = n % 13 == 0;            let between = n % 7 == 0 && !self.people.is_empty();            let mut args = object(json!({                "occurredOn": day(at), "accountId": account.0, "currency": account.2,                "amountMinor": rng.between(50,5000)*100, "amountKnown": true,                "direction": if n%4==0 {"in"} else {"out"},                "status": if expected {"expected"} else {"actual"},                "description": rng.pick(names::MERCHANTS), "betweenUs":between,                "movesMoney": true, "tag": if n%4==0 {"Income"} else {"Food"}            }));            if expected {                args.insert("certainty".into(), json!("expected"));            }            if between {                args.insert(                    "personId".into(),                    json!(self.people[n % self.people.len()].id),                );            }            items.push((at, args));        }        items.sort_by_key(|item| item.0);        let sample = &mut self.transactions;        chunked(            env,            &mut self.counts,            &items,            |item| item.0,            |ctx, (_, args), counts| {                let out = call("money transaction", record_transaction(ctx, args))?;                counts.add("cotton_money_transactions", 1);                if sample.len() < 12 {                    sample.extend(out.get("id").and_then(Value::as_str).map(str::to_string));                }                Ok(())            },        )?;        self.write_claims_in_two_currencies()    }    /// One person owed in BOTH currencies, so a walker can judge "Between    /// you" per currency side by side and never summed: the owner lent them    /// €50 from the first euro account and borrowed ₹1,200 from them into the    /// home account, three days ago. Every other claim is in the home    /// currency. Fixed words and no draw on the seed, after every draw.    fn write_claims_in_two_currencies(&mut self) -> Result<()> {        let env = &self.env;        let (Some(home), Some(euro), Some(person)) = (            self.accounts.first(),            self.accounts.iter().find(|account| account.2 == "EUR"),            self.people.first(),        ) else {            return Ok(());        };        let on = day(env.now - Duration::days(3));        let claims = [            ("lent", &euro.0, 5_000, format!("Lent to {}", person.first)),            ("borrowed", &home.0, 120_000, format!("Borrowed from {}", person.first)),        ];        env.once(env.now - Duration::days(3), |ctx| {            for (verb, account, amount, description) in claims {                let args = object(json!({                    "direction": if verb=="lent" {"out"} else {"in"}, "betweenUs":true, "status":"actual", "occurredOn": on, "accountId": account,                    "personId": person.id, "amountMinor": amount, "description": description,                }));                call("money transaction", record_transaction(ctx, &args))?;            }            Ok(())        })?;        self.counts.add("cotton_money_transactions", 2);        Ok(())    }}/// The first of the month `months` before `first` (itself a first).fn month_back(first: chrono::NaiveDate, months: i64) -> chrono::NaiveDate {    let total = i64::from(first.year()) * 12 + i64::from(first.month0()) - months;    chrono::NaiveDate::from_ymd_opt((total.div_euclid(12)) as i32, (total.rem_euclid(12)) as u32 + 1, 1)        .expect("a first of the month")}