//! Cross-file record moves. //! //! A move is deliberately a snapshot-and-retract operation: the destination //! receives the source rows under their existing ids, while the source keeps a //! `cotton_changes` `move` fact with the complete before image and the named //! destination. The history fact is the tombstone; adding a column would make //! every reader and every older file learn a second representation of it. use std::collections::{BTreeSet, VecDeque}; use cotton_core::records::moves::{self, MoveRequest, RecordKey, RelatedSnapshot, Snapshot}; use cotton_core::{constants::BinKind, rules::bin::bin_source}; use cotton_store::StoreError; use cotton_store::driver::Driver; use cotton_store::schema::codecs::decode_row; use cotton_store::schema::package_shape::spec_on; use cotton_store::schema::table_specs::OWNING_REFS; use cotton_store::schema::versioned::VERSIONED_TABLES; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value, json}; use super::dispatch::{Ctx, ToolResult}; use super::protocol::ToolFailure; use super::writer::Retract; /// Read the newest move tombstone for a record id. /// /// `after` is intentionally returned as data rather than prose: cards decide /// how to say “moved to …”, and the history remains useful to undo and to an /// audit reader without a parallel tombstone shape. pub fn lookup_moved(db: &Driver, id: &str) -> cotton_store::Result> { lookup_moved_in(db, None, id) } pub fn lookup_moved_table(db: &Driver, table: &str, id: &str) -> cotton_store::Result> { lookup_moved_in(db, Some(table), id) } fn lookup_moved_in(db: &Driver, table: Option<&str>, id: &str) -> cotton_store::Result> { let Some(row) = db.get( "SELECT c.table_id, c.after FROM cotton_changes c WHERE c.record_id = ? AND (? IS NULL OR c.table_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 live WHERE live.record_id = c.record_id AND live.verb != 'move' AND live._hlc > c._hlc) ORDER BY c._hlc DESC, c.id DESC LIMIT 1", &[SqlValue::Text(id.to_owned()), table.map_or(SqlValue::Null, |t|SqlValue::Text(t.into())), table.map_or(SqlValue::Null, |t|SqlValue::Text(t.into()))], )? else { return Ok(None); }; if let Some(table) = row.text("table_id") { if spec_on(db, table)?.is_some() && db .get( &format!("SELECT 1 FROM {} WHERE id = ?", quote_ident(table)), &[SqlValue::Text(id.to_owned())], )? .is_some() { return Ok(None); } } let mut metadata: Value = serde_json::from_str(row.text("after").unwrap_or("null")).map_err(StoreError::encode)?; metadata["moved"] = json!(true); metadata["id"] = json!(id); Ok(Some(metadata)) } /// Validate and queue a whole move without committing either writer. /// /// The durable cross-file coordinator uses this seam to prepare both sets of /// receipts before it records its own commit decision. Ordinary callers use /// [`move_batch`], which commits the queued set under the two SQLite guards. pub fn queue_batch( source: &mut Ctx<'_>, dest: &mut Ctx<'_>, ids: &[String], to_name: &str, ) -> ToolResult { queue_transfer(source, dest, ids, to_name, MoveIntent::OwnerAct) } /// Append a repeat imported thread to its proven filing home. Call inside /// `prepare_contexts` under the same pair lock and durable journal as a move. /// The existing root and existing children are never overwritten; conflicting /// child identities refuse the entire arrival. This is not ordinary Move Undo: /// returning the thread uses a fresh move of its complete current contents. pub fn queue_arrival( source: &mut Ctx<'_>, dest: &mut Ctx<'_>, id: &str, to_name: &str, ) -> ToolResult { queue_transfer(source, dest, &[id.to_owned()], to_name, MoveIntent::Arrival) } /// Return only records whose recorded origin is the destination Personal file. /// This is the departure path, not authority to file a new chat or photo. pub fn queue_return(source: &mut Ctx<'_>, dest: &mut Ctx<'_>, ids: &[String], to_name: &str) -> ToolResult { queue_transfer(source, dest, ids, to_name, MoveIntent::Return) } #[derive(Clone, Copy, PartialEq, Eq)] enum MoveIntent { OwnerAct, Arrival, Return } fn requires_owner(table: &str) -> bool { matches!(table, "cotton_msg_threads" | "cotton_photos" | "cotton_videos" | "cotton_media_albums") } fn owner_act(source: &Ctx<'_>) -> Result<(), ToolFailure> { if source.writer_actor().is_some_and(|actor| actor.is_owner()) { return Ok(()); } Err(ToolFailure::new("Filing a chat or photo needs the owner's confirmation on the phone. Propose the batch for approval.")) } fn queue_transfer( source: &mut Ctx<'_>, dest: &mut Ctx<'_>, ids: &[String], to_name: &str, intent: MoveIntent, ) -> ToolResult { let snapshots = collect_snapshots(source.db(), ids)?; if snapshots.iter().any(|s| s.table == "cotton_msg_messages") { return Err(ToolFailure::new("File the whole chat, not an individual message.")); } let arrival = intent == MoveIntent::Arrival; if intent == MoveIntent::OwnerAct && snapshots.iter().any(|s| requires_owner(&s.table)) { owner_act(source)?; } if intent == MoveIntent::Return { if cotton_store::link_rule::file_kind(dest.db()).map_err(store_failure)? != cotton_store::link_rule::FileKind::Personal { return Err(ToolFailure::new("A departure returns records to their Personal origin.")); } for snapshot in &snapshots { let prior = source.db().get("SELECT after FROM cotton_changes WHERE table_id=? AND record_id=? AND verb='move_in' ORDER BY created_at,id LIMIT 1", &[SqlValue::Text(snapshot.table.clone()),SqlValue::Text(snapshot.id.clone())]).map_err(store_failure)?; let origin: Value = prior.and_then(|row|row.text("after").map(str::to_owned)).and_then(|s|serde_json::from_str(&s).ok()).unwrap_or(Value::Null); if origin["origin"]["database"] != dest.workspace_id { return Err(ToolFailure::new("A departure can return only records moved from this Personal database.")); } } } if cotton_store::link_rule::file_kind(dest.db()).map_err(store_failure)? == cotton_store::link_rule::FileKind::Shared { for snapshot in &snapshots { if snapshot.table == "cotton_msg_threads" { if let Some(reason) = crate::messages::admission::refusal(source.db(), source.workspace_id, dest.db(), dest.workspace_id, &snapshot.id).map_err(store_failure)? { return Err(ToolFailure::new(reason)); } } } } let mut destination = destination_keys(dest.db(), &snapshots)?; if arrival { for snapshot in &snapshots { if !matches!( snapshot.table.as_str(), "cotton_msg_threads" | "cotton_email_threads" ) { return Err(ToolFailure::new("repeat arrival needs an imported thread")); } let prior = dest.db().get("SELECT after FROM cotton_changes WHERE table_id = ? AND record_id = ? AND verb = 'move_in' ORDER BY created_at DESC,id DESC LIMIT 1", &[SqlValue::Text(snapshot.table.clone()),SqlValue::Text(snapshot.id.clone())]).map_err(store_failure)?; let proof: Value = prior .and_then(|r| r.text("after").map(str::to_owned)) .and_then(|v| serde_json::from_str(&v).ok()) .unwrap_or(Value::Null); if proof["from"] != source.workspace_id || read_row(dest.db(), &snapshot.table, &snapshot.id)?.is_none() { return Err(ToolFailure::new( "repeat arrival has no existing filing from this source", )); } let existing = read_row(dest.db(), &snapshot.table, &snapshot.id)?.unwrap(); for (child, column, _) in OWNING_REFS { if *child == snapshot.table && snapshot.fields.get(*column) != existing.get(*column) { return Err(ToolFailure::new( "repeat arrival changed its thread identity", )); } } destination.remove(&snapshot.key()); for related in &snapshot.related { if let Some(live) = read_row(dest.db(), &related.table, &related.id)? { if !related.reference_only { ensure_same_snapshot(&related.table, &related.fields, &live)?; } destination.remove(&related.key()); } } } } let plan = moves::plan(MoveRequest { from: source.workspace_id.to_owned(), to: dest.workspace_id.to_owned(), snapshots, destination, moved_at: crate::clock::iso(source.now), moved_by: source.agent.to_owned(), }) .map_err(|error| ToolFailure::new(error.to_string()))?; let moving_ids: BTreeSet = plan .destination .iter() .flat_map(|root| { std::iter::once(root.id.clone()).chain( root.related .iter() .filter(|row| !row.reference_only) .map(|row| row.id.clone()), ) }) .collect(); let moving_keys: BTreeSet = plan .destination .iter() .flat_map(|root| { std::iter::once(root.key()).chain( root.related .iter() .filter(|row| !row.reference_only) .map(RelatedSnapshot::key), ) }) .collect(); // One named history fact is the old home's tombstone. Related rows travel // too, but only roots need an answer for a reader following their old id. let mut change_ids = Vec::with_capacity(plan.destination.len()); for (snapshot, tombstone) in plan.destination.iter().zip(&plan.source_tombstones) { let mut before = snapshot.fields.clone(); let related: Vec = snapshot .related .iter() .map(|row| json!({"table": row.table, "id": row.id, "fields": row.fields, "reference_only":row.reference_only})) .collect(); before.insert("related".to_owned(), Value::Array(related)); let incoming: Vec<_> = rows_by_sql( source.db(), "cotton_links", "to_id = ?", &[SqlValue::Text(snapshot.id.clone())], )? .into_iter() .filter(|(_, fields)| { fields .get("from_id") .and_then(Value::as_str) .is_some_and(|id| !moving_ids.contains(id)) }) .collect(); before.insert("incoming_links".into(), json!(incoming)); let mut history = Map::new(); history.insert( "actor".into(), json!( source .writer_actor() .ok_or_else(|| ToolFailure::new("move needs write access"))? .to_wire() ), ); history.insert("id".to_owned(), Value::String(source.new_uuid())); history.insert("table_id".to_owned(), Value::String(snapshot.table.clone())); history.insert("record_id".to_owned(), Value::String(snapshot.id.clone())); history.insert("verb".to_owned(), Value::String("move".to_owned())); history.insert("byline".to_owned(), Value::String(source.agent.to_owned())); history.insert("before".to_owned(), Value::Object(before)); history.insert( "after".to_owned(), json!({"to": tombstone.destination, "to_name": to_name, "moved_at": tombstone.moved_at, "moved_by": tombstone.moved_by, "from": source.workspace_id, "origin":original_origin(source,snapshot)?, "moving_ids":moving_ids,"arrival":arrival}), ); history.insert( "created_at".to_owned(), Value::String(tombstone.moved_at.clone()), ); let change_id = history["id"].as_str().expect("id").to_owned(); let mut arrival = history.clone(); let arrival_id = dest.new_uuid(); arrival.insert("id".into(), json!(arrival_id)); arrival.insert("verb".into(), json!("move_in")); arrival.insert( "actor".into(), json!( dest.writer_actor() .ok_or_else(|| ToolFailure::new("move needs write access"))? .to_wire() ), ); dest.writer()? .upsert("cotton_changes", &arrival_id, arrival); source .writer()? .upsert("cotton_changes", &change_id, history); change_ids.push(change_id); for (id, fields) in &incoming { let mut fields = fields.clone(); fields.insert("to_database".into(), json!(dest.workspace_id)); source.writer()?.upsert("cotton_links", id, fields); } if !owned_by_moving_parent(&snapshot.table, &snapshot.fields, &moving_keys) { source .writer()? .retract(&snapshot.table, &snapshot.id, Retract::Machine("moved")); } for related in &snapshot.related { if !related.reference_only && !owned_by_moving_parent(&related.table, &related.fields, &moving_keys) { source .writer()? .retract(&related.table, &related.id, Retract::Machine("moved")); } } } // Queue destination writes only after the planner has proved every member // can land. Do not copy workspace_id: Writer stamps the destination's // workspace, while all provenance fields (including byline and created_at) // remain exactly as read. for snapshot in &plan.destination { if !arrival { queue_row( source, dest, &snapshot.table, &snapshot.id, &snapshot.fields, &moving_ids, )?; } for related in &snapshot.related { if (related.reference_only || arrival) && read_row(dest.db(), &related.table, &related.id)?.is_some() { continue; } queue_row( source, dest, &related.table, &related.id, &related.fields, &moving_ids, )?; } } let changes: Vec = plan.destination.iter().zip(change_ids).map(|(row, change_id)| json!({"id": change_id, "table":row.table, "record_id": row.id, "before":row.fields, "verb":"move", "byline":source.agent, "created_at":crate::clock::iso(source.now), "undoable":true})).collect(); let mut answer = json!({"moved":plan.destination.iter().map(|row| row.id.clone()).collect::>(), "to":to_name, "to_database":dest.workspace_id, "home_database":dest.workspace_id, "changes":changes,"records":plan.destination.iter().map(|row|json!({"table":row.table,"id":row.id})).collect::>()}); let change = if changes.len() == 1 { changes[0].clone() } else { let batch_id = source.new_uuid(); let at = crate::clock::iso(source.now); let history = json!({"id":batch_id,"table_id":"_move_batch","verb":"move","byline":source.agent,"before":{"changes":changes.iter().map(|change|change["id"].clone()).collect::>()},"after":{"to":dest.workspace_id,"to_name":to_name},"created_at":at}); source.writer()?.upsert( "cotton_changes", &batch_id, history.as_object().unwrap().clone(), ); json!({"id":batch_id,"table":"_move_batch","verb":"move","undoable":true}) }; answer["change"] = change.clone(); answer["undo"] = json!({"method":"records.move", "args":{"change_id":change["id"], "database":source.workspace_id}}); if arrival { answer.as_object_mut().unwrap().remove("undo"); answer["change"]["undoable"] = json!(false); } Ok(answer) } /// Move a batch under one transaction per file. /// /// The destination transaction sits inside the source transaction so any /// ordinary error rolls both back. Separate SQLite files cannot make that a /// durable two-phase commit; callers that need crash recovery use /// [`queue_batch`] and their durable coordinator. pub fn move_batch( source: &mut Ctx<'_>, dest: &mut Ctx<'_>, ids: &[String], to_name: &str, ) -> ToolResult { let source_db = source.db(); let dest_db = dest.db(); let result = source_db .transaction(|_| { dest_db.transaction(|_| { let answer = queue_batch(source, dest, ids, to_name) .map_err(|error| StoreError::refused(error.0))?; dest.commit() .map_err(|error| StoreError::refused(error.0))?; source .commit() .map_err(|error| StoreError::refused(error.0))?; verify_materialized(source, dest, &answer) .map_err(|e| StoreError::refused(e.message()))?; Ok(answer) }) }) .map_err(|error| ToolFailure::new(error.to_string())); if result.is_err() { source.discard_queued(); dest.discard_queued(); } result } /// Queue the reverse of one move history fact. The caller supplies the old /// home as `source` and the current home as `dest`; this is the same ordering /// as [`queue_batch`]. A later change at the destination refuses the undo so /// an old snapshot never overwrites somebody's newer edit. pub fn queue_undo(source: &mut Ctx<'_>, dest: &mut Ctx<'_>, change_id: &str) -> ToolResult { // Check the entire batch before any member queues its restoration. if !source.writer_actor().is_some_and(|actor| actor.is_owner()) { let mut pending = vec![change_id.to_owned()]; let mut seen = BTreeSet::new(); while let Some(id) = pending.pop() { if !seen.insert(id.clone()) { continue; } if let Some(row) = source.db().get("SELECT table_id,before FROM cotton_changes WHERE id=? AND verb='move'", &[SqlValue::Text(id)]).map_err(store_failure)? { if requires_owner(row.text("table_id").unwrap_or_default()) { owner_act(source)?; } if row.text("table_id") == Some("_move_batch") { let before: Value = serde_json::from_str(row.text("before").unwrap_or("null")).map_err(store_failure)?; if let Some(members) = before["changes"].as_array() { pending.extend(members.iter().filter_map(Value::as_str).map(str::to_owned)); } } } } } let row = source.db().get( "SELECT table_id, record_id, before, after, created_at FROM cotton_changes WHERE id = ? AND verb = 'move' AND NOT EXISTS (SELECT 1 FROM cotton_undos WHERE change_id = ?)", &[SqlValue::Text(change_id.to_owned()), SqlValue::Text(change_id.to_owned())], ).map_err(store_failure)?.ok_or_else(|| ToolFailure::new("move is not available to undo"))?; let metadata: Value = serde_json::from_str(row.text("after").unwrap_or("null")).map_err(store_failure)?; if metadata["arrival"] == true { return Err(ToolFailure::new( "repeat arrivals return through a fresh whole-thread move", )); } let table = row .text("table_id") .ok_or_else(|| ToolFailure::new("move history has no table"))? .to_owned(); if table == "_move_batch" { let before: Value = serde_json::from_str( row.text("before") .ok_or_else(|| ToolFailure::new("batch has no snapshot"))?, ) .map_err(store_failure)?; let members = before["changes"] .as_array() .ok_or_else(|| ToolFailure::new("batch has no changes"))?; let mut undone = Vec::new(); for member in members { let member = member .as_str() .ok_or_else(|| ToolFailure::new("batch has an invalid change id"))?; undone.push(queue_undo(source, dest, member)?); } queue_undo_mark(source, change_id)?; return Ok(json!({"undone":undone,"change_id":change_id})); } if requires_owner(&table) { owner_act(source)?; } let id = row .text("record_id") .ok_or_else(|| ToolFailure::new("move history has no record"))? .to_owned(); let before: Map = serde_json::from_str( row.text("before") .ok_or_else(|| ToolFailure::new("move history has no snapshot"))?, ) .map_err(|error| ToolFailure::new(format!("move history snapshot is invalid: {error}")))?; let live = read_row(dest.db(), &table, &id)? .ok_or_else(|| ToolFailure::new("moved record is no longer at its destination"))?; let moved_at = row .text("created_at") .ok_or_else(|| ToolFailure::new("move history has no timestamp"))?; let later = dest .db() .get( "SELECT 1 AS one FROM cotton_changes WHERE record_id = ? AND created_at > ? LIMIT 1", &[ SqlValue::Text(id.clone()), SqlValue::Text(moved_at.to_owned()), ], ) .map_err(store_failure)? .is_some(); if later { return Err(ToolFailure::new( "move cannot be undone because the record changed after it moved", )); } let metadata: Value = serde_json::from_str( row.text("after") .ok_or_else(|| ToolFailure::new("move has no destination metadata"))?, ) .map_err(store_failure)?; let moving_ids: BTreeSet = serde_json::from_value(metadata["moving_ids"].clone()).map_err(store_failure)?; let mut root = before.clone(); let incoming: Vec<(String, Map)> = serde_json::from_value(root.remove("incoming_links").unwrap_or_else(|| json!([]))) .map_err(store_failure)?; let related = root .remove("related") .and_then(|value| value.as_array().cloned()) .unwrap_or_default(); let expected_keys: BTreeSet = related .iter() .filter_map(|row| { Some(RecordKey::new( row.get("table")?.as_str()?, row.get("id")?.as_str()?, )) }) .collect(); for current in collect_related(dest.db(), &table, &id)? { if !expected_keys.contains(¤t.key()) && !moving_ids.contains(¤t.id) { return Err(ToolFailure::new( "move cannot be undone because the record gained a related row", )); } } if table == "cotton_secrets" { ensure_secret_payload_same(source, dest, &id, &root, &live)?; } ensure_same_snapshot( &table, &relocated_fields(&table, &root, source.workspace_id, &moving_ids), &live, )?; for (link_id, original) in &incoming { let actual = read_row(source.db(), "cotton_links", link_id)?.ok_or_else(|| { ToolFailure::new("move cannot be undone because an incoming link is gone") })?; let mut expected = original.clone(); expected.insert("to_database".into(), json!(dest.workspace_id)); ensure_same_snapshot("cotton_links", &expected, &actual)?; } for related_row in &related { if related_row["reference_only"] == Value::Bool(true) { continue; } let object = related_row .as_object() .ok_or_else(|| ToolFailure::new("move history related snapshot is invalid"))?; let related_table = object .get("table") .and_then(Value::as_str) .ok_or_else(|| ToolFailure::new("move history related table is invalid"))?; let related_id = object .get("id") .and_then(Value::as_str) .ok_or_else(|| ToolFailure::new("move history related id is invalid"))?; let expected = object .get("fields") .and_then(Value::as_object) .ok_or_else(|| ToolFailure::new("move history related fields are invalid"))?; let actual = read_row(dest.db(), related_table, related_id)?.ok_or_else(|| { ToolFailure::new("move cannot be undone because a related row is gone") })?; ensure_same_snapshot( related_table, &relocated_fields(related_table, expected, source.workspace_id, &moving_ids), &actual, )?; } if read_row(source.db(), &table, &id)?.is_some() { return Err(ToolFailure::new( "move cannot be undone because the old home holds another life of this record", )); } queue_undo_mark(source, change_id)?; queue_restore(source, &table, &id, &root)?; for (link_id, fields) in incoming { queue_restore(source, "cotton_links", &link_id, &fields)?; } let undo_keys: BTreeSet = std::iter::once(RecordKey::new(&table, &id)) .chain( related .iter() .filter(|row| row["reference_only"] != Value::Bool(true)) .filter_map(|row| { Some(RecordKey::new(row["table"].as_str()?, row["id"].as_str()?)) }), ) .collect(); if !owned_by_moving_parent(&table, &root, &undo_keys) { dest.writer()? .retract(&table, &id, Retract::Machine("moved")); } for related in related { if related["reference_only"] == Value::Bool(true) { continue; } let object = related .as_object() .ok_or_else(|| ToolFailure::new("move history related snapshot is invalid"))?; let table = object .get("table") .and_then(Value::as_str) .ok_or_else(|| ToolFailure::new("move history related table is invalid"))?; let id = object .get("id") .and_then(Value::as_str) .ok_or_else(|| ToolFailure::new("move history related id is invalid"))?; let fields = object .get("fields") .and_then(Value::as_object) .ok_or_else(|| ToolFailure::new("move history related fields are invalid"))?; queue_restore(source, table, id, fields)?; if !owned_by_moving_parent(table, fields, &undo_keys) { dest.writer()?.retract(table, id, Retract::Machine("moved")); } } Ok( json!({"undone": id, "change_id": change_id, "home_database":source.workspace_id,"records":[{"table":table,"id":id}]}), ) } fn queue_row( source: &Ctx<'_>, ctx: &mut Ctx<'_>, table: &str, id: &str, fields: &Map, moving: &BTreeSet, ) -> ToolResult { let mut fields = relocated_fields(table, fields, source.workspace_id, moving); fields.remove("workspace_id"); if table == "cotton_msg_contacts" && cotton_store::link_rule::file_kind(ctx.db()).map_err(store_failure)? == cotton_store::link_rule::FileKind::Shared { let person=crate::messages::admission::person_for_contact(source.db(),ctx.db(),ctx.workspace_id,id).map_err(store_failure)?; fields.insert("person_id".into(),person.map(|p|json!(p.id)).unwrap_or(Value::Null)); } if table == "cotton_secrets" { let source_vault = source.services.vault.as_ref().ok_or_else(|| { ToolFailure::new("vault_unavailable: move cannot open the source secret") })?; let dest_vault = ctx.services.vault.as_ref().ok_or_else(|| { ToolFailure::new("vault_unavailable: move cannot seal the destination secret") })?; let sealed = fields .get("value_enc") .and_then(Value::as_str) .ok_or_else(|| ToolFailure::new("secret has no sealed payload"))?; let version = fields .get("vmk_version") .and_then(Value::as_i64) .ok_or_else(|| ToolFailure::new("secret has no vault key version"))? as u32; let mut payload = source_vault.open(id, version, sealed).ok_or_else(|| { ToolFailure::new("source vault could not open secret; nothing was moved") })?; let resealed = dest_vault.seal(id, &payload); cotton_core::vault::seal::wipe(std::mem::take(&mut payload)); let resealed = resealed.ok_or_else(|| { ToolFailure::new("destination vault could not seal secret; nothing was moved") })?; fields.insert("value_enc".to_owned(), Value::String(resealed.value_enc)); fields.insert("vmk_version".to_owned(), Value::from(resealed.vmk_version)); } ctx.writer()?.upsert(table, id, fields); Ok(Value::Null) } /// Restore a move snapshot in its original file. In particular, a secret's /// sealed body was made for this file's vault, so restoring it is safe without /// ever opening the destination ciphertext. fn queue_restore( ctx: &mut Ctx<'_>, table: &str, id: &str, fields: &Map, ) -> ToolResult { let mut fields = fields.clone(); fields.remove("workspace_id"); ctx.writer()?.upsert(table, id, fields); Ok(Value::Null) } fn ensure_same_snapshot( table: &str, expected: &Map, actual: &Map, ) -> Result<(), ToolFailure> { let mut expected = expected.clone(); let mut actual = actual.clone(); expected.remove("workspace_id"); actual.remove("workspace_id"); if table == "cotton_secrets" { // Ciphertext is necessarily different after a cross-file move; its // metadata is still checked, while the original cipher is restored in // its original vault without exposing either plaintext. for field in ["value_enc", "vmk_version", "hint"] { expected.remove(field); actual.remove(field); } } if expected == actual { Ok(()) } else { Err(ToolFailure::new( "move cannot be undone because the record changed after it moved", )) } } pub fn collect_snapshots(db: &Driver, ids: &[String]) -> Result, ToolFailure> { if ids.is_empty() { return Err(ToolFailure::new("move needs at least one record")); } let mut snapshots = Vec::with_capacity(ids.len()); let mut roots = BTreeSet::new(); for id in ids { let (table, fields) = find_root(db, id)?; if !roots.insert(RecordKey::new(table.clone(), id.clone())) { return Err(ToolFailure::new(format!( "move names {table} {id} more than once" ))); } let related = collect_related(db, &table, id)?; snapshots.push(Snapshot { table, id: id.clone(), fields, related, }); } // A shared link or a comment reached from two selected roots travels once. // The planner rightly refuses duplicate write keys, so normalize the // traversal result before asking it to validate the batch. let root_keys: BTreeSet = snapshots.iter().map(Snapshot::key).collect(); let mut related_seen = root_keys.clone(); for snapshot in &mut snapshots { snapshot .related .retain(|row| related_seen.insert(row.key())); } Ok(snapshots) } fn find_root(db: &Driver, id: &str) -> Result<(String, Map), ToolFailure> { let mut found = Vec::new(); for table in root_tables(db)? { if spec_on(db, &table).map_err(store_failure)?.is_none() { continue; } if let Some(row) = read_row(db, &table, id)? { found.push((table, row)); } } match found.len() { 0 => Err(ToolFailure::new(format!("no supported record has id {id}"))), 1 => Ok(found.remove(0)), _ => Err(ToolFailure::new(format!( "id {id} names more than one record table" ))), } } fn root_tables(db: &Driver) -> Result, ToolFailure> { let tables = VERSIONED_TABLES .iter() .map(|entry| entry.table.to_owned()) .chain( BinKind::ALL .into_iter() .map(|kind| bin_source(kind).table.to_owned()), ) .chain( ["cotton_comments", "cotton_msg_threads", "cotton_repos", "cotton_inbox_items"] .into_iter() .map(str::to_owned), ) .chain(cotton_store::schema::package_shape::held_tables(db).map_err(store_failure)?); Ok(tables.collect()) } fn collect_related( db: &Driver, root_table: &str, root_id: &str, ) -> Result, ToolFailure> { let mut related = Vec::new(); let mut seen = BTreeSet::new(); let mut todo = VecDeque::from([(root_table.to_owned(), root_id.to_owned())]); while let Some((parent_table, parent_id)) = todo.pop_front() { for (child, column, parent) in OWNING_REFS { if *parent != parent_table { continue; } for (id, fields) in rows_where(db, child, column, &parent_id)? { if seen.insert(RecordKey::new((*child).to_owned(), id.clone())) { todo.push_back(((*child).to_owned(), id.clone())); related.push(RelatedSnapshot { table: (*child).to_owned(), id, fields, reference_only: false, }); } } } // A comment is owned by the record it discusses, while its replies are // collected through OWNING_REFS above. `record_kind` prevents an id // shared by different record types from pulling unrelated discussion. if parent_table == root_table && parent_id == root_id { for (id, fields) in comments_for(db, record_kind(root_table), root_id)? { if seen.insert(RecordKey::new("cotton_comments", id.clone())) { todo.push_back(("cotton_comments".to_owned(), id.clone())); related.push(RelatedSnapshot { table: "cotton_comments".to_owned(), id, fields, reference_only: false, }); } } for (id, fields) in links_for(db, root_id)? { if seen.insert(RecordKey::new("cotton_links", id.clone())) { related.push(RelatedSnapshot { table: "cotton_links".to_owned(), id, fields, reference_only: false, }); } } } } let content = root_tables(db)?; let mut parents = VecDeque::from([(root_table.to_owned(), root_id.to_owned())]); parents.extend( related .iter() .map(|row| (row.table.clone(), row.id.clone())), ); while let Some((child_table, child_id)) = parents.pop_front() { let Some(fields) = read_row(db, &child_table, &child_id)? else { continue; }; for (child, column, parent) in OWNING_REFS { if *child != child_table || content.contains(*parent) { continue; } let Some(id) = fields.get(*column).and_then(Value::as_str) else { continue; }; let key = RecordKey::new(*parent, id); if seen.insert(key) { let fields = read_row(db, parent, id)? .ok_or_else(|| ToolFailure::new("record has a missing supporting parent"))?; parents.push_back(((*parent).into(), id.into())); related.push(RelatedSnapshot { table: (*parent).into(), id: id.into(), fields, reference_only: true, }); } } } // A contact is supporting context, and its identity handles are context // too. They remain in Personal and carry to the filed chat's home. let contacts: Vec = related.iter().filter(|r|r.table=="cotton_msg_contacts").map(|r|r.id.clone()).collect(); for contact in contacts { for (id,fields) in rows_where(db,"cotton_msg_contact_handles","contact_id",&contact)? { if seen.insert(RecordKey::new("cotton_msg_contact_handles",id.clone())) { related.push(RelatedSnapshot{table:"cotton_msg_contact_handles".into(),id,fields,reference_only:true}); } } } Ok(related) } fn record_kind(table: &str) -> &str { if table == "cotton_inbox_items" { return "thought"; } VERSIONED_TABLES .iter() .find(|entry| entry.table == table) .map(|entry| entry.kind) .or_else(|| { BinKind::ALL .into_iter() .find(|kind| bin_source(*kind).table == table) .map(|kind| kind.as_str()) }) .unwrap_or(table) } fn destination_keys( db: &Driver, snapshots: &[Snapshot], ) -> Result, ToolFailure> { let mut keys = BTreeSet::new(); for snapshot in snapshots { for key in std::iter::once(RecordKey::new(&snapshot.table, &snapshot.id)).chain( snapshot .related .iter() .filter(|row| !row.reference_only) .map(RelatedSnapshot::key), ) { if read_row(db, &key.table, &key.id)?.is_some() { keys.insert(key); } } } Ok(keys) } fn comments_for( db: &Driver, kind: &str, id: &str, ) -> Result)>, ToolFailure> { rows_by_sql( db, "cotton_comments", "record_id = ? AND record_kind = ?", &[ SqlValue::Text(id.to_owned()), SqlValue::Text(kind.to_owned()), ], ) } fn links_for(db: &Driver, id: &str) -> Result)>, ToolFailure> { rows_by_sql( db, "cotton_links", "from_id = ?", &[SqlValue::Text(id.to_owned())], ) } fn rows_where( db: &Driver, table: &str, column: &str, value: &str, ) -> Result)>, ToolFailure> { rows_by_sql( db, table, &format!("{} = ?", quote_ident(column)), &[SqlValue::Text(value.to_owned())], ) } fn rows_by_sql( db: &Driver, table: &str, where_sql: &str, params: &[SqlValue], ) -> Result)>, ToolFailure> { let spec = spec_on(db, table) .map_err(store_failure)? .ok_or_else(|| ToolFailure::new(format!("move does not support {table}")))?; let sql = format!("SELECT * FROM {} WHERE {where_sql}", quote_ident(table)); db.all(&sql, params) .map_err(store_failure)? .into_iter() .map(|row| { let fields = decode_row(spec.columns, row.columns()).map_err(store_failure)?; let id = fields .get("id") .and_then(Value::as_str) .ok_or_else(|| ToolFailure::new(format!("{table} row has no id")))? .to_owned(); Ok((id, fields)) }) .collect() } fn read_row(db: &Driver, table: &str, id: &str) -> Result>, ToolFailure> { let rows = rows_by_sql(db, table, "id = ?", &[SqlValue::Text(id.to_owned())])?; Ok(rows.into_iter().next().map(|(_, fields)| fields)) } fn quote_ident(identifier: &str) -> String { format!("\"{}\"", identifier.replace('"', "\"\"")) } fn store_failure(error: impl std::fmt::Display) -> ToolFailure { ToolFailure::new(error.to_string()) } #[cfg(test)] #[path = "record_moves_tests.rs"] mod tests; fn original_byline(db: &Driver, snapshot: &Snapshot) -> Result { for column in ["record_byline", "byline", "author_label"] { if let Some(byline) = snapshot.fields.get(column).filter(|v| !v.is_null()) { return Ok(byline.clone()); } } Ok(db .get( "SELECT byline FROM cotton_changes WHERE record_id = ? ORDER BY created_at, id LIMIT 1", &[SqlValue::Text(snapshot.id.clone())], ) .map_err(store_failure)? .and_then(|row| row.text("byline").map(|s| json!(s))) .unwrap_or_else(|| json!("user"))) } fn relocated_fields( table: &str, fields: &Map, from: &str, moving: &BTreeSet, ) -> Map { let mut relocated = fields.clone(); if table == "cotton_links" && fields.get("to_database").is_none_or(Value::is_null) && fields .get("to_id") .and_then(Value::as_str) .is_some_and(|id| !moving.contains(id)) { relocated.insert("to_database".into(), json!(from)); } relocated } fn ensure_secret_payload_same( source: &Ctx<'_>, destination: &Ctx<'_>, id: &str, original: &Map, current: &Map, ) -> Result<(), ToolFailure> { let open = |ctx: &Ctx<'_>, fields: &Map| -> Result, ToolFailure> { let vault = ctx .services .vault .as_ref() .ok_or_else(|| ToolFailure::new("vault_unavailable: undo needs both vaults"))?; let version = fields .get("vmk_version") .and_then(Value::as_u64) .and_then(|v| u32::try_from(v).ok()) .ok_or_else(|| ToolFailure::new("secret has no vault key version"))?; let sealed = fields .get("value_enc") .and_then(Value::as_str) .ok_or_else(|| ToolFailure::new("secret has no sealed payload"))?; vault .open(id, version, sealed) .ok_or_else(|| ToolFailure::new("vault could not open secret; nothing was undone")) }; let original = open(source, original)?; let current = open(destination, current); let same = current.as_ref().is_ok_and(|current| { current.len() == original.len() && current .iter() .zip(&original) .fold(0u8, |diff, (a, b)| diff | (a ^ b)) == 0 }); cotton_core::vault::seal::wipe(original); match current { Ok(current) => cotton_core::vault::seal::wipe(current), Err(error) => return Err(error), } if same { Ok(()) } else { Err(ToolFailure::new( "move cannot be undone because the secret changed after it moved", )) } } fn queue_undo_mark(source: &mut Ctx<'_>, change_id: &str) -> Result<(), ToolFailure> { let undo_id = cotton_store::fact_hooks::undo_fact_id(change_id); let undo_actor = source .writer_actor() .ok_or_else(|| ToolFailure::new("undo needs write access"))? .to_wire(); let undo_at = crate::clock::iso(source.now); source.writer()?.upsert( "cotton_undos", &undo_id, Map::from_iter([ ("id".to_owned(), Value::String(undo_id.clone())), ("change_id".to_owned(), Value::String(change_id.to_owned())), ( "undo_change_id".to_owned(), Value::String(change_id.to_owned()), ), ("at".to_owned(), Value::String(undo_at)), ("actor".to_owned(), Value::String(undo_actor)), ]), ); Ok(()) } fn original_origin(source: &Ctx<'_>, snapshot: &Snapshot) -> Result { if let Some(row) = source.db().get("SELECT after FROM cotton_changes WHERE record_id = ? AND verb = 'move_in' ORDER BY created_at,id LIMIT 1", &[SqlValue::Text(snapshot.id.clone())]).map_err(store_failure)? { let metadata: Value = serde_json::from_str(row.text("after").unwrap_or("null")).map_err(store_failure)?; if let Some(origin) = metadata.get("origin").filter(|origin| origin.is_object()) { return Ok(origin.clone()); } } Ok( json!({"database":source.workspace_id,"byline":original_byline(source.db(),snapshot)?,"created_at":snapshot.fields.get("created_at")}), ) } pub fn verify_materialized( source: &Ctx<'_>, destination: &Ctx<'_>, answer: &Value, ) -> Result<(), ToolFailure> { if let Some(undone) = answer.get("undone").and_then(Value::as_array) { for child in undone { verify_materialized(source, destination, child)?; } } let home = if answer.get("home_database").and_then(Value::as_str) == Some(source.workspace_id) { source } else { destination }; if let Some(records) = answer.get("records").and_then(Value::as_array) { for record in records { let table = record["table"] .as_str() .ok_or_else(|| ToolFailure::new("move has no record table"))?; let id = record["id"] .as_str() .ok_or_else(|| ToolFailure::new("move has no record id"))?; if read_row(home.db(), table, id)?.is_none() { return Err(ToolFailure::new( "move needs its owning parent in the destination; move the parent with the record", )); } } } Ok(()) } fn owned_by_moving_parent( table: &str, fields: &Map, moving: &BTreeSet, ) -> bool { OWNING_REFS.iter().any(|(child, column, parent)| { *child == table && fields .get(*column) .and_then(Value::as_str) .is_some_and(|id| moving.contains(&RecordKey::new(*parent, id))) }) }