Cotton code
500 lines · 22.1 KB · RustRaw
//! An id two producers can agree on without talking to each other.//!//! Most rows are minted by whoever writes them first, and that is fine because//! only one writer ever has a reason to create them. A materialized recurrence//! occurrence is not like that: the phone's opportunistic pass and the server's//! hourly sweep BOTH compute, from the same rule, that the 2nd of November is//! owed a row. In a file whose replication unit is a ROW ID that is a poison//! pill — the fold resolves by primary key, so the second arrival is an INSERT//! of an unseen id that trips the natural key's UNIQUE constraint.//!//! So the id is DERIVED from the natural key instead: sha256 over the table//! name and the key parts, rendered uuid-shaped because every other id in this//! schema is a uuid and a column holding two kinds of thing invites someone to//! parse it. The table name is mixed in so two tables cannot collide on the//! same key values.//!//! EVERY named wrapper below exists for one reason: the two sides agreeing IS//! the point, and one function with one argument order removes the chance of//! the server hashing `(id, iso)` while the phone hashes `(iso, id)`.use crate::file_identity::{FileId, Namespace};pub use cotton_rules::ids::derived_id;// ── the ids two DEVICES have to agree on ───────────────────────────────────//// The block below exists for a second reason, and it is the merge rather than// the sweep. When two files of one person's life are joined, one adopts the// other's workspace id and the two exchange everything; from that moment both// halves are in one file, and a workspace-scoped UNIQUE index is a wall. Two// devices that each made a project called "cotton" arrive as two rows with two// minted uuids and one `(workspace_id, slug)` — the second is a rejection, and// nobody asked for two "cotton" projects.//// Derived from the natural key, the two are ONE row and the per-column fold// merges them. The honest limit is written where anyone can read it: a row// MINTED before this shipped keeps its uuid, so two old rows with equal slugs// still collide, and the receiver parks the rejection with its patch rather// than renaming anything. Derived ids fix the future; the merge report names// what they could not.//// Each takes the file's `Namespace`, never a bare string: a database made at// the stop derives under the OLD file's id, so its records keep the ids every// device already holds, and only the open file knows which value that is. The// repository family is the exception and takes the `FileId` — a repository's// id names its clone on disk, and two files sharing a namespace must never// share a clone./// A project's id — `(workspace, slug)`, the table's own UNIQUE.pub fn memory_project_id(namespace: &Namespace, slug: &str) -> String {    derived_id("cotton_memory_projects", &[namespace.as_str(), slug])}/// A repository's id — `(workspace, key)`, `cotton_repos`' own UNIQUE.////// Two Macs each run a `ReposWorker`, and a repository is DISCOVERED rather/// than created by a person: both list the same forge, both see/// `git.example.com/owner/name`, and before either had synced they each minted/// a uuid for it. The second to arrive is refused by/// `UNIQUE (workspace_id, key)` for ever, every later pass of its mirror is a/// patch of a row that does not exist here, and its commits, pulls and issues/// fail the foreign key at the repository that never landed. That is where/// 49,632 parked writes on one standby Mac came from.pub fn repo_id(file: &FileId, key: &str) -> String {    derived_id("cotton_repos", &[file.as_str(), key])}/// A mirrored pull request's id — `(workspace, repo, number)`.pub fn repo_pull_id(file: &FileId, repo_id: &str, number: i64) -> String {    derived_id("cotton_repo_pulls", &[file.as_str(), repo_id, &number.to_string()])}/// A mirrored issue's id — `(workspace, repo, number)`.pub fn repo_issue_id(file: &FileId, repo_id: &str, number: i64) -> String {    derived_id(        "cotton_repo_issues",        &[file.as_str(), repo_id, &number.to_string()],    )}/// A mirrored comment's id — `(workspace, repo, kind, remote_id)`.pub fn repo_comment_id(    file: &FileId,    repo_id: &str,    kind: &str,    remote_id: i64,) -> String {    derived_id(        "cotton_repo_comments",        &[file.as_str(), repo_id, kind, &remote_id.to_string()],    )}/// A mirrored commit's id — `(workspace, repo, sha)`.////// TWO writers mint this one — the repository worker's poll and the mirror's/// own commit page — which is a second reason it cannot be minted: they are/// both on this Mac and they still have to agree.pub fn repo_commit_id(file: &FileId, repo_id: &str, sha: &str) -> String {    derived_id("cotton_repo_commits", &[file.as_str(), repo_id, sha])}/// A mirrored release's id — `(workspace, repo, tag)`.pub fn repo_release_id(file: &FileId, repo_id: &str, tag: &str) -> String {    derived_id("cotton_repo_releases", &[file.as_str(), repo_id, tag])}/// A mirrored bundle's id — `(workspace, repo, sha256)`.pub fn repo_bundle_id(file: &FileId, repo_id: &str, sha256: &str) -> String {    derived_id("cotton_repo_bundles", &[file.as_str(), repo_id, sha256])}/// One Mac's clone of a held repository — `(workspace, repo, device)`,/// `cotton_repo_clones`' own UNIQUE. Only that Mac writes it, so a second/// write of its clone's state is a restatement of the same row.pub fn repo_clone_id(file: &FileId, repo_id: &str, device_id: &str) -> String {    derived_id("cotton_repo_clones", &[file.as_str(), repo_id, device_id])}/// A logged prompt's id — `(session, seq)`, `cotton_prompts`' own UNIQUE.pub fn prompt_id(session_id: &str, seq: i64) -> String {    derived_id("cotton_prompts", &[session_id, &seq.to_string()])}/// A mirrored task's id — `(session, seq)`, `cotton_session_tasks`' own UNIQUE.////// [`prompt_id`]'s reason exactly: the mirror may reach two servers, and a/// uuid apiece is two rows one index refuses to hold.pub fn session_task_id(session_id: &str, seq: i64) -> String {    derived_id("cotton_session_tasks", &[session_id, &seq.to_string()])}/// A note attachment's id — `(note, kind, record)`, the table's own UNIQUE.////// The natural key, hashed, for the reason every derived id here exists: the/// same picture attached to the same note from the phone and from a Mac is ONE/// row the fold merges, where two minted uuids would be a second row the/// UNIQUE refuses and an op parked for ever. It is note-scoped rather than/// workspace-scoped because the UNIQUE is: a note belongs to exactly one/// workspace, so the note id already carries that scope.pub fn note_attachment_id(note_id: &str, record_kind: &str, record_id: &str) -> String {    derived_id(        "cotton_note_attachments",        &[note_id, record_kind, record_id],    )}/// A thought attachment's id — `(thought, kind, record)`, the table's own/// UNIQUE; [`note_attachment_id`]'s reason with the owner renamed. Thought-scoped/// rather than workspace-scoped because the UNIQUE is.pub fn thought_attachment_id(thought_id: &str, record_kind: &str, record_id: &str) -> String {    derived_id(        "cotton_thought_attachments",        &[thought_id, record_kind, record_id],    )}/// A project's standing CONVERSATION — `(workspace, project)`.////// The conversation is at most one per project and the file says so with a/// partial unique index; deriving the id is what keeps that index from ever/// having to REFUSE anything. Two devices opening one project's conversation/// in the same minute arrive at the same row and the per-column fold merges/// them, where two minted uuids would be a rejection parked for ever.pub fn project_conversation_id(namespace: &Namespace, project_id: &str) -> String {    derived_id("cotton_sessions", &["conversation", namespace.as_str(), project_id])}/// A session's id — `(tool, external_id)`, `cotton_sessions`' own UNIQUE.////// NOT workspace-scoped, because the index is not: an agent's own session id is/// unique to its tool, and a person has one workspace. Two servers that both/// hear about one Claude Code session — the hook through one, the bus through/// the other — used to write two rows for it.pub fn session_id(tool: &str, external_id: &str) -> String {    derived_id("cotton_sessions", &[tool, external_id])}/// An OAuth refresh rotation's id — `(workspace, grant, generation)`/// (`crate::grant_rotations`). Two Macs that move one grant's chain to one/// generation write ONE fact id, so the fold sees the second as a second/// write of it rather than as another row.pub fn grant_rotation_id(namespace: &Namespace, grant_id: &str, generation: u32) -> String {    derived_id(        "cotton_grant_rotations",        &[namespace.as_str(), grant_id, &generation.to_string()],    )}/// A memory entry's id — `(workspace, slug)`, `idx_cotton_memories_slug`.pub fn memory_id(namespace: &Namespace, slug: &str) -> String {    derived_id("cotton_memories", &[namespace.as_str(), slug])}/// A document's id — `(workspace, sha256)`. The bytes ARE the key, and two/// devices that filed the same file were always meant to hold one row.pub fn document_id(namespace: &Namespace, sha256: &str) -> String {    derived_id("cotton_documents", &[namespace.as_str(), sha256])}/// A message contact's id — `(workspace, phone_e164)`.////// `phone_e164` must arrive as the column holds it: DIGITS ONLY, which the/// table's own CHECK insists on. A caller that passes `+91…` derives an id/// nothing else will find.pub fn msg_contact_id(namespace: &Namespace, phone_e164: &str) -> String {    cotton_rules::ids::msg_contact_id(namespace.as_str(), phone_e164)}/// A one-to-one thread's id — `(workspace, contact)`, `uq_cotton_msg_threads_dm`.pub fn dm_thread_id(namespace: &Namespace, contact_id: &str) -> String {    cotton_rules::ids::dm_thread_id(namespace.as_str(), contact_id)}/// A group thread's id — `(workspace, external key)`,/// `uq_cotton_msg_threads_group_key`.////// Its own prefix rather than the dm one's, because a group's external key and/// a contact id are different kinds of string in the same column position and/// one hash over both would let them collide.pub fn group_thread_id(namespace: &Namespace, external_key: &str) -> String {    cotton_rules::ids::group_thread_id(namespace.as_str(), external_key)}/// A contactless one-to-one thread's id — `(workspace, channel, the source's/// own conversation key)`. A site that names people by display name alone (an/// Instagram export) has no contact to derive [`dm_thread_id`] from, so its/// importer reserves this id and a re-run lands in the same thread.pub fn keyed_dm_thread_id(namespace: &Namespace, channel: &str, external_key: &str) -> String {    derived_id(        "cotton_msg_threads:keyed-dm",        &[namespace.as_str(), channel, external_key],    )}/// A materialized recurrence occurrence's id. `occurrence_at_iso` must be the/// exact string the column holds.pub fn recurrence_occurrence_id(recurrence_id: &str, occurrence_at_iso: &str) -> String {    derived_id(        "cotton_todos:occurrence",        &[recurrence_id, occurrence_at_iso],    )}/// A project link's id (schema v12). Derived from the natural key so any/// device — or the server over MCP — linking the same record to the same/// project converges on ONE row, and a re-link after an unlink is the same row/// returning rather than a sibling.pub fn project_link_id(project_id: &str, record_kind: &str, record_id: &str) -> String {    derived_id(        "cotton_project_links",        &[project_id, record_kind, record_id],    )}/// `cotton_msg_thread_filings`: one row per (chat, shared database). Derived,/// so a chat filed on the phone and by an assistant at the same moment is ONE/// filing, and filing again after an unfile is the same row returning.pub fn thread_filing_id(thread_id: &str, database_id: &str) -> String {    derived_id("cotton_msg_thread_filings", &[thread_id, database_id])}/// `cotton_msg_thread_marks`: one row per (shared database, filed chat) in a/// person's own file. Derived, so the phone and an assistant marking the same/// copy write ONE row, and its columns are each one last write.pub fn thread_marks_id(database_id: &str, thread_id: &str) -> String {    derived_id("cotton_msg_thread_marks", &[database_id, thread_id])}/// `cotton_push_acks`: one row per (device, push). Derived, so a phone that/// both shows a push and later finds it in its list writes ONE receipt.pub fn push_ack_id(device_id: &str, push_id: &str) -> String {    derived_id("cotton_push_acks", &[device_id, push_id])}/// `cotton_device_relay_keys`: one row per (device, serving epoch). Derived, so/// two serving Macs of the SAME epoch keeping a Mac's key write one row, and/// Macs of different epochs write different rows that every device keeps —/// the device's key is then the lowest epoch's, a pure function of the set.pub fn relay_key_id(device_id: &str, epoch: i64) -> String {    derived_id("cotton_device_relay_keys", &[device_id, &epoch.to_string()])}/// `cotton_audiences`: one row per record. Derived, so the owner marking a/// record on two devices at once writes ONE row, and the newer write wins.pub fn audience_id(record_table: &str, record_id: &str) -> String {    derived_id("cotton_audiences", &[record_table, record_id])}/// `cotton_device_keep`: one row per (device, kind, target). Derived, so the/// same rule set on the phone and by an assistant is ONE row whose `rule` is/// one last write, and a rule set again after it was cleared is the same row/// returning.pub fn device_keep_id(device_id: &str, kind: &str, target: &str) -> String {    derived_id("cotton_device_keep", &[device_id, kind, target])}/// A group's member row (137): one per (group, record).pub fn group_member_id(group_id: &str, record_id: &str) -> String {    derived_id("cotton_group_members", &[group_id, record_id])}/// A tool package's picture row (137): one per (tool, file name).pub fn tool_asset_id(tool_id: &str, name: &str) -> String {    derived_id("cotton_tool_assets", &[tool_id, name])}/// An email thread's id (schema v13) — the ingest caller's conversation key.pub fn email_thread_id(namespace: &Namespace, external_key: &str) -> String {    derived_id("cotton_email_threads", &[namespace.as_str(), external_key])}/// An email's id (schema v13) — its fingerprint (`fingerprint::email`).pub fn email_id(namespace: &Namespace, external_id: &str) -> String {    derived_id("cotton_emails", &[namespace.as_str(), external_id])}/// An email participant's id (schema v13).////// `email` must arrive LOWERCASED — the column's own CHECK says so, and this/// function does not lower it for you, exactly as the TypeScript does not: a/// caller that passes a mixed-case address derives an id nothing else will/// find, which is a bug in the caller and has to look like one.pub fn email_participant_id(thread_id: &str, email: &str) -> String {    derived_id("cotton_email_participants", &[thread_id, email])}/// A blocked sender's id (schema v33). Workspace plus the LOWERCASED address.pub fn blocked_sender_id(namespace: &Namespace, address: &str) -> String {    derived_id("cotton_blocked_senders", &[namespace.as_str(), address])}/// An email sender's id (schema v107). Workspace plus the LOWERCASED address,/// so every device that meets the address writes the same row.pub fn email_sender_id(namespace: &Namespace, address: &str) -> String {    derived_id("cotton_email_senders", &[namespace.as_str(), address])}/// An outage row's id (schema v120): the condition it keys on and the instant/// it started — so the Mac that opens it, asked again in the same round or/// after a restart, writes the same row, and the next time the same condition/// comes back is a row of its own.pub fn outage_id(namespace: &Namespace, condition: &str, started_at: &str) -> String {    derived_id("cotton_outages", &[namespace.as_str(), condition, started_at])}/// A record-to-record edge's id (`cotton_links`).////// DIRECTION MATTERS — an edge from a note to a person is not the edge back.pub fn record_link_id(from_kind: &str, from_id: &str, to_kind: &str, to_id: &str) -> String {    derived_id("cotton_links", &[from_kind, from_id, to_kind, to_id])}/// A record-to-record edge's id when the target may live in another database/// (`cotton_links.to_database`).////// `None` is this database, and derives exactly [`record_link_id`]'s id, so/// every link already minted keeps its id. A named database is mixed in last,/// so a link to one id in this database and to the same id in another are two/// rows. Called only by [`link_id_for`], which decides what `None` means.pub fn record_link_id_in(    from_kind: &str,    from_id: &str,    to_kind: &str,    to_id: &str,    to_database: Option<&str>,) -> String {    match to_database {        None => record_link_id(from_kind, from_id, to_kind, to_id),        Some(database) => derived_id("cotton_links", &[from_kind, from_id, to_kind, to_id, database]),    }}/// The ends of a `cotton_links` row, as [`link_id_for`] reads them.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct LinkRow<'a> {    pub from_kind: &'a str,    pub from_id: &'a str,    pub to_kind: &'a str,    pub to_id: &'a str,    pub to_database: Option<&'a str>,}/// THE id of a link row, in the database whose own file id is `own_database`.////// A `to_database` naming the file the row is written in is the same link as/// one naming none — `mint` stores it as NULL — so it derives the same id. The/// file's id is asked for rather than guessed, because the same row read in/// two files means two different things.pub fn link_id_for(row: &LinkRow<'_>, own_database: &FileId) -> String {    let to_database = row        .to_database        .filter(|database| *database != own_database.as_str());    record_link_id_in(row.from_kind, row.from_id, row.to_kind, row.to_id, to_database)}/// A photo's id (schema v31) — `photo:<sha256>`, which the file's own CHECK/// insists on.////// The odd ones out in this module: NOT a hash of a natural key, but the/// content hash itself under a prefix. The hash is already the natural key, so/// hashing it again would only make it unreadable. The prefix is what keeps a/// photo and a video of the same bytes two records rather than one id/// colliding across both.pub fn photo_record_id(sha256: &str) -> String {    format!("photo:{sha256}")}/// A video's id (schema v31) — `video:<sha256>`.pub fn video_record_id(sha256: &str) -> String {    format!("video:{sha256}")}/// A contact handle's id (schema v36). `value` must arrive NORMALISED: digits/// for a phone, lower-cased for an email, exactly what the column's own CHECKs/// insist on.pub fn contact_handle_id(namespace: &Namespace, kind: &str, value: &str) -> String {    cotton_rules::ids::contact_handle_id(namespace.as_str(), kind, value)}/// A message contact reached ONLY by a social handle (schema v90): an/// Instagram, Facebook or LinkedIn sender has no phone, so its contact is/// derived from the handle itself — `value` NORMALISED — and two reads of the/// same sender are one contact.pub fn msg_contact_handle_id(namespace: &Namespace, kind: &str, value: &str) -> String {    cotton_rules::ids::msg_contact_handle_id(namespace.as_str(), kind, value)}/// A person handle's id (schema v90) — `(workspace, kind, normalised)`, the/// table's own unique key, so two devices adding the same handle converge.pub fn person_handle_id(namespace: &Namespace, kind: &str, normalised: &str) -> String {    derived_id("cotton_person_handles", &[namespace.as_str(), kind, normalised])}/// A call log entry's id (schema v36) — `(workspace, source, external id)`,/// which is what makes a re-read of the phone's call history free.pub fn call_log_id(namespace: &Namespace, source: &str, external_id: &str) -> String {    derived_id("cotton_call_log", &[namespace.as_str(), source, external_id])}/// A post's id (schema v86) — `(workspace, source, account, external id)`,/// `uq_cotton_posts_external`, so a re-read of the same export or feed is free.pub fn post_id(namespace: &Namespace, source: &str, account: &str, external_id: &str) -> String {    derived_id(        "cotton_posts",        &[namespace.as_str(), source, account, external_id],    )}/// A story's id (schema 88): one per post per source app, whichever account saw it.pub fn story_id(namespace: &Namespace, source: &str, external_id: &str) -> String {    derived_id("cotton_stories", &[namespace.as_str(), source, external_id])}/// A media sighting's id (schema v39) — where a photo or a video was seen.////// A share-sheet sighting names no source id at all, so NULL is spelled as the/// empty string here and as `ifnull(source_id, '')` in the table's unique/// index — the two agree by construction.pub fn media_sighting_id(    record_kind: &str,    record_id: &str,    source: &str,    source_id: Option<&str>,) -> String {    derived_id(        "cotton_media_sightings",        &[record_kind, record_id, source, source_id.unwrap_or("")],    )}/// A detected face's id (schema v39) — the source's own face key under the/// record it was found on.pub fn media_face_id(record_kind: &str, record_id: &str, source: &str, source_id: &str) -> String {    derived_id(        "cotton_media_faces",        &[record_kind, record_id, source, source_id],    )}/// A near-duplicate proposal's id (schema v40), keyed on the ORDERED pair.pub fn media_duplicate_id(keep_id: &str, copy_id: &str) -> String {    derived_id("cotton_media_duplicates", &[keep_id, copy_id])}/// A suggested album's id (schema v42): `album:<kind>:<anchor>`, where the/// anchor is the cluster's first local HOUR for an event (`2026-03-14T09`) and/// its first local DAY for a trip (`2026-03-14`). Readable on purpose.pub fn media_album_id(kind: &str, anchor: &str) -> String {    format!("album:{kind}:{anchor}")}/// An album member's id (schema v42): the (album, record) pair.pub fn media_album_item_id(album_id: &str, record_id: &str) -> String {    derived_id("cotton_media_album_items", &[album_id, record_id])}#[cfg(test)]#[path = "derived_id_tests.rs"]mod tests;