Cotton code
1238 lines · 48.5 KB · RustRaw
//! `export.build` — "Export everything", below the boundary.//!//! The Home screen's database card closes with *"Everything here lives in your//! own database, nobody else's."* A sovereignty claim with no way to get the//! data out is a slogan, so this assembles the whole file as ONE JSON document//! and hands the app a PATH to it.//!//! ## Why here, and why a path//!//! It is a PORT of `apps/cotton/src/lib/exportEverything.ts`, which is pure//! local assembly over the `@cottondb/core` services — no server route, nothing//! to sign, nothing to upload. The crate is the one side that can walk the//! whole file in one pass (P4's own argument), and everything the TypeScript//! reached through fourteen services is a query against the replica here.//!//! **The answer is a path and a count, never bytes.** `read.mediaPath` answers//! a path for the same reason and AGENTS.md states the rule outright ("A big body//! is a FILE, never bytes"): a whole-database document crossing the FFI as a//! string is the jetsam kill build 106 already paid for. So the document is//! written to the data directory's own disposable `cache/exports/` folder —//! where the TypeScript writes to `Paths.cache` — and the app shares the file.//!//! ## Fidelity, and the four places this is NOT the TypeScript//!//! Every key, every field name, every filter, the ±5-year window, the media//! ceiling and the record count are the TypeScript's. Four differences are//! DECLARED rather than hidden, each beside the code that makes it://!//!   1. the year arithmetic and the file name's date are UTC, where a phone's//!      `Date` is local ([`shift_years`], [`export_file_name`]);//!   2. `collections[].color` and the media `subtypes` are passed through//!      rather than filtered against a catalogue that has no Rust declaration//!      ([`collections`], [`media_rows`]);//!   3. `captures[].routeProposal` and `.routedRecords` are the stored JSON,//!      not the TypeScript's lenient re-parse ([`captures`]).//!//! Nothing is omitted: every one of the TypeScript's eighteen top-level keys is//! written, over tables the Rust store already has.use crate::shell::file::ReadFile;use std::collections::{BTreeMap, BTreeSet};use std::path::{Path, PathBuf};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_client::layout::Layout;use cotton_core::rules::people::birthday::{columns_sql, whole_held, Birthday};use cotton_core::rules::people::handles::phones_and_emails_sql;use cotton_core::transforms::rrule::DateRange;use cotton_core::rules::series::{expand_calendar, SeriesRow};use cotton_core::transforms::zoned_clock::{date_utc, zoned_parts};use cotton_core::records::account_number_ending;use cotton_store::driver::{Driver, Row};use cotton_store::protocol::js::{parse_date_ms, to_iso_string};use cotton_store::schema::codecs::decode_row;use cotton_store::schema::specs::columns_of;use crate::handle::CottonHandle;use crate::methods::MethodError;/// Stamped into the document so a reader can tell what it is holding.pub const EXPORT_FORMAT: &str = "cottondb-export";/// The document's version — `EXPORT_VERSION` in `exportEverything.ts`, whose/// own version note is the history of what each bump changed.pub const EXPORT_VERSION: i64 = 8;/// How far either side of today the events read reaches.////// The events read has no raw row list — it lists engine-EXPANDED occurrences/// inside a window — so the export walks a wide window and dedupes back to the/// underlying event rows. The document states the window it used rather than/// implying it holds everything.pub const EXPORT_WINDOW_YEARS: i64 = 5;/// How many pictures and videos an export reads.////// A ceiling this document asks for by name, and the moment it BITES the/// document says so in `truncated`.pub const EXPORT_MEDIA_LIMIT: i64 = 1000;// ── the method ────────────────────────────────────────────────────────────/// Build the document, write it, and answer where it went.////// `args.now` is honoured the way the 4d reads honour it — the phone stands/// where its owner does — and otherwise the instant is the controller's own/// clock seam. Never a wall clock read inside this function: the seam is the/// thing a test replaces.pub fn build(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let args = request        .get("args")        .and_then(Value::as_object)        .cloned()        .unwrap_or_default();    let client = handle.client();    let now_iso = match args.get("now").and_then(Value::as_str) {        Some(iso) => iso.to_string(),        None => client.now_iso(),    };    let now_ms = parse_date_ms(&now_iso)        .ok_or_else(|| MethodError::new("bad_request", format!("`now` is not an ISO instant: {now_iso}")))?;    // The zone this phone is standing in, handed down at open — the same    // `time_zone` the 4d reads band by. The expansion below prefers the    // WORKSPACE's, exactly as `expansionZone()` does.    let device_zone = client.time_zone().map(str::to_string);    let document = client        .with_file(|replica| document(replica, now_ms, &now_iso, device_zone.as_deref()))        .map_err(|reason| MethodError::new("unreadable", reason))?;    let count = record_count(&document);    let file_name = export_file_name(now_ms)        .map_err(|reason| MethodError::new("bad_request", reason))?;    let written = write_document(handle.layout(), &file_name, &document)        .map_err(|reason| MethodError::new("unwritable", reason))?;    Ok(json!({        "path": written.path.to_string_lossy(),        "fileName": file_name,        "recordCount": count,        "sizeBytes": written.size_bytes,    }))}// ── the file ──────────────────────────────────────────────────────────────struct Written {    path: PathBuf,    size_bytes: u64,}/// The file name the share sheet offers: `cotton-export-2026-09-08.json`.////// The date is UTC's. The TypeScript reads `getFullYear`/`getMonth`/`getDate`/// off a local `Date`; there is no device zone below this boundary and this/// crate refuses to guess one, so the stamp differs by a day for the few hours/// either side of local midnight. It is a file NAME, not a fact in the/// document — `exportedAt` inside carries the instant itself.fn export_file_name(now_ms: i64) -> Result<String, String> {    let parts = zoned_parts(now_ms, "UTC").map_err(|error| error.to_string())?;    Ok(format!(        "cotton-export-{:04}-{:02}-{:02}.json",        parts.year, parts.month, parts.day    ))}/// Write the document under `cache/exports/`, and leave nothing else behind.////// The folder holds AT MOST ONE export: an earlier `cotton-export-*.json` is/// removed before the new one lands. A whole database as JSON is the largest/// object this app can produce, and one per day accumulating in a container/// nobody browses is a disk leak with a person's own data in it. The/// TypeScript's equivalent is `Paths.cache` plus a date-stamped name, which the/// OS reclaims; nothing reclaims this directory, so the writer does.////// Pretty-printed with two spaces — `JSON.stringify(doc, null, 2)` — because/// the person who exports their life is the one who opens the file.fn write_document(layout: &Layout, file_name: &str, document: &Value) -> Result<Written, String> {    let dir = layout.exports_dir();    std::fs::create_dir_all(&dir)        .map_err(|error| format!("the exports folder could not be made: {error}"))?;    clear_earlier_exports(&dir, file_name);    let path = dir.join(file_name);    let body = serde_json::to_vec_pretty(document)        .map_err(|error| format!("the export could not be rendered as JSON: {error}"))?;    let size_bytes = body.len() as u64;    // not a copy: an export.    std::fs::write(&path, &body)        .map_err(|error| format!("the export could not be written to {}: {error}", path.display()))?;    Ok(Written { path, size_bytes })}/// Remove every `cotton-export-*.json` that is not the one about to be written.////// Best effort on purpose: a file that will not delete is a stale copy in a/// cache folder, and refusing the export the person asked for over it would be/// the worse trade. Nothing else in this directory is touched.fn clear_earlier_exports(dir: &Path, keeping: &str) {    let Ok(entries) = std::fs::read_dir(dir) else {        return;    };    for entry in entries.flatten() {        let name = entry.file_name();        let Some(name) = name.to_str() else { continue };        if name == keeping || !name.starts_with("cotton-export-") || !name.ends_with(".json") {            continue;        }        // not a copy: an export.        let _ = std::fs::remove_file(entry.path());    }}// ── the document ──────────────────────────────────────────────────────────/// Read the whole database.////// Refuses on the first failure — a partial export that silently omits a/// tool's data would be worse than none, which is the TypeScript's own rule.fn document(    replica: &ReadFile<'_>,    now_ms: i64,    now_iso: &str,    device_zone: Option<&str>,) -> Result<Value, String> {    let db = &replica.driver;    let workspace_id = replica.workspace_id;    let from_ms = shift_years(now_ms, -EXPORT_WINDOW_YEARS)?;    let to_ms = shift_years(now_ms, EXPORT_WINDOW_YEARS)?;    let from_iso = iso_of(from_ms)?;    let to_iso = iso_of(to_ms)?;    let collections = collections(db, workspace_id)?;    let events = events(        db,        workspace_id,        DateRange {            from: from_ms,            to: to_ms,        },        &to_iso,        device_zone,    )?;    let transactions = money_transactions(db, workspace_id)?;    let statements = statements(db, workspace_id)?;    let statement_lines = statement_lines(db, &ids_of(&statements))?;    let photos = media_rows(db, workspace_id, "cotton_photos", PHOTO_FIELDS)?;    let videos = media_rows(db, workspace_id, "cotton_videos", VIDEO_FIELDS)?;    let mut truncated = Map::new();    // `>=` rather than `==` on purpose: a read that ever returned one more than    // it was asked for must still be reported as truncated, and the safe    // direction of this flag is "there may be more", never "this is everything".    if photos.len() as i64 >= EXPORT_MEDIA_LIMIT {        truncated.insert("photos".to_string(), Value::Bool(true));    }    if videos.len() as i64 >= EXPORT_MEDIA_LIMIT {        truncated.insert("videos".to_string(), Value::Bool(true));    }    Ok(json!({        "format": EXPORT_FORMAT,        "version": EXPORT_VERSION,        "exportedAt": now_iso,        "workspaceId": workspace_id,        "eventsWindow": { "from": from_iso, "to": to_iso },        "collections": collections,        "todos": todos(db, workspace_id)?,        "events": events,        "notes": notes(db, workspace_id)?,        "journal": journal(db, workspace_id, false)?,        "projectJournal": journal(db, workspace_id, true)?,        "people": people(db, workspace_id)?,        "captures": captures(db, workspace_id)?,        "money": {            "accounts": money_accounts(db, workspace_id)?,            "transactions": transactions,            "statements": statements,            "statementLines": statement_lines,        },        "documents": documents(db, workspace_id)?,        "photos": photos,        "videos": videos,        "truncated": Value::Object(truncated),    }))}/// How many records a finished export holds — the toast counts this.////// Transactions, not their lines: a person counts entries, not their halves./// Statements are not counted either — a statement IS one of the documents/// counted below, read into rows, so counting it would count one filed paper/// twice. Documents, not grants: a grant is something a document has. Pictures/// DO count: a photo is a row in this file, and a person asking how much of/// their life came out expects their pictures in the figure.fn record_count(document: &Value) -> i64 {    let len = |value: &Value| value.as_array().map_or(0, |rows| rows.len() as i64);    len(&document["todos"])        + len(&document["events"])        + len(&document["notes"])        + len(&document["journal"])        + len(&document["projectJournal"])        + len(&document["people"])        + len(&document["captures"])        + len(&document["money"]["transactions"])        + len(&document["documents"])        + len(&document["photos"])        + len(&document["videos"])}/// `now` shifted by whole years, `Date.prototype.setFullYear`'s way.////// [`date_utc`] IS `Date.UTC` including the day carry, so 29 February five/// years out lands on 1 March exactly as the phone's `Date` does. The parts are/// read in UTC rather than a device zone — see this module's note (2).fn shift_years(instant_ms: i64, years: i64) -> Result<i64, String> {    let parts = zoned_parts(instant_ms, "UTC").map_err(|error| error.to_string())?;    Ok(date_utc(        parts.year + years,        parts.month - 1,        parts.day,        parts.hour,        parts.minute,        parts.second,        instant_ms.rem_euclid(1_000),    ))}fn iso_of(instant_ms: i64) -> Result<String, String> {    to_iso_string(instant_ms)        .ok_or_else(|| format!("{instant_ms} is not an instant a calendar can read"))}// ── reading a table into the document's own shape ─────────────────────────fn param(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}fn rows_of(db: &Driver, sql: &str, params: &[SqlValue]) -> Result<Vec<Row>, String> {    db.all(sql, params).map_err(|error| error.to_string())}/// One row, decoded by its table's codecs and renamed to the document's keys.////// `fields` is `(documentKey, column)` in the order the TypeScript's transform/// writes them, which is why it is spelled out per table rather than derived by/// case-conversion: three of these lists rename a column (`personId` ←/// `counterparty_person_id`), several drop one (`birth_month` and its two/// siblings become `birthday`), and a derived key has no column at all./// [`decode_row`] is the same decoder the TypeScript's `decodeRow` is, so a/// boolean is a boolean and a JSON column is already parsed.fn shaped(table: &str, row: &Row, fields: &[(&str, &str)]) -> Result<Map<String, Value>, String> {    let columns = columns_of(table).ok_or_else(|| format!("{table} is not a table this store has"))?;    let mut decoded = decode_row(columns, row.columns()).map_err(|error| error.to_string())?;    let mut out = Map::new();    for (key, column) in fields {        let value = decoded.remove(*column).unwrap_or(Value::Null);        out.insert((*key).to_string(), value);    }    Ok(out)}/// Read a whole table's rows into the document's shape.fn shaped_rows(    db: &Driver,    table: &str,    fields: &[(&str, &str)],    sql: &str,    params: &[SqlValue],) -> Result<Vec<Value>, String> {    rows_of(db, sql, params)?        .iter()        .map(|row| shaped(table, row, fields).map(Value::Object))        .collect()}/// The ids of a list of already-shaped rows, in the order they came out.fn ids_of(rows: &[Value]) -> Vec<String> {    rows.iter()        .filter_map(|row| row["id"].as_str().map(str::to_string))        .collect()}/// A JSON array of non-empty strings, read TOTALLY.////// `stringListOf` in `models/media/enrichment.ts`: anything that is not a/// non-empty string is dropped rather than thrown on, because a grid must not/// blank because one row came through a path that predates the column.fn string_list(value: &Value) -> Value {    let Some(items) = value.as_array() else {        return Value::Array(Vec::new());    };    Value::Array(        items            .iter()            .filter(|item| item.as_str().is_some_and(|text| !text.is_empty()))            .cloned()            .collect(),    )}// ── collections, and the calendars events hang off ────────────────────────/// `listCollections` — every live collection, in the app's own order.////// `color` is passed through where the TypeScript maps an unrecognised value to/// null against `COLLECTION_COLORS`. That catalogue has no Rust declaration,/// and writing one here would be a second copy of a list TypeScript owns —/// exactly the drift a generated store exists to prevent. Every value a writer/// in this repo can store is in it.fn collections(db: &Driver, workspace_id: &str) -> Result<Vec<Value>, String> {    shaped_rows(        db,        "cotton_collections",        &[            ("id", "id"),            ("workspaceId", "workspace_id"),            ("kind", "kind"),            ("name", "name"),            ("isDefault", "is_default"),            ("sortKey", "sort_key"),            ("color", "color"),            ("createdAt", "created_at"),            ("archivedAt", "archived_at"),        ],        "SELECT * FROM cotton_collections WHERE workspace_id = ? AND archived_at IS NULL \         ORDER BY sort_key IS NULL, sort_key ASC, created_at ASC",        &[param(workspace_id)],    )}// ── the events window ─────────────────────────────────────────────────────const EVENT_FIELDS: &[(&str, &str)] = &[    ("id", "id"),    ("collectionId", "collection_id"),    ("title", "title"),    ("notes", "notes"),    ("startsAt", "starts_at"),    ("endsAt", "ends_at"),    ("allDay", "all_day"),    ("rrule", "rrule"),    ("location", "location"),    ("sourceInboxId", "source_inbox_id"),    ("gcalId", "gcal_id"),    ("gcalEtag", "gcal_etag"),    ("syncState", "sync_state"),    ("organizerIsSelf", "organizer_is_self"),    ("myResponse", "my_response"),    ("seriesId", "series_id"),    ("originalStartsAt", "original_starts_at"),    ("exdates", "exdates"),    ("trashedAt", "trashed_at"),    ("createdAt", "created_at"),    ("updatedAt", "updated_at"),];/// The event ROWS that produce at least one occurrence in the window.////// `listEvents` has no raw row list: it reads candidates, EXPANDS them through/// the engine, and the export dedupes the occurrences back to the rows that/// drew them. So a trashed master contributes nothing (the expansion drops it,/// which is why there is no `trashed_at` predicate in the SQL — the TypeScript/// has none either, deliberately), and an event whose every occurrence falls/// outside ±5 years is simply absent.////// The candidate predicate is the TypeScript's, less its calendar: `starts_at/// <= to OR original_starts_at <= to`, both bound to the window's END — every/// event of the database, which is what an event belongs to (the object keeps/// no calendars; 27 Oct 2026). The engine, not the query, decides what is in/// range.fn events(    db: &Driver,    workspace_id: &str,    range: DateRange,    to_iso: &str,    device_zone: Option<&str>,) -> Result<Vec<Value>, String> {    let params: Vec<SqlValue> = vec![param(to_iso), param(to_iso)];    let sql = "SELECT * FROM cotton_events WHERE (starts_at <= ? OR original_starts_at <= ?) ORDER BY starts_at ASC";    let mut shaped_by_id: BTreeMap<String, Value> = BTreeMap::new();    let mut order: Vec<String> = Vec::new();    let mut series: Vec<SeriesRow> = Vec::new();    for row in rows_of(db, sql, &params)? {        let mut event = shaped("cotton_events", &row, EVENT_FIELDS)?;        // `parseExdates` flattens NULL and a non-list alike to `[]`, and drops        // a non-string member.        let exdates = string_list(event.get("exdates").unwrap_or(&Value::Null));        event.insert("exdates".to_string(), exdates.clone());        let id = event["id"]            .as_str()            .ok_or_else(|| "an event row answered no id".to_string())?            .to_string();        series.push(SeriesRow {            id: id.clone(),            starts_at: text_of(&event, "startsAt"),            ends_at: opt_text_of(&event, "endsAt"),            rrule: opt_text_of(&event, "rrule"),            exdates: Some(                exdates                    .as_array()                    .map(|items| {                        items                            .iter()                            .filter_map(|item| item.as_str().map(str::to_string))                            .collect()                    })                    .unwrap_or_default(),            ),            series_id: opt_text_of(&event, "seriesId"),            original_starts_at: opt_text_of(&event, "originalStartsAt"),            trashed_at: opt_text_of(&event, "trashedAt"),        });        order.push(id.clone());        shaped_by_id.insert(id, Value::Object(event));    }    let zone = expansion_zone(db, workspace_id, device_zone)?;    let occurrences = expand_calendar(&series, range, &zone).map_err(|error| error.to_string())?;    let drawn: BTreeSet<String> = occurrences        .into_iter()        .map(|occurrence| occurrence.event_id)        .collect();    Ok(order        .into_iter()        .filter(|id| drawn.contains(id))        .filter_map(|id| shaped_by_id.remove(&id))        .collect())}fn text_of(row: &Map<String, Value>, key: &str) -> String {    row.get(key)        .and_then(Value::as_str)        .unwrap_or_default()        .to_string()}fn opt_text_of(row: &Map<String, Value>, key: &str) -> Option<String> {    row.get(key).and_then(Value::as_str).map(str::to_string)}/// The zone a recurrence is expanded in — `expansionZone()`, exactly.////// The WORKSPACE's zone first, and this device's when the workspace has never/// recorded one. That order is deliberate and is the TypeScript's: one producer/// per state, so the phone and the server cannot come to disagree about when a/// repeating appointment happens. It is the opposite order from/// `phone::reads`' own `reading_zone`, which takes the device's and only the/// device's — a day BOUNDARY is the device's calendar day, an expansion is the/// workspace's rule — and both are ports of what the app already does.////// UTC is the floor, and it is the TypeScript's floor too: `deviceZone()` is/// `Intl…timeZone || "UTC"`. It is reached only by a workspace with no zone on/// a device that named none, and it moves an occurrence at the very edge of a/// ten-year window and nothing else.////// The workspace's zone lives on `cotton_news_settings` — the one row that/// names it.fn expansion_zone(    db: &Driver,    workspace_id: &str,    device_zone: Option<&str>,) -> Result<String, String> {    let found = rows_of(        db,        "SELECT timezone FROM cotton_news_settings WHERE workspace_id = ?",        &[param(workspace_id)],    )?;    let named = |zone: Option<&str>| {        zone.map(str::to_string)            .filter(|zone| !zone.trim().is_empty())    };    Ok(named(found.first().and_then(|row| row.text("timezone")))        .or_else(|| named(device_zone))        .unwrap_or_else(|| "UTC".to_string()))}// ── todos, notes, journal ─────────────────────────────────────────────────/// `listTodos` — everything but the DROPPED ones, which the export does not/// carry because the app's own list does not.fn todos(db: &Driver, workspace_id: &str) -> Result<Vec<Value>, String> {    shaped_rows(        db,        "cotton_todos",        &[            ("id", "id"),            ("workspaceId", "workspace_id"),            ("title", "title"),            ("notes", "notes"),            ("status", "status"),            ("dueAt", "due_at"),            ("snoozedUntil", "snoozed_until"),            ("priority", "priority"),            ("completedAt", "completed_at"),            ("sourceInboxId", "source_inbox_id"),            ("recurrenceId", "recurrence_id"),            ("occurrenceAt", "occurrence_at"),            ("createdAt", "created_at"),            ("updatedAt", "updated_at"),        ],        "SELECT * FROM cotton_todos WHERE workspace_id = ? AND status != 'dropped' \         ORDER BY due_at IS NULL, due_at ASC, created_at ASC",        &[param(workspace_id)],    )}const NOTE_FIELDS: &[(&str, &str)] = &[    ("id", "id"),    ("workspaceId", "workspace_id"),    ("kind", "kind"),    ("title", "title"),    ("body", "body"),    ("journalDate", "journal_date"),    ("projectId", "project_id"),    ("publishedAt", "published_at"),    ("publicSlug", "public_slug"),    ("sourceInboxId", "source_inbox_id"),    ("archivedAt", "archived_at"),    ("authorKind", "author_kind"),    ("authorLabel", "author_label"),    ("managedBy", "managed_by"),    ("externalId", "external_id"),    ("sourceHash", "source_hash"),    ("createdAt", "created_at"),    ("updatedAt", "updated_at"),];/// `listNotes` — the person's own notes. A MANAGED note is a mirror of/// something else and the default read excludes it, so the export does too.fn notes(db: &Driver, workspace_id: &str) -> Result<Vec<Value>, String> {    shaped_rows(        db,        "cotton_notes",        NOTE_FIELDS,        "SELECT * FROM cotton_notes WHERE workspace_id = ? AND kind = 'note' \         AND archived_at IS NULL AND managed_by IS NULL ORDER BY updated_at DESC",        &[param(workspace_id)],    )}/// `listJournal` (the OWNER's pages, `project_id IS NULL`) and/// `listProjectJournal` (every project's), which are two keys rather than one/// wider list because a reader would have no way to tell them apart in one.fn journal(db: &Driver, workspace_id: &str, of_projects: bool) -> Result<Vec<Value>, String> {    let predicate = if of_projects {        "project_id IS NOT NULL"    } else {        "project_id IS NULL"    };    shaped_rows(        db,        "cotton_notes",        NOTE_FIELDS,        &format!(            "SELECT * FROM cotton_notes WHERE workspace_id = ? AND kind = 'journal' \             AND {predicate} AND archived_at IS NULL \             ORDER BY journal_date IS NULL, journal_date DESC"        ),        &[param(workspace_id)],    )}// ── people ────────────────────────────────────────────────────────────────/// `listPeople` — every live person, by name.////// `birthday` is DERIVED from three columns the document does not carry, and/// `phones`/`emails` default to a list rather than null, both as `toIPerson`/// does.fn people(db: &Driver, workspace_id: &str) -> Result<Vec<Value>, String> {    // `phones`/`emails` live in `cotton_person_handles` since v90; the    // document keeps answering them as the two lists a person always had.    // The birthday's own columns ride along ([`columns_sql`]), so a copy    // that keeps the object's whole date exports it by the one rule.    let held = whole_held(db).map_err(|error| error.to_string())?;    let found = rows_of(        db,        &format!(            "SELECT p.*, {}, {} FROM cotton_people p WHERE p.workspace_id = ? AND p.archived_at IS NULL \             ORDER BY p.full_name ASC",            phones_and_emails_sql("p.id"),            columns_sql("p", held)        ),        &[param(workspace_id)],    )?;    let mut out = Vec::with_capacity(found.len());    for row in &found {        let mut person = shaped(            "cotton_people",            row,            &[                ("id", "id"),                ("workspaceId", "workspace_id"),                ("fullName", "full_name"),                ("org", "org"),                ("roleTitle", "role_title"),                ("city", "city"),                ("summary", "summary"),                ("summaryBy", "summary_by"),                ("summaryUpdatedAt", "summary_updated_at"),                ("contactSource", "contact_source"),                ("deviceContactId", "device_contact_id"),                // Placeholder, replaced below: `birthday` has no column.                ("birthday", "birth_month"),                ("timezone", "timezone"),                ("avatarKey", "avatar_key"),                ("deviceContactSnapshot", "device_contact_snapshot"),                ("archivedAt", "archived_at"),                ("createdAt", "created_at"),                ("updatedAt", "updated_at"),            ],        )?;        for key in ["phones", "emails"] {            let list = row                .text(key)                .and_then(|raw| serde_json::from_str::<Value>(raw).ok())                .unwrap_or(Value::Null);            person.insert(key.to_string(), string_list(&list));        }        person.insert("birthday".to_string(), birthday(row)?);        let snapshot = person            .get("deviceContactSnapshot")            .cloned()            .unwrap_or(Value::Null);        assert_snapshot_v1(&snapshot)?;        out.push(Value::Object(person));    }    Ok(out)}/// `parseBirthday` — both, or neither.////// A half-set birthday is a refusal rather than a guess: a month with no day/// would export as a date nobody can read back, and the row is wrong at the/// source. `cotton_people` carries a CHECK saying the same thing, so this is a/// floor rather than a path — kept because the TypeScript keeps it, and because/// a reader that trusted a constraint it cannot see is a reader that goes quiet/// if the constraint ever moves.////// Past that floor, the birthday is `cotton_core::rules::people::birthday`'s/// one rule: the three columns where set, else the date a signed-in copy/// keeps whole from the object.fn birthday(row: &Row) -> Result<Value, String> {    let month = row.int("birth_month");    let day = row.int("birth_day");    if month.is_some() != day.is_some() {        return Err(format!(            "cotton_people.birth_month/birth_day: {{\"month\":{month:?},\"day\":{day:?}}}. \             Both must be set, or neither."        ));    }    Ok(Birthday::of_row(row).map_or(Value::Null, |birthday| json!({        "month": birthday.month,        "day": birthday.day,        "year": birthday.year,    })))}/// `parseDeviceContactSnapshot` — only `v: 1` is known.////// A snapshot from a later build is refused rather than exported as a shape no/// reader of this document can trust. The PAYLOAD is withheld from the message/// on purpose: that column is the owner's address book.fn assert_snapshot_v1(snapshot: &Value) -> Result<(), String> {    if snapshot.is_null() {        return Ok(());    }    if snapshot.get("v") == Some(&json!(1)) {        return Ok(());    }    Err("cotton_people.device_contact_snapshot: only v1 is known. \         The payload is withheld on purpose."        .to_string())}// ── captures ──────────────────────────────────────────────────────────────/// `listInbox` — every capture, newest first, whatever it was routed to.////// `routeProposal` and `routedRecords` are the STORED JSON. The TypeScript/// re-parses them leniently on the way out — dropping a record whose kind it/// cannot file and re-deriving a page's host — which is a reader's/// normalisation, not the row. The column has always held the contract's own/// camelCase shape (`routing/core.rs`'s `pending_patch` says so beside the/// write), so what comes out here is what the router wrote, unnarrowed. Porting/// the lenient reader would mean declaring its seven target shapes a second/// time in Rust with nothing holding the two copies together.fn captures(db: &Driver, workspace_id: &str) -> Result<Vec<Value>, String> {    let found = rows_of(        db,        "SELECT * FROM cotton_inbox_items WHERE workspace_id = ? ORDER BY captured_at DESC",        &[param(workspace_id)],    )?;    let mut out = Vec::with_capacity(found.len());    for row in &found {        let mut capture = shaped(            "cotton_inbox_items",            row,            &[                ("id", "id"),                ("workspaceId", "workspace_id"),                ("rawText", "raw_text"),                ("transcript", "transcript"),                ("audioUrl", "audio_url"),                ("capturedAt", "captured_at"),                ("routeStatus", "route_status"),                ("routedKind", "routed_kind"),                ("routedId", "routed_id"),                ("routedRecords", "routed_records"),                ("routeConfidence", "route_confidence"),                ("routeReason", "route_reason"),                ("routeProposal", "route_proposal"),                ("sweptAt", "swept_at"),                ("sweepNote", "sweep_note"),                ("correctionOf", "correction_of"),                ("createdAt", "created_at"),                ("updatedAt", "updated_at"),            ],        )?;        // A list, never null — `parseRoutedRecords` answers `[]` for anything        // that is not an array.        if !capture            .get("routedRecords")            .is_some_and(|value| value.is_array())        {            capture.insert("routedRecords".to_string(), Value::Array(Vec::new()));        }        // The column is DecimalText, so the store decodes it to a string and        // the model's `Number(...)` is what makes it a number here.        let confidence = capture            .get("routeConfidence")            .and_then(Value::as_str)            .and_then(|text| text.trim().parse::<f64>().ok())            .and_then(serde_json::Number::from_f64)            .map_or(Value::Null, Value::Number);        capture.insert("routeConfidence".to_string(), confidence);        out.push(Value::Object(capture));    }    Ok(out)}// ── the money ─────────────────────────────────────────────────────────────/// `listAccounts` — every live account, by name.fn money_accounts(db: &Driver, workspace_id: &str) -> Result<Vec<Value>, String> {    let mut accounts = shaped_rows(        db,        "cotton_money_accounts",        &[            ("id", "id"),            ("workspaceId", "workspace_id"),            ("kind", "kind"),            ("subtype", "subtype"),            ("name", "name"),            ("personId", "counterparty_person_id"),            ("currency", "currency"),            ("institution", "institution"),            ("numberMask", "number_mask"),            ("isDefault", "is_default"),            ("isPooled", "is_pooled"),            ("archivedAt", "archived_at"),            ("createdAt", "created_at"),            ("updatedAt", "updated_at"),        ],        "SELECT * FROM cotton_money_accounts WHERE workspace_id = ? AND archived_at IS NULL \         ORDER BY name ASC",        &[param(workspace_id)],    )?;    for account in &mut accounts {        if let Some(number) = account            .get("numberMask")            .and_then(Value::as_str)            .map(str::to_owned)        {            account["numberMask"] = Value::String(account_number_ending(&number));        }    }    Ok(accounts)}/// `listTransactions` with no filters — money is not windowed the way a/// recurring calendar has to be. Every entry ever made comes out, which is the/// only version of a person's own figures an accountant can use.fn money_transactions(db: &Driver, workspace_id: &str) -> Result<Vec<Value>, String> {    shaped_rows(        db,        "cotton_money_transactions",        &[            ("id", "id"),            ("workspaceId", "workspace_id"),            ("occurredOn", "occurred_on"),            ("description", "description"),            ("payeeText", "payee_text"),            ("accountId", "account_id"),            ("personId", "counterparty_person_id"),            ("amountMinor", "amount_minor"),            ("amountKnown", "amount_known"),            ("direction", "direction"),            ("currency", "currency"),            ("forPeriod", "for_period"),            ("status", "status"),            ("certainty", "certainty"),            ("repeat", "repeat"),            ("repeatDay", "repeat_day"),            ("betweenUs", "between_us"),            ("movesMoney", "moves_money"),            ("tag", "tag"),            ("transferOf", "transfer_of"),            ("source", "source"),            ("externalHash", "external_hash"),            ("notes", "notes"),            ("settlesTransactionId", "settles_transaction_id"),            ("dueDate", "due_date"),            ("sourceInboxId", "source_inbox_id"),            ("createdBy", "created_by"),            ("createdAt", "created_at"),            ("updatedAt", "updated_at"),        ],        "SELECT * FROM cotton_money_transactions WHERE workspace_id = ? ORDER BY occurred_on DESC",        &[param(workspace_id)],    )}/// `listStatements` — the paper behind the figures. Unwindowed for the same/// reason the transactions are.fn statements(db: &Driver, workspace_id: &str) -> Result<Vec<Value>, String> {    shaped_rows(        db,        "cotton_money_statements",        &[            ("id", "id"),            ("workspaceId", "workspace_id"),            ("documentId", "document_id"),            ("accountId", "account_id"),            ("kind", "kind"),            ("periodStart", "period_start"),            ("periodEnd", "period_end"),            ("openingBalanceMinor", "opening_balance_minor"),            ("closingBalanceMinor", "closing_balance_minor"),            ("currency", "currency"),            ("readStatus", "read_status"),            ("readError", "read_error"),            ("readBy", "read_by"),            ("readAt", "read_at"),            ("lineCount", "line_count"),            ("sumInMinor", "sum_in_minor"),            ("sumOutMinor", "sum_out_minor"),            ("balanceCheck", "balance_check"),            ("createdAt", "created_at"),            ("updatedAt", "updated_at"),        ],        "SELECT * FROM cotton_money_statements WHERE workspace_id = ? \         ORDER BY period_start DESC NULLS LAST, created_at DESC",        &[param(workspace_id)],    )}/// Every statement's own lines, flattened into one list, each carrying its/// `statementId` — so the shape a reader needs is a group-by rather than a/// nested document that could not be streamed.////// `state` and `transactionId` are DERIVED, never stored: `ignored` wins over/// booked, and a line is booked when a `statement_line` evidence row cites it./// The rule is `money/statements.rs`'s and `money/book.rs`'s `booked_line_ids`;/// this is the same two facts read against the replica's own driver.fn statement_lines(db: &Driver, statement_ids: &[String]) -> Result<Vec<Value>, String> {    let mut out = Vec::new();    for statement_id in statement_ids {        let found = rows_of(            db,            "SELECT * FROM cotton_money_statement_lines WHERE statement_id = ? \             ORDER BY line_no ASC",            &[param(statement_id)],        )?;        let booked = booked_lines(db, statement_id)?;        for row in &found {            let mut line = shaped(                "cotton_money_statement_lines",                row,                &[                    ("id", "id"),                    ("workspaceId", "workspace_id"),                    ("statementId", "statement_id"),                    ("page", "page"),                    ("lineNo", "line_no"),                    ("postedOn", "posted_on"),                    ("text", "text"),                    ("amountMinor", "amount_minor"),                    ("direction", "direction"),                    ("balanceAfterMinor", "balance_after_minor"),                    ("reference", "reference"),                    ("fingerprint", "fingerprint"),                    ("ignoredReason", "ignored_reason"),                    ("createdAt", "created_at"),                ],            )?;            let id = line["id"]                .as_str()                .ok_or_else(|| "a statement line answered no id".to_string())?                .to_string();            let transaction_id = booked.get(&id);            let state = if !line["ignoredReason"].is_null() {                "ignored"            } else if transaction_id.is_some() {                "booked"            } else {                "unbooked"            };            line.insert("state".to_string(), json!(state));            line.insert(                "transactionId".to_string(),                transaction_id.map_or(Value::Null, |id| Value::from(id.clone())),            );            out.push(Value::Object(line));        }    }    Ok(out)}/// line id → the transaction that cites it. Absent means unbooked.fn booked_lines(db: &Driver, statement_id: &str) -> Result<BTreeMap<String, String>, String> {    let found = rows_of(        db,        "SELECT ref_id, transaction_id FROM cotton_money_evidence WHERE kind = 'statement_line' \         AND ref_id IN (SELECT id FROM cotton_money_statement_lines WHERE statement_id = ?)",        &[param(statement_id)],    )?;    let mut out = BTreeMap::new();    for row in &found {        if let (Some(ref_id), Some(transaction_id)) =            (row.text("ref_id"), row.text("transaction_id"))        {            out.insert(ref_id.to_string(), transaction_id.to_string());        }    }    Ok(out)}// ── the vault ─────────────────────────────────────────────────────────────/// `documents.list` — the vault's rows, PASSWORDS INCLUDED.////// Deliberate, and it is the whole point: an export that carried the papers but/// not the passwords would hand somebody a folder of files they cannot open —/// the precise failure the vault exists to end. The export is already the most/// sensitive object Cotton can produce, it goes to the share sheet by the/// person themselves, and redacting one column would not make the rest safe.////// The BYTES are not here: each row carries its `storagePath`, so a future/// archive export can walk them.fn documents(db: &Driver, workspace_id: &str) -> Result<Vec<Value>, String> {    let found = rows_of(        db,        "SELECT * FROM cotton_documents WHERE workspace_id = ? \         ORDER BY document_date IS NULL, document_date DESC, created_at DESC",        &[param(workspace_id)],    )?;    let mut out = Vec::with_capacity(found.len());    for row in &found {        let mut document = shaped(            "cotton_documents",            row,            &[                ("id", "id"),                ("workspaceId", "workspace_id"),                ("title", "title"),                ("originalName", "original_name"),                ("mime", "mime"),                ("byteSize", "byte_size"),                ("sha256", "sha256"),                ("storagePath", "storage_path"),                ("decryptedPath", "decrypted_path"),                ("password", "password"),                ("pageCount", "page_count"),                ("status", "status"),                ("failedStage", "failed_stage"),                ("errorCode", "error_code"),                ("statusChangedAt", "status_changed_at"),                ("docType", "doc_type"),                ("documentDate", "document_date"),                ("periodStart", "period_start"),                ("periodEnd", "period_end"),                ("issuer", "issuer"),                ("summary", "summary"),                ("facts", "facts"),                ("textExtracted", "text_extracted"),                ("source", "source"),                ("mcpTokenId", "mcp_token_id"),                ("createdAt", "created_at"),                ("updatedAt", "updated_at"),            ],        )?;        // An open bag, and anything that is not an object reads as an empty        // one — `toIDocument` says so.        if !document.get("facts").is_some_and(Value::is_object) {            document.insert("facts".to_string(), Value::Object(Map::new()));        }        out.push(Value::Object(document));    }    Ok(out)}// ── the pictures ──────────────────────────────────────────────────────────/// The seventeen enrichment columns both media tables carry, in the order/// `enrichmentOf` spreads them.const ENRICHMENT_FIELDS: &[(&str, &str)] = &[    ("takenOffset", "taken_offset"),    ("latitude", "latitude"),    ("longitude", "longitude"),    ("placeName", "place_name"),    ("placeCity", "place_city"),    ("placeRegion", "place_region"),    ("placeCountry", "place_country"),    ("cameraMake", "camera_make"),    ("cameraModel", "camera_model"),    ("orientation", "orientation"),    ("favourite", "favourite"),    ("subtypes", "subtypes"),    ("originalFilename", "original_filename"),    ("aestheticScore", "aesthetic_score"),    ("curationScore", "curation_score"),    ("labels", "labels"),    ("phash", "phash"),];const PHOTO_HEAD: &[(&str, &str)] = &[    ("id", "id"),    ("workspaceId", "workspace_id"),    ("key", "key"),    ("sha256", "sha256"),    ("contentType", "content_type"),    ("sizeBytes", "size_bytes"),    ("width", "width"),    ("height", "height"),    ("takenAt", "taken_at"),];const PHOTO_TAIL: &[(&str, &str)] = &[    ("preview", "preview"),    ("caption", "caption"),    ("summary", "summary"),    ("summaryBy", "summary_by"),    ("summaryAt", "summary_at"),    ("reviewNote", "review_note"),    ("reviewBy", "review_by"),    ("reviewAt", "review_at"),    ("ocrText", "ocr_text"),    ("isUtility", "is_utility"),    ("createdAt", "created_at"),    ("updatedAt", "updated_at"),];const VIDEO_HEAD: &[(&str, &str)] = &[    ("id", "id"),    ("workspaceId", "workspace_id"),    ("key", "key"),    ("sha256", "sha256"),    ("contentType", "content_type"),    ("sizeBytes", "size_bytes"),    ("width", "width"),    ("height", "height"),    ("durationMs", "duration_ms"),    ("takenAt", "taken_at"),];const VIDEO_TAIL: &[(&str, &str)] = &[    ("preview", "preview"),    ("posterKey", "poster_key"),    ("caption", "caption"),    ("summary", "summary"),    ("summaryBy", "summary_by"),    ("summaryAt", "summary_at"),    ("reviewNote", "review_note"),    ("reviewBy", "review_by"),    ("reviewAt", "review_at"),    ("createdAt", "created_at"),    ("updatedAt", "updated_at"),];/// Which halves a media table's document shape is made of.struct MediaFields {    head: &'static [(&'static str, &'static str)],    tail: &'static [(&'static str, &'static str)],}const PHOTO_FIELDS: &MediaFields = &MediaFields {    head: PHOTO_HEAD,    tail: PHOTO_TAIL,};const VIDEO_FIELDS: &MediaFields = &MediaFields {    head: VIDEO_HEAD,    tail: VIDEO_TAIL,};/// Every picture or video the person holds, up to the document's own ceiling.////// `favourite` is a boolean and never null, and `subtypes`/`labels` are lists/// and never null, as `enrichmentOf` has them. The subtype MEMBERS are not/// filtered against `PHOTO_SUBTYPES` the way the TypeScript filters them: that/// catalogue has no Rust declaration, and writing one here would be a second/// copy of a list TypeScript owns.////// The BYTES are not here: each row carries its `key` (and a video its/// `posterKey`), so a future archive export can walk them.fn media_rows(    db: &Driver,    workspace_id: &str,    table: &str,    fields: &MediaFields,) -> Result<Vec<Value>, String> {    let all: Vec<(&str, &str)> = fields        .head        .iter()        .chain(ENRICHMENT_FIELDS.iter())        .chain(fields.tail.iter())        .copied()        .collect();    let sql = format!(        "SELECT * FROM {table} WHERE {table}.workspace_id = ? \         ORDER BY {table}.taken_at DESC, {table}.id ASC LIMIT ?"    );    let found = rows_of(        db,        &sql,        &[param(workspace_id), SqlValue::Integer(EXPORT_MEDIA_LIMIT)],    )?;    let mut out = Vec::with_capacity(found.len());    for row in &found {        let mut item = shaped(table, row, &all)?;        let favourite = item.get("favourite") == Some(&Value::Bool(true));        item.insert("favourite".to_string(), Value::Bool(favourite));        item.insert(            "subtypes".to_string(),            string_list(item.get("subtypes").unwrap_or(&Value::Null)),        );        item.insert(            "labels".to_string(),            string_list(item.get("labels").unwrap_or(&Value::Null)),        );        out.push(Value::Object(item));    }    Ok(out)}#[cfg(test)]#[path = "export_tests.rs"]mod tests;