Cotton code
939 lines · 32.3 KB · RustRaw
//! Transient `message_import` records backed by the native WhatsApp chat importer.//!//! A chat export is a capability held by this installation, not a durable//! database row.  These records therefore deliberately contain only runs this//! handle started: the durable `cotton_imports` history must never stand in for//! an in-flight chooser, owner question, retry, or receipt.use std::collections::HashMap;use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{Mutex, OnceLock};use std::time::{SystemTime, UNIX_EPOCH};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::phone::whatsapp_import::sanitise_file_name;use serde_json::{json, Map, Value};pub const TABLE: &str = "message_import";pub const WHATSAPP: &str = "whatsapp";/// Methods used by shipped definition commands.  `records.command` resolves/// these normally, so command validation and picked-value binding stay in the/// generic records engine.pub const METHODS: [&str; 4] = [    "message.import.choose",    "message.import.run",    "message.import.retry",    "message.import.owner",];/// Runs are process-local and scoped to both the handle data directory and the/// database from which creation happened. A page in another held database can/// never retarget an import run.static RUNS: OnceLock<Mutex<HashMap<Scope, Vec<Run>>>> = OnceLock::new();static NEXT_ID: AtomicU64 = AtomicU64::new(1);#[derive(Clone, Debug, Hash, PartialEq, Eq)]struct Scope {    data_dir: PathBuf,    database: String,}#[derive(Clone, Debug)]struct Run {    id: String,    /// The private copy native importers may read after the picker closes.    path: String,    /// The selected capability, retained only to refuse a second held run.    origin_path: String,    /// Directory Cotton created for this run and may remove on success.    stage_dir: PathBuf,    name: String,    source: Option<Source>,    state: State,}#[derive(Clone, Copy, Debug, PartialEq, Eq)]enum Source {    WhatsApp,}#[derive(Clone, Debug)]enum State {    Choosing,    Asking(Vec<String>),    /// Claimed under the held-run mutex before either native importer runs.    /// A second command sees this state and cannot import the same file twice.    Running,    Completed(Value),    Failed(String),}/// Intercepts the transient read/create verbs only. `records.command` must/// continue to the standard definition engine, which calls [`call_method`].pub fn call(    handle: &CottonHandle,    method: &str,    request: &Value,) -> Option<Result<Value, MethodError>> {    if request.get("table").and_then(Value::as_str) != Some(TABLE) {        return None;    }    match method {        "records.list" => Some(list(handle, request)),        "records.get" => Some(get(handle, request)),        "records.create" => Some(create(handle, request)),        _ => None,    }}/// Standard definition-command endpoint. `args` contains the already-bound/// command arguments; every transition still validates the held state here.pub fn call_method(    handle: &CottonHandle,    method: &str,    args: &Value,) -> Result<Value, MethodError> {    match method {        "message.import.choose" => choose(handle),        "message.import.run" => run_method(handle, args),        "message.import.retry" => retry(handle, args),        "message.import.owner" => owner(handle, args),        other => Err(MethodError::new(            "unknown_method",            format!("`{other}` is not a message-import method"),        )),    }}fn runs() -> &'static Mutex<HashMap<Scope, Vec<Run>>> {    RUNS.get_or_init(|| Mutex::new(HashMap::new()))}fn lock_runs() -> std::sync::MutexGuard<'static, HashMap<Scope, Vec<Run>>> {    runs()        .lock()        .unwrap_or_else(|poisoned| poisoned.into_inner())}fn scope(handle: &CottonHandle) -> Result<Scope, MethodError> {    let database = handle.client().current_database().map_err(|reason| {        MethodError::new(            "database_unavailable",            format!("the current database could not be read: {reason}"),        )    })?;    Ok(Scope {        data_dir: handle.data_dir().to_path_buf(),        database,    })}fn listed_runs(handle: &CottonHandle) -> Result<Vec<Run>, MethodError> {    let scope = scope(handle)?;    Ok(lock_runs().get(&scope).cloned().unwrap_or_default())}fn list(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let mut rows = listed_runs(handle)?        .into_iter()        .rev() // newest first, matching the old source        .map(|run| record(&run))        .collect::<Vec<_>>();    if let Some(ids) = request.get("ids") {        let ids = ids            .as_array()            .ok_or_else(|| MethodError::new("bad_request", "`ids` is an array of record ids"))?;        let wanted = ids            .iter()            .filter_map(Value::as_str)            .collect::<std::collections::BTreeSet<_>>();        rows.retain(|row| row["id"].as_str().is_some_and(|id| wanted.contains(id)));    }    let total = rows.len();    Ok(json!({"table": TABLE, "records": rows, "total": total, "next_page": Value::Null}))}fn get(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let id = id(request, "`records.get` needs a record id")?;    listed_runs(handle)?        .into_iter()        .find(|run| run.id == id)        .map(|run| record(&run))        .ok_or_else(|| {            MethodError::new(                "record_not_found",                format!("the `{TABLE}` table has no held import `{id}`"),            )        })}fn create(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let data = request        .get("data")        .and_then(Value::as_object)        .ok_or_else(|| {            MethodError::new(                "bad_request",                "`message_import` creation needs data with a selected file",            )        })?;    let source = data        .get("file")        .and_then(Value::as_str)        .map(str::trim)        .filter(|path| !path.is_empty())        .ok_or_else(|| {            MethodError::new(                "bad_request",                "`message_import` creation needs the selected file path",            )        })?;    let source = PathBuf::from(source);    let source = source.canonicalize().map_err(|error| {        MethodError::new(            "unreadable",            format!("the selected export could not be found: {error}"),        )    })?;    let metadata = std::fs::metadata(&source).map_err(|error| {        MethodError::new(            "unreadable",            format!("the selected export could not be read: {error}"),        )    })?;    if !metadata.is_file() {        return Err(MethodError::new(            "bad_request",            "the selected export must be a regular file",        ));    }    let name = staged_name(data.get("name").and_then(Value::as_str), &source);    let origin_path = source.to_string_lossy().to_string();    let scope = scope(handle)?;    // Reject the ordinary duplicate before copying.  A second check below    // closes the race without ever starting a second native importer.    if holds_origin(        &lock_runs().get(&scope).cloned().unwrap_or_default(),        &origin_path,    ) {        return Err(MethodError::new(            "already_importing",            "this selected export already has a held import",        ));    }    let id = next_id();    let (path, stage_dir) = stage_file(handle.data_dir(), &id, &source, &name)?;    let mut run = Run {        id,        path: path.to_string_lossy().to_string(),        origin_path,        stage_dir,        name,        source: None,        state: State::Choosing,    };    {        let mut held = lock_runs();        let entries = held.entry(scope).or_default();        if holds_origin(entries, &run.origin_path) {            // not a copy: imported message files.            let _ = std::fs::remove_dir_all(&run.stage_dir);            return Err(MethodError::new(                "already_importing",                "this selected export already has a held import",            ));        }        if starts_as_whatsapp(&run) {            run.source = Some(Source::WhatsApp);        }        entries.push(run.clone());    }    if run.source.is_some() {        run = execute(handle, &run.id, None, None)?;    }    Ok(json!({"change": Value::Null, "record": record(&run)}))}/// Copy while the platform still holds the selected URL's security scope./// Only this directory is Cotton-owned; the selected original is never moved/// or deleted.fn stage_file(    data_dir: &Path,    run_id: &str,    source: &Path,    name: &str,) -> Result<(PathBuf, PathBuf), MethodError> {    let metadata = std::fs::metadata(source).map_err(|error| {        MethodError::new(            "unreadable",            format!("the selected export could not be read: {error}"),        )    })?;    if !metadata.is_file() {        return Err(MethodError::new(            "bad_request",            "the selected export must be a regular file",        ));    }    let stage_dir = data_dir.join("tmp").join("message-imports").join(run_id);    std::fs::create_dir_all(&stage_dir).map_err(|error| {        MethodError::new(            "unreadable",            format!("the import staging folder could not be made: {error}"),        )    })?;    let target = stage_dir.join(name);    // not a copy: imported message files.    if let Err(error) = std::fs::copy(source, &target) {        // not a copy: imported message files.        let _ = std::fs::remove_dir_all(&stage_dir);        return Err(MethodError::new(            "unreadable",            format!("the selected export could not be copied: {error}"),        ));    }    Ok((target, stage_dir))}fn staged_name(given: Option<&str>, source: &Path) -> String {    let leaf = given        .and_then(sanitise_file_name)        .or_else(|| {            source                .file_name()                .and_then(|name| name.to_str())                .and_then(sanitise_file_name)        })        .unwrap_or_else(|| "Export".into());    // A platform-provided display name occasionally loses its suffix; retain    // it because native import validation needs to distinguish a ZIP.    if Path::new(&leaf).extension().is_none() {        if let Some(extension) = source.extension().and_then(|extension| extension.to_str()) {            return format!("{leaf}.{extension}");        }    }    leaf}fn choose(handle: &CottonHandle) -> Result<Value, MethodError> {    let database = scope(handle)?.database;    Ok(json!({        "platform_action":"pick_file",        "accept":["public.zip-archive", "public.plain-text"],        "then":{"method":"records.create","arguments":{"table":TABLE,"data":{"file":"$path","name":"$name"},"database":database}}    }))}fn run_method(handle: &CottonHandle, args: &Value) -> Result<Value, MethodError> {    let id = id(args, "message.import.run needs an import id")?;    let source = source(args)?;    let run = execute(handle, id, Some(source), None)?;    Ok(command_answer(&run))}fn retry(handle: &CottonHandle, args: &Value) -> Result<Value, MethodError> {    let id = id(args, "message.import.retry needs an import id")?;    let before = find(handle, id)?;    if !matches!(before.state, State::Failed(_)) {        return Err(MethodError::new(            "not_offered",            "this import is not waiting to be retried",        ));    }    let run = execute(handle, id, None, None)?;    Ok(command_answer(&run))}fn owner(handle: &CottonHandle, args: &Value) -> Result<Value, MethodError> {    let id = id(args, "message.import.owner needs an import id")?;    let owner = args        .get("ownerName")        .and_then(Value::as_str)        .map(str::trim)        .filter(|value| !value.is_empty())        .ok_or_else(|| {            MethodError::new(                "bad_request",                "message.import.owner needs the selected sender",            )        })?;    let before = find(handle, id)?;    let State::Asking(senders) = &before.state else {        return Err(MethodError::new(            "not_offered",            "this import is not asking for its sender",        ));    };    if !sender_is_offered(senders, owner) {        return Err(MethodError::new(            "not_offered",            "that sender is not one of this export's choices",        ));    }    let run = execute(handle, id, None, Some(owner))?;    Ok(command_answer(&run))}fn command_answer(run: &Run) -> Value {    if matches!(run.state, State::Completed(_)) {        json!({"record":record(run), "receipt":receipt(run)})    } else {        json!({"record":record(run), "pending":true})    }}fn source(args: &Value) -> Result<Source, MethodError> {    match args.get("source").and_then(Value::as_str) {        Some("whatsapp") => Ok(Source::WhatsApp),        // Instagram left Cotton (owner, 22 Nov 2026): its export is no longer read.        Some("instagram") => Err(MethodError::new(            "refused",            "Cotton no longer imports Instagram exports",        )),        _ => Err(MethodError::new(            "bad_request",            "message.import.run needs source `whatsapp`",        )),    }}fn sender_is_offered(senders: &[String], owner: &str) -> bool {    !owner.is_empty() && senders.iter().any(|sender| sender == owner)}/// Atomically select/validate and claim a held run.  The expensive native/// importer runs only after this returns and therefore never holds RUNS.fn claim(    handle: &CottonHandle,    id: &str,    selected: Option<Source>,    owner: Option<&str>,) -> Result<Run, MethodError> {    let scope = scope(handle)?;    let mut held = lock_runs();    let run = held        .entry(scope)        .or_default()        .iter_mut()        .find(|run| run.id == id)        .ok_or_else(|| {            MethodError::new(                "record_not_found",                format!("the `{TABLE}` table has no held import `{id}`"),            )        })?;    claim_run(run, selected, owner)?;    Ok(run.clone())}fn claim_run(    run: &mut Run,    selected: Option<Source>,    owner: Option<&str>,) -> Result<(), MethodError> {    match (&run.state, selected, owner) {        (State::Choosing, Some(source), None) if run.source.is_none() => run.source = Some(source),        // A non-zip share chose WhatsApp before it entered RUNS; creation is        // its one automatic claim and no page command can take this branch.        (State::Choosing, None, None) if run.source.is_some() => {}        (State::Failed(_), None, None) if run.source.is_some() => {}        (State::Asking(senders), None, Some(owner)) if sender_is_offered(senders, owner) => {}        (State::Asking(_), None, Some(_)) => {            return Err(MethodError::new(                "not_offered",                "that sender is not one of this export's choices",            ))        }        (State::Running, _, _) => {            return Err(MethodError::new(                "already_importing",                "this export is already being imported",            ))        }        (State::Completed(_), _, _) => {            return Err(MethodError::new(                "not_offered",                "this import already completed and cannot run twice",            ))        }        (State::Failed(_), Some(_), _)        | (State::Choosing, Some(_), Some(_))        | (State::Choosing, None, Some(_))        | (State::Asking(_), Some(_), _)        | (State::Asking(_), None, None) => {            return Err(MethodError::new(                "not_offered",                "that import action is not offered in this state",            ))        }        _ => {            return Err(MethodError::new(                "not_offered",                "that import action is not offered in this state",            ))        }    }    run.state = State::Running;    Ok(())}/// Run outside the held-state mutex after [`claim`] made this run exclusive.fn execute(    handle: &CottonHandle,    id: &str,    selected: Option<Source>,    owner: Option<&str>,) -> Result<Run, MethodError> {    let run = claim(handle, id, selected, owner)?;    let source = run.source.expect("claim requires a source before Running");    // Sync is best-effort: an offline server does not make a local export unreadable.    let _ = handle.client().sync_now();    let result = (|| {        let args = match source {            Source::WhatsApp => json!({"path":run.path,"fileName":nonempty(&run.name),"ownerName":owner,"tzOffset":import_offset(handle)?}),        };        match source {            Source::WhatsApp => crate::phone::whatsapp_import::import(handle, &args),        }    })();    let changed = replace(handle, id, |held| {        if !matches!(held.state, State::Running) {            return Err(MethodError::new(                "unreadable",                "an import changed state before its native importer completed",            ));        }        held.state = match result {            Ok(answer)                if source == Source::WhatsApp && answer["needs"].as_str() == Some("ownerName") =>            {                let senders = answer["senders"]                    .as_array()                    .map(|values| {                        values                            .iter()                            .filter_map(Value::as_str)                            .map(str::to_owned)                            .collect::<Vec<_>>()                    })                    .unwrap_or_default();                if senders.is_empty() {                    // Do not strand a claimed run in Running when an importer                    // violates its owner-question contract.  The held error is                    // visible and the original source remains available to Retry.                    State::Failed(                        "The WhatsApp importer asked for an owner without sender choices.".into(),                    )                } else {                    State::Asking(senders)                }            }            Ok(answer) => State::Completed(answer),            Err(error) => State::Failed(error.message),        };        Ok(())    })?;    if matches!(changed.state, State::Completed(_)) {        // The importer has copied every message/media byte it needed.  This        // path is ours, unlike `origin_path`, and completion is terminal.        // not a copy: imported message files.        let _ = std::fs::remove_dir_all(&changed.stage_dir);    }    Ok(changed)}fn find(handle: &CottonHandle, id: &str) -> Result<Run, MethodError> {    listed_runs(handle)?        .into_iter()        .find(|run| run.id == id)        .ok_or_else(|| {            MethodError::new(                "record_not_found",                format!("the `{TABLE}` table has no held import `{id}`"),            )        })}fn replace(    handle: &CottonHandle,    id: &str,    change: impl FnOnce(&mut Run) -> Result<(), MethodError>,) -> Result<Run, MethodError> {    let scope = scope(handle)?;    let mut held = lock_runs();    let run = held        .entry(scope)        .or_default()        .iter_mut()        .find(|run| run.id == id)        .ok_or_else(|| {            MethodError::new(                "record_not_found",                format!("the `{TABLE}` table has no held import `{id}`"),            )        })?;    change(run)?;    Ok(run.clone())}fn id<'a>(request: &'a Value, message: &'static str) -> Result<&'a str, MethodError> {    request        .get("id")        .and_then(Value::as_str)        .map(str::trim)        .filter(|id| !id.is_empty())        .ok_or_else(|| MethodError::new("bad_request", message))}fn nonempty(value: &str) -> Value {    if value.trim().is_empty() { Value::Null } else { Value::String(value.to_owned()) }}/// The app's explicit zone, or the database's recorded zone; neither is/// inferred from the machine running the importer.fn import_offset(handle: &CottonHandle) -> Result<String, MethodError> {    let client = handle.client();    let zone = if let Some(zone) = client.time_zone() {        Some(zone.to_string())    } else {        client.read_rows("message.import.timezone", &mut |ctx| {            cotton_tools::mcp::handlers::common::workspace_timezone_or_null(ctx)                .map(|zone| zone.map_or(Value::Null, Value::from))                .map_err(|error| error.to_string())        }).map_err(|reason| MethodError::new("unreadable", reason))?            .as_str().map(str::to_string)    };    offset_for(zone.as_deref(), client.now().timestamp_millis())}fn offset_for(zone: Option<&str>, at_ms: i64) -> Result<String, MethodError> {    let missing = || MethodError::new("timezone_required", "Set a known time zone before importing this export.");    let zone = zone.ok_or_else(missing)?;    let seconds = cotton_core::transforms::zoned_clock::zone_offset_ms(at_ms, zone)        .map_err(|_| missing())? / 1000;    let whole = seconds.unsigned_abs();    Ok(format!(        "{}{:02}:{:02}",        if seconds < 0 { "-" } else { "+" },        whole / 3600,        (whole % 3600) / 60    ))}fn holds_origin(runs: &[Run], origin_path: &str) -> bool {    runs.iter().any(|run| run.origin_path == origin_path)}fn next_id() -> String {    let millis = SystemTime::now()        .duration_since(UNIX_EPOCH)        .unwrap_or_default()        .as_millis();    let serial = NEXT_ID.fetch_add(1, Ordering::Relaxed);    format!("message-import-{millis}-{serial}")}fn starts_as_whatsapp(run: &Run) -> bool {    let named = if run.name.is_empty() {        &run.path    } else {        &run.name    };    !named        .rsplit('.')        .next()        .is_some_and(|extension| extension.eq_ignore_ascii_case("zip"))        || named.to_ascii_lowercase().starts_with("whatsapp chat ")}fn record(run: &Run) -> Value {    let mut data = Map::from_iter([        ("name".into(), Value::String(title(&run.name))),        ("receipt".into(), Value::String(receipt(run))),        ("state".into(), Value::String(state_name(&run.state).into())),    ]);    if let State::Asking(senders) = &run.state {        // This is data, never a durable person/contact assertion.  A generic        // client may show these exact choices and issue `owner:<sender>`.        data.insert(            "senders".into(),            Value::Array(senders.iter().cloned().map(Value::String).collect()),        );    }    if let State::Completed(answer) = &run.state {        if run.source == Some(Source::WhatsApp) {            if let Some(thread) = answer["thread"].as_str() {                data.insert("thread_id".into(), Value::String(thread.to_owned()));            }            if let Some(media) = media_receipt(&answer["media"]) {                data.insert("media_receipt".into(), Value::String(media));            }        }    }    json!({"id":run.id,"data":data,"deleted_at":Value::Null})}fn state_name(state: &State) -> &'static str {    match state {        State::Choosing => "choosing",        State::Asking(_) => "asking",        State::Running => "running",        State::Completed(_) => "completed",        State::Failed(_) => "failed",    }}fn title(name: &str) -> String {    let leaf = name.rsplit(['/', '\\']).next().unwrap_or(name).trim();    let title = leaf        .rsplit_once('.')        .map(|(stem, _)| stem)        .unwrap_or(leaf)        .trim();    if title.is_empty() {        "Export".into()    } else {        title.into()    }}fn receipt(run: &Run) -> String {    match &run.state {        State::Choosing => "Choose where this export came from.".into(),        State::Asking(_) => {            "This export does not say which sender is you. Choose your name.".into()        }        State::Running => "Importing this export.".into(),        State::Failed(sentence) => sentence.clone(),        State::Completed(answer) => whatsapp_receipt(answer),    }}fn whatsapp_receipt(answer: &Value) -> String {    match answer["imported"].as_i64().unwrap_or_default() {        0 => "Nothing new — this chat was already here.".into(),        1 => "1 message added".into(),        count => format!("{count} messages added"),    }}fn media_receipt(media: &Value) -> Option<String> {    let copied = media["copied"].as_i64().unwrap_or_default();    let omitted = media["omitted"].as_i64().unwrap_or_default();    let mut parts = Vec::new();    if copied > 0 {        parts.push(if copied == 1 {            "1 picture or file copied".into()        } else {            format!("{copied} pictures and files copied")        });    }    if omitted > 0 {        parts.push(if omitted == 1 {            "1 was not in the export".into()        } else {            format!("{omitted} were not in the export")        });    }    (!parts.is_empty()).then(|| parts.join("; "))}#[cfg(test)]mod tests {    use super::*;    /// RULE: An export import uses a supplied or recorded zone and refuses an absent or unknown one, so no machine clock or timezone default changes imported message stamps.    #[test]    fn import_offset_requires_a_known_zone_and_respects_its_offset() {        let at = chrono::DateTime::parse_from_rfc3339("2026-03-08T10:05:00Z").unwrap().timestamp_millis();        assert!(offset_for(None, at).is_err());        assert!(offset_for(Some("invented/zone"), at).is_err());        assert_eq!(offset_for(Some("Asia/Kathmandu"), at).unwrap(), "+05:45");        assert_eq!(offset_for(Some("America/Los_Angeles"), at).unwrap(), "-07:00");    }    /// RULE: Claiming a held export is atomic, so two commands cannot import its staged bytes twice.    #[test]    fn atomic_claim_blocks_a_second_run_while_the_first_is_in_flight() {        let mut run = Run {            id: "one".into(),            path: "/tmp/a.txt".into(),            origin_path: "/tmp/a.txt".into(),            stage_dir: PathBuf::from("/tmp/stage"),            name: "Chat.txt".into(),            source: None,            state: State::Choosing,        };        claim_run(&mut run, Some(Source::WhatsApp), None).expect("the first run claims the export");        assert!(matches!(run.state, State::Running));        let duplicate = claim_run(&mut run, Some(Source::WhatsApp), None)            .expect_err("a concurrent run must be refused");        assert_eq!(duplicate.code, "already_importing");    }    /// RULE: A completed import is terminal, while a failed one retains exactly its prior source for retry.    #[test]    fn completed_or_failed_claims_cannot_duplicate_a_completed_import() {        let mut completed = Run {            id: "one".into(),            path: "/tmp/a.txt".into(),            origin_path: "/tmp/a.txt".into(),            stage_dir: PathBuf::from("/tmp/stage"),            name: "Chat.txt".into(),            source: Some(Source::WhatsApp),            state: State::Completed(json!({"imported":1})),        };        assert_eq!(            claim_run(&mut completed, None, None)                .expect_err("completed is terminal")                .code,            "not_offered"        );        let mut failed = Run {            id: "two".into(),            path: "/tmp/b.txt".into(),            origin_path: "/tmp/b.txt".into(),            stage_dir: PathBuf::from("/tmp/stage"),            name: "Chat.txt".into(),            source: Some(Source::WhatsApp),            state: State::Failed("could not read".into()),        };        claim_run(&mut failed, None, None).expect("a failed run keeps its source for one retry");        assert!(matches!(failed.state, State::Running));    }    /// RULE: A completion never offers a second native import for the same held record.    #[test]    fn completed_import_never_offers_or_runs_a_second_import() {        let run = Run {            id: "one".into(),            path: "/tmp/a.txt".into(),            origin_path: "/tmp/a.txt".into(),            stage_dir: PathBuf::from("/tmp/stage"),            name: "Chat.txt".into(),            source: Some(Source::WhatsApp),            state: State::Completed(json!({"imported":1})),        };        assert_eq!(receipt(&run), "1 message added");        assert!(            matches!(run.state, State::Completed(_)),            "a completed held run has no retry transition"        );    }    /// RULE: One selected capability can have only one held import in its database scope.    #[test]    fn duplicate_staged_path_is_detected_before_an_import_runs() {        let held = vec![Run {            id: "one".into(),            path: "/tmp/a.txt".into(),            origin_path: "/tmp/a.txt".into(),            stage_dir: PathBuf::from("/tmp/stage"),            name: String::new(),            source: None,            state: State::Choosing,        }];        assert!(            holds_origin(&held, "/tmp/a.txt"),            "the create guard refuses a second held run for one staged capability"        );        assert!(            !holds_origin(&held, "/tmp/other.txt"),            "a different capability remains independently importable"        );    }    /// RULE: A run created in one held database is never readable or actionable in another.    #[test]    fn held_runs_are_partitioned_by_database_before_any_record_lookup() {        let base = PathBuf::from("/tmp/cotton");        let mine = Scope {            data_dir: base.clone(),            database: "mine".into(),        };        let project = Scope {            data_dir: base,            database: "project".into(),        };        let mut all: HashMap<Scope, Vec<Run>> = HashMap::new();        all.insert(mine, vec![]);        assert!(all.contains_key(&Scope {            data_dir: PathBuf::from("/tmp/cotton"),            database: "mine".into()        }));        assert!(            !all.contains_key(&project),            "a run created in Mine is never visible on a project page"        );    }    /// RULE: A forged sender value never reaches the importer, even if a client bypasses its picker.    #[test]    fn owner_transition_accepts_only_the_importers_exact_sender_choice() {        let senders = vec!["Ada".to_owned(), "Bea".to_owned()];        assert!(sender_is_offered(&senders, "Ada"));        assert!(            !sender_is_offered(&senders, "Mallory"),            "a forged picker value never runs an import"        );        assert!(            !sender_is_offered(&senders, ""),            "an empty picker value never runs an import"        );    }    /// RULE: Only WhatsApp selects a native importer; Instagram's export is refused in words since Instagram left (22 Nov 2026).    #[test]    fn run_source_is_closed_before_the_held_state_changes() {        assert!(source(&json!({"source":"whatsapp"})).is_ok());        assert!(source(&json!({"source":"instagram"})).is_err());        assert!(            source(&json!({"source":"telegram"})).is_err(),            "a source outside the declared commands never reaches an importer"        );    }    /// RULE: The importer reads a Cotton-owned copy, so closing the picker or changing the original cannot change a held run; missing and directory capabilities refuse.    #[test]    fn staging_copies_a_regular_file_and_refuses_nonfiles() {        let temp = tempfile::tempdir().expect("temporary data directory");        let original = temp.path().join("selected.txt");        std::fs::write(&original, "before").expect("selected file");        let (staged, stage_dir) =            stage_file(temp.path(), "run-1", &original, "Chat.txt").expect("staged copy");        std::fs::write(&original, "after").expect("original may change after picker closes");        assert_eq!(std::fs::read_to_string(&staged).unwrap(), "before");        assert_eq!(stage_dir, temp.path().join("tmp/message-imports/run-1"));        assert_eq!(            stage_file(                temp.path(),                "missing",                &temp.path().join("none.txt"),                "none.txt"            )            .unwrap_err()            .code,            "unreadable"        );        assert_eq!(            stage_file(temp.path(), "folder", temp.path(), "folder")                .unwrap_err()                .code,            "bad_request"        );    }    /// RULE: A row never displays a sandbox path as the export's name.    #[test]    fn file_name_is_a_leaf_and_never_a_path_in_the_row() {        assert_eq!(            title("/private/stage/WhatsApp Chat - Ada.txt"),            "WhatsApp Chat - Ada"        );        assert_eq!(title(""), "Export");    }}