//! The link rule (design 5.3): **a record in the personal database may point//! into a project's database; a record in a project's database never points//! into the personal one.**//!//! A file's kind is its own `cotton_workspaces` row's `kind` — the row whose id//! is `_meta.workspace_id`. The personal database ("Mine") is `personal`;//! every project's database is `shared` from birth. The rule is asked by the fold for every write this file//! mints ([`crate::fold::Arrival::Local`]) and every write a device hands it//! ([`crate::fold::Arrival::Handed`]), so `mint` and a device's push meet the//! same check, and a crossing push is parked with the reason.//!//! What it refuses://!//! - a `cotton_links` row naming another file (`to_database`) in any file//! that is not Mine — only Mine may point into another file;//! - a `cotton_links` row naming THIS file as `to_database`: that is written//! as null (`mint` nulls it before the fold, and//! [`crate::protocol::derived_id::link_id_for`] derives the same id), so//! only a device that skipped `mint` sends one;//! - in a shared database, any of the four forms naming a Mine-bound record: a link//! whose `from_kind` or `to_kind` is on [`MINE_BOUND_LINK_KINDS`], a soft//! column whose parent is a Mine-bound table, a project link whose//! `record_kind` is on [`MINE_BOUND_PROJECT_LINK_KINDS`], and a set database column of a soft pair//! (`todo_database`, `event_database`) — a shared database names nothing outside//! itself;//! - in a shared database, a row of the Messages tables that a filing did not//! write ([`ONLY_A_FILING`]): a chat is in a shared database because its//! owner filed it there, and nothing else puts one there;//! - in a shared database, a reader's own marks on a filed chat//! ([`MARKS_ARE_PERSONAL`]): where one person keeps a filed chat (pinned,//! muted, archived, cleared) is a row in THEIR personal database, and the//! shared one holds only the filing.//!//! Whether a `to_database` names a database of the same owner needs the//! server's registry, which the store does not hold; the tools' door refuses//! an id outside the token's reach until then.use rusqlite::types::ValueasSqlValue;usecrate::driver::Driver;usecrate::error::{Result, StoreError};usecrate::protocol::types::{CottonOp, OpKind};usecrate::schema::table_specs::{SOFT_REFS, SOFT_REF_DATABASES};/// What a file is, from its own workspace row.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumFileKind {/// Mine — the owner's own personal database.Personal,/// A project's database, which may be shared with other people; it names/// nothing outside itself.Shared,/// No workspace row yet, or one written before kinds (a raw fixture).Unset,}/// The file a write lands in: its own id (`_meta.workspace_id`, `None` before/// the file has a `_meta` row) and its kind. Read once per folded batch.#[derive(Debug, Clone, PartialEq, Eq)]pubstructThisFile {pub id: Option<String>,pub kind: FileKind,}/// Ordinary tools, including Money, may link to records in their own database./// Cross-database links remain forbidden in a shared database.pubconst MINE_BOUND_LINK_KINDS: [&str; 0] = [];/// Personal imports may be referred to by project links only in Personal.pubconst MINE_BOUND_PROJECT_LINK_KINDS: [&str; 4] = ["thread", "email_thread", "journal", "call"];/// Personal parents that a shared database's soft columns may not name./// Money belongs to the database where its statement was filed.pubconst MINE_BOUND_TABLES: [&str; 8] = ["cotton_emails","cotton_email_threads","cotton_email_participants","cotton_call_log","cotton_moods","cotton_sessions","cotton_session_messages","cotton_mcp_tokens",];/// The Messages tables, in the order their foreign keys ask for: a contact,/// its handles, the chat, its seats, its messages. The personal database/// holds every chat — ingest and the owner write them there. A shared/// database holds ONLY the chats its owner filed in it, so in a shared file/// these are written by a filing and by nothing else.pubconst FILED_CHAT_TABLES: [&str; 5] = ["cotton_msg_contacts","cotton_msg_contact_handles","cotton_msg_threads","cotton_msg_thread_participants","cotton_msg_messages",];/// Where one READER keeps a chat filed in a shared database — pinned, muted,/// archived, cleared: a row of their PERSONAL database, one per (shared/// database, chat), synced to their own devices and nobody else's (architect,/// 12 Oct 2026). A shared database holds only the filing, so this table takes/// no row there from anybody, a filing included.pubconst THREAD_MARKS_TABLE: &str = "cotton_msg_thread_marks";/// A phone's receipt for a push (`cotton_push_acks`, v126): about the/// person's own devices, so a row of their PERSONAL database only.pubconst PUSH_ACKS_TABLE: &str = "cotton_push_acks";/// A Mac's kept relay key (`cotton_device_relay_keys`, v136): the relay/// roster is the household's, so a row of the PERSONAL database only.pubconst DEVICE_RELAY_KEYS_TABLE: &str = "cotton_device_relay_keys";/// The reason a kept relay key is refused in a shared database.pubconst RELAY_KEYS_ARE_PERSONAL: &str ="a Mac's relay key is kept in the household's personal database, never in a shared one";/// The reason a push receipt is refused in a shared database.pubconst ACKS_ARE_PERSONAL: &str ="a phone's receipt for a push lives in its owner's personal database, never in a shared one";/// The reason a reader's mark row is refused in a shared database.pubconst MARKS_ARE_PERSONAL: &str ="a reader's own marks on a filed chat live in their personal database, never in a shared one";/// The actor a filing writes as: the serving Mac's own `filing` job, the/// copier that carries a filed chat out of the personal database.pubconst FILING_ACTOR: &str = "job:filing";/// A serving connector with a proved, owner-filed chat home. Device jobs/// cannot acquire this actor by sending an op to the serving Mac.pubconst FILED_CHAT_IMPORT_ACTOR: &str = "job:filed-chat-import";/// The reason a Messages row no filing wrote is refused in a shared database.pubconst ONLY_A_FILING: &str = "a shared database's Messages hold only the chats filed there";/// The reason a crossing write is refused and parked.pubconst INTO_MINE: &str = "a record in a shared database cannot point into the personal database";/// This file's id and kind.pubfn this_file(db: &Driver) -> Result<ThisFile> {let id = db .get("SELECT workspace_id FROM _meta", &[])? .and_then(|row| row.text("workspace_id").map(str::to_string)) .filter(|id| !id.is_empty());letSome(id) = id else {returnOk(ThisFile { id: None, kind: FileKind::Unset }); };let kind = db .get("SELECT kind FROM cotton_workspaces WHERE id = ?", &[SqlValue::Text(id.clone())], )? .and_then(|row| row.text("kind").map(str::to_string));let kind = match kind.as_deref() {None => FileKind::Unset,Some("personal") => FileKind::Personal,Some("shared") => FileKind::Shared,Some(other) => {returnErr(StoreError::refused(format!("cotton_workspaces {id} has kind {other:?}, which the file's own CHECK does not allow" ))) } };Ok(ThisFile { id: Some(id), kind })}/// This file's kind — [`this_file`]'s second half.pubfn file_kind(db: &Driver) -> Result<FileKind> {Ok(this_file(db)?.kind)}fn text<'a>(columns: &'a [(String, SqlValue)], name: &str) -> Option<&'a str> { columns.iter().find(|(column, _)| column == name).and_then(|(_, value)| match value {SqlValue::Text(text) => Some(text.as_str()), _ => None, })}fn is_set(columns: &[(String, SqlValue)], name: &str) -> bool { columns .iter() .any(|(column, value)| column == name && !matches!(value, SqlValue::Null))}fn mine_bound_kind(kind: &str) -> bool { MINE_BOUND_LINK_KINDS.contains(&kind)}fn mine_bound_project_link_kind(kind: &str) -> bool { MINE_BOUND_PROJECT_LINK_KINDS.contains(&kind)}fn mine_bound_table(table: &str) -> bool { MINE_BOUND_TABLES.contains(&table)}/// The same link rule reads protocol writes and audited rows; an audit never/// invents receipt, author, signature or clock metadata to ask it.structLinkWrite<'a> { kind: OpKind, table: &'a str, row_id: &'a str, actor: &'a str, patch: Option<&'a serde_json::Map<String, serde_json::Value>>,}impl<'a> From<&'a CottonOp> forLinkWrite<'a> {fn from(op: &'a CottonOp) -> Self {Self { kind: op.kind, table: &op.table, row_id: &op.row_id, actor: &op.actor, patch: op.patch.as_ref() } }}/// The rule, asked of one upsert: `None` is "nothing to say", `Some(reason)`/// the refusal. `encoded` is the op's patch as the fold encoded it.pubfn check( file: &ThisFile, op: &CottonOp, encoded: Option<&[(String, SqlValue)]>,) -> Option<String> { check_fields(file, &LinkWrite::from(op), encoded)}fn check_fields(file: &ThisFile, op: &LinkWrite<'_>, encoded: Option<&[(String, SqlValue)]>) -> Option<String> {if op.kind != OpKind::Upsert {returnNone; }let columns = encoded?;if matches!(op.table, "cotton_arrivals" | "cotton_filing_proposals") && file.kind != FileKind::Personal {returnSome("Arrivals and the owner's proposals stay in Personal.".into()); }if op.table == "cotton_links" {ifletSome(database) = text(columns, "to_database") {if file.id.as_deref() == Some(database) {returnSome(format!("cotton_links {} names this file as to_database; a link into its own file is written with none", op.row_id )); }if file.kind != FileKind::Personal {returnSome(format!("cotton_links {} names another database; only Mine may point into another file", op.row_id )); } } }ifletSome(reason) = media_key_outside_prefix(file, op) {returnSome(reason); }if file.kind != FileKind::Shared {returnNone; }if op.table == "cotton_usage" {returnSome("usage is kept only in the person's personal database, never in a shared one".into()); }if op.table == THREAD_MARKS_TABLE {returnSome(format!("{MARKS_ARE_PERSONAL}: {} {}", op.table, op.row_id)); }if op.table == PUSH_ACKS_TABLE {returnSome(format!("{ACKS_ARE_PERSONAL}: {} {}", op.table, op.row_id)); }if op.table == DEVICE_RELAY_KEYS_TABLE {returnSome(format!("{RELAY_KEYS_ARE_PERSONAL}: {} {}", op.table, op.row_id)); }ifletSome(reason) = not_a_filing(op, columns) {returnSome(reason); }let crossing = match op.table {"cotton_links" => ["from_kind", "to_kind"] .iter() .any(|column| text(columns, column).is_some_and(mine_bound_kind)),"cotton_project_links" => { text(columns, "record_kind").is_some_and(mine_bound_project_link_kind) } _ => false, } || SOFT_REFS.iter().any(|(child, column, parent)| { *child == op.table && mine_bound_table(parent) && is_set(columns, column) }) || SOFT_REF_DATABASES .iter() .any(|(child, _, database)| *child == op.table && is_set(columns, database)); crossing.then(|| format!("{INTO_MINE}: {} {}", op.table, op.row_id))}/// A move may carry its existing references and media keys into its new/// home. The immutable move fact is the narrow exception to the creation/// rule; it confers no read grant on the old database.pubfn check_on(db: &Driver, file: &ThisFile, op: &CottonOp, encoded: Option<&[(String, SqlValue)]>) -> Result<Option<String>> { check_fields_on(db, file, &LinkWrite::from(op), encoded)}fn check_fields_on(db: &Driver, file: &ThisFile, op: &LinkWrite<'_>, encoded: Option<&[(String, SqlValue)]>) -> Result<Option<String>> {if op.kind == OpKind::Upsert {letmut moved = db.get("SELECT c.after FROM cotton_changes c WHERE c.table_id = ? AND c.record_id = ? AND c.verb = 'move' AND NOT EXISTS(SELECT 1 FROM cotton_undos u WHERE u.change_id = c.id) AND NOT EXISTS(SELECT 1 FROM cotton_changes back WHERE back.verb='move_in' AND back.table_id=c.table_id AND back.record_id=c.record_id AND back._hlc > c._hlc AND json_extract(back.after,'$.to')=?) ORDER BY c._hlc DESC LIMIT 1", &[SqlValue::Text(op.table.to_owned()),SqlValue::Text(op.row_id.to_owned()),SqlValue::Text(file.id.clone().unwrap_or_default())])?;if moved.is_none() && db.get("SELECT 1 FROM _tombstones WHERE tbl = ? AND row_id = ?", &[SqlValue::Text(op.table.to_owned()),SqlValue::Text(op.row_id.to_owned())])?.is_some() { moved = db.get("SELECT c.after FROM cotton_changes c WHERE c.verb = 'move' AND NOT EXISTS(SELECT 1 FROM cotton_undos u WHERE u.change_id = c.id) AND NOT EXISTS(SELECT 1 FROM cotton_changes back WHERE back.verb='move_in' AND back.table_id=c.table_id AND back.record_id=c.record_id AND back._hlc > c._hlc AND json_extract(back.after,'$.to')=?) AND EXISTS(SELECT 1 FROM json_each(c.before,'$.related') r WHERE json_extract(r.value,'$.table') = ? AND json_extract(r.value,'$.id') = ? AND coalesce(json_extract(r.value,'$.reference_only'),0) = 0) ORDER BY c._hlc DESC LIMIT 1", &[SqlValue::Text(file.id.clone().unwrap_or_default()),SqlValue::Text(op.table.to_owned()),SqlValue::Text(op.row_id.to_owned())])?; }ifletSome(moved) = moved {let metadata: serde_json::Value = serde_json::from_str(moved.text("after").unwrap_or("null")).map_err(StoreError::encode)?;returnOk(Some(format!("record moved to {}; it cannot be changed in its old database",metadata["to_name"].as_str().unwrap_or("another database")))); } }let refusal = check_fields(file, op, encoded);if refusal.is_none() || matches!(op.table, "cotton_usage" | THREAD_MARKS_TABLE | PUSH_ACKS_TABLE | DEVICE_RELAY_KEYS_TABLE) {returnOk(refusal); }letSome(columns) = encoded else { returnOk(refusal); };for row in db.all("SELECT table_id,record_id,before,after,verb FROM cotton_changes WHERE verb IN ('move','move_in')", &[])? {let before: serde_json::Value = serde_json::from_str(row.text("before").unwrap_or("null")).map_err(StoreError::encode)?;let after: serde_json::Value = serde_json::from_str(row.text("after").unwrap_or("null")).map_err(StoreError::encode)?;if row.text("verb") == Some("move") && op.table == "cotton_links" {ifletSome(incoming) = before["incoming_links"].as_array() {for link in incoming {if link[0].as_str() == Some(op.row_id) && carried_columns(op.table, columns, &link[1], after["to"].as_str())? {returnOk(None); } } } }if row.text("verb") != Some("move_in") { continue; }if row.text("table_id") == Some(op.table) && row.text("record_id") == Some(op.row_id) && carried_columns(op.table, columns, &before, None)? { returnOk(None); }ifletSome(related) = before["related"].as_array() {for related in related {if related["table"].as_str() == Some(op.table) && related["id"].as_str() == Some(op.row_id) {let fields = &related["fields"];let target_moved = fields["to_database"].is_null() && after["moving_ids"].as_array().is_some_and(|ids| ids.iter().any(|id| *id == fields["to_id"]));let target = if target_moved { None } else { fields["to_database"].as_str().or(after["from"].as_str()).filter(|database| file.id.as_deref() != Some(*database)) };if carried_columns(op.table, columns, fields, target)? { returnOk(None); } } } } }Ok(refusal)}fn carried_columns(table: &str, columns: &[(String, SqlValue)], original: &serde_json::Value, link_database: Option<&str>) -> Result<bool> {letSome(spec) = crate::schema::specs::spec_for(table) else { returnOk(false); };let identity: &[&str] = if table == "cotton_links" { &["from_kind","from_id","to_kind","to_id","to_database"] } else { &[] };for (column, value) in columns {let restricted = identity.contains(&column.as_str()) || SOFT_REFS.iter().any(|(child, field, parent)| *child == table && *field == column && mine_bound_table(parent)) || SOFT_REF_DATABASES.iter().any(|(child, _, field)| *child == table && *field == column) || crate::media_keys::MEDIA_KEY_HOLDERS.iter().any(|(holder,field,_)| *holder == table && *field == column);if !restricted || matches!(column.as_str(), "id" | "workspace_id" | "_hlc" | "_born") { continue; }let expected = if column == "to_database" { link_database.map(serde_json::Value::from).unwrap_or(serde_json::Value::Null) } else { original[column].clone() };letSome((_,codec)) = spec.columns.iter().find(|(field,_)| *field == column) else { returnOk(false); };ifcrate::schema::codecs::decode_value(*codec,value)? != expected { returnOk(false); } }Ok(true)}/// In a shared database, a write to one of [`FILED_CHAT_TABLES`] that is not a/// filing's: an incoming message an ingest would put there, a chat a device/// made there, an edit of a filed message. A filing is the owner's own act on/// one chat, checked against that database's people; a row arriving any other/// way would be a chat nobody filed, in front of everybody in the database.////// One write is not a filing's and is let through, the database's own to/// say and naming nothing outside the file: WHO a contact is among this/// database's people (`person_id` — merging two of its people repoints the/// contact). Where a reader keeps the copy (pinned, muted, archived,/// cleared) is not the copy's: it is that reader's row in their personal/// database ([`THREAD_MARKS_TABLE`]), so a patch of the copy naming only/// those is refused like any other.////// The actor is the op's own word, as every job's is; a device forging a job/// on arrival is the arrival fence's to refuse, not this rule's.fn not_a_filing(op: &LinkWrite<'_>, columns: &[(String, SqlValue)]) -> Option<String> {if !FILED_CHAT_TABLES.contains(&op.table) || op.actor == FILING_ACTOR || op.actor == FILED_CHAT_IMPORT_ACTOR {returnNone; }// (`workspace_id` is the file's own id, which a writer stamps on every row.)let who_only = op.table == "cotton_msg_contacts" && columns.iter().all(|(column, _)| matches!(column.as_str(), "person_id" | "updated_at" | "workspace_id"));if who_only {returnNone; }Some(format!("{ONLY_A_FILING}: {} {} was not written by a filing", op.table, op.row_id))}/// The reason a row naming another file's bytes is refused and parked.pubconst MEDIA_OUTSIDE_PREFIX: &str = "a record names a media key outside its own database's prefix";/// A media key in the op's patch that does not sit under this file's own/// `{file id}/` prefix (design 5.3, P11b): every database's bytes live under/// its own id, and a row naming another's would let an erasure, a quota or a/// leave here reach bytes that are not this database's. A file with no id yet/// (a raw fixture before `_meta`) has no prefix to hold a key to.fn media_key_outside_prefix(file: &ThisFile, op: &LinkWrite<'_>) -> Option<String> {let id = file.id.as_deref()?;if !crate::media_keys::is_holder_table(op.table) {returnNone; }let patch = op.patch.as_ref()?;crate::media_keys::keys_in_fields(op.table, |column| patch.get(column)) .into_iter() .find(|key| key.strip_prefix(id).and_then(|rest| rest.strip_prefix('/')).is_none_or(str::is_empty)) .map(|key| format!("{MEDIA_OUTSIDE_PREFIX}: {} {} names {key:?}", op.table, op.row_id))}/// A row the audit found pointing where the rule says it may not.#[derive(Debug, Clone, PartialEq, Eq)]pubstructCrossing {pub table: String,pub row_id: String,pub reason: String,}/// The audit: every row in this file that breaks the link rule, in the same/// four forms [`check`] refuses one write in — a `cotton_links` row naming/// another database (or this one), a Mine-bound link kind, a Mine-bound soft/// column, a Mine-bound project link, and a set database column of a soft/// pair. Rows get past the fold only by raw SQL or by a rule that changed/// after they landed, so the daily run lists them for the owner rather than/// deleting them.pubfn crossing_links(db: &Driver) -> Result<Vec<Crossing>> {let file = this_file(db)?;letmut out = Vec::new();let push = |out: &mutVec<Crossing>, table: &str, row_id: &str, reason: String| { out.push(Crossing { table: table.to_string(), row_id: row_id.to_string(), reason, }) };for row in db.all("SELECT id, to_database FROM cotton_links WHERE to_database IS NOT NULL ORDER BY id", &[], )? {let id = row.text("id").unwrap_or_default();let database = row.text("to_database").unwrap_or_default();if file.id.as_deref() == Some(database) { push(&mut out, "cotton_links", id, format!("cotton_links {id} names this file as to_database; a link into its own file is written with none" )); } elseif file.kind != FileKind::Personal { push(&mut out, "cotton_links", id, format!("cotton_links {id} names another database; only Mine may point into another file" )); } }if file.kind != FileKind::Shared {returnOk(out); }for row in db.all("SELECT id, from_kind, to_kind FROM cotton_links ORDER BY id", &[], )? {let id = row.text("id").unwrap_or_default();let crossing = [row.text("from_kind"), row.text("to_kind")] .iter() .any(|kind| kind.is_some_and(mine_bound_kind));if crossing { push(&mut out, "cotton_links", id, format!("{INTO_MINE}: cotton_links {id}")); } }for row in db.all("SELECT id, record_kind FROM cotton_project_links ORDER BY id", &[], )? {let id = row.text("id").unwrap_or_default();if row.text("record_kind").is_some_and(mine_bound_project_link_kind) { push(&mut out, "cotton_project_links", id, format!("{INTO_MINE}: cotton_project_links {id}" )); } }let soft_columns = SOFT_REFS .iter() .filter(|(_, _, parent)| mine_bound_table(parent)) .map(|(child, column, _)| (*child, *column)) .chain(SOFT_REF_DATABASES.iter().map(|(child, _, database)| (*child, *database)));for (table, column) in soft_columns {for row in db.all( &format!("SELECT id FROM {table} WHERE {column} IS NOT NULL AND {column} != '' ORDER BY id" ), &[], )? {let id = row.text("id").unwrap_or_default(); push(&mut out, table, id, format!("{INTO_MINE}: {table} {id} ({column})")); } }letmut kept = Vec::new();for crossing in out {letSome(spec) = crate::schema::package_shape::spec_on(db,&crossing.table)? else { kept.push(crossing); continue; };let row = db.get(&format!("SELECT * FROM {} WHERE id = ?",format!("\"{}\"",crossing.table.replace('"',"\"\""))), &[SqlValue::Text(crossing.row_id.clone())])?;letSome(row) = row else { continue; };let patch = crate::schema::codecs::decode_row(spec.columns, row.columns())?;let fields = LinkWrite { kind: OpKind::Upsert, table: &crossing.table, row_id: &crossing.row_id, actor: "", patch: Some(&patch) };if check_fields_on(db, &file, &fields, Some(row.columns()))?.is_some() { kept.push(crossing); } }Ok(kept)}/// A file's identity is set when its workspace row is made and never changed/// after: `kind`, `namespace` and `owner_user_id`. A patch naming any of them/// with another value than the row holds — a null becoming a value included —/// is refused. A patch restating the same value says nothing.pubfn no_identity_change( db: &Driver, op: &CottonOp, encoded: Option<&[(String, SqlValue)]>,) -> Result<Option<String>> {const IDENTITY: [&str; 3] = ["kind", "namespace", "owner_user_id"];if op.table != "cotton_workspaces" || op.kind != OpKind::Upsert {returnOk(None); }letSome(columns) = encoded else {returnOk(None); };if !columns.iter().any(|(column, _)| IDENTITY.contains(&column.as_str())) {returnOk(None); }letSome(row) = db.get("SELECT kind, namespace, owner_user_id FROM cotton_workspaces WHERE id = ?", &[SqlValue::Text(op.row_id.clone())], )?else {returnOk(None); };for name in IDENTITY {letSome((_, incoming)) = columns.iter().find(|(column, _)| column == name) else {continue; };let held = row.text(name).map(|text| SqlValue::Text(text.to_string()));let held = held.unwrap_or(SqlValue::Null);if *incoming != held {returnOk(Some(format!("cotton_workspaces {}: {name} is set when the file is made and never changed", op.row_id ))); } }Ok(None)}#[cfg(test)]#[path = "link_rule_tests.rs"]mod tests;