Cotton code
253 lines · 10.9 KB · RustRaw
//! THE MERGE PROOF ON A COPY (lane mergefix, 21 Oct 2026): on a copy of a//! real file — `COTTON_PROOF_FILE=<copy> cargo test -p cotton-tools --test//! merge_proof_on_copy -- --ignored --nocapture` — or, without one, on a//! synthetic file holding the same kinds of rows://!   1. count the rows a move left past their receipts (person handles with no//!      create kept; money rows with no create, or whose receipts say another//!      status than the row);//!   2. merge a synthetic duplicate into a person holding such handles, merge//!      such a person into a synthetic survivor, and update one such money//!      row: every handle present, every status unchanged, the creates minted;//!   3. merge again: a no-op on handles.//! Only synthetic people are made; no real value is printed — counts only.mod support;use cotton_store::receipts;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::Harness;use support::mcp::call_tool_in_prepared_file;fn strings(h: &Harness, sql: &str, params: &[SqlValue]) -> Vec<String> {    h.db.all(sql, params)        .expect("the read runs")        .iter()        .filter_map(|row| row.text("v").map(str::to_string))        .collect()}/// Handles with no create receipt kept.fn receiptless_handles(h: &Harness) -> Vec<String> {    strings(        h,        "SELECT id AS v FROM cotton_person_handles AS t WHERE NOT EXISTS (SELECT 1 FROM _writes AS w \         WHERE w.tbl = 'cotton_person_handles' AND w.row_id = t.id AND (w.kind IS NULL OR w.kind = 'create'))",        &[],    )}/// Money rows with no create kept, or whose receipts say another status.fn moved_money(h: &Harness) -> (Vec<String>, Vec<String>) {    let mut receiptless = Vec::new();    let mut stale = Vec::new();    for row in h.db.all("SELECT id, status FROM cotton_money_transactions", &[]).expect("the read") {        let id = row.text("id").unwrap_or_default().to_string();        let held = row.text("status").unwrap_or_default().to_string();        let stored = receipts::of_row(&h.db, "cotton_money_transactions", &id).expect("receipts");        let t = receipts::retract_stamp(&h.db, "cotton_money_transactions", &id).expect("retract");        let life = receipts::assemble("cotton_money_transactions", &stored, t.as_deref());        if !life.live {            receiptless.push(id);        } else if life.fields.get("status").and_then(|c| c.value.as_str()).is_some_and(|says| says != held) {            stale.push(id);        }    }    (receiptless, stale)}fn handles_of(h: &Harness, person: &str) -> Vec<String> {    let mut ids = strings(        h,        "SELECT id AS v FROM cotton_person_handles WHERE person_id = ?",        &[SqlValue::Text(person.to_string())],    );    ids.sort();    ids}fn has_create(h: &Harness, table: &str, id: &str) -> bool {    !strings(        h,        "SELECT kind AS v FROM _writes WHERE tbl = ? AND row_id = ? AND kind = 'create'",        &[SqlValue::Text(table.to_string()), SqlValue::Text(id.to_string())],    )    .is_empty()}fn call(h: &Harness, secret: &str, tool: &str, args: Value) -> Value {    let answer = call_tool_in_prepared_file(h, secret, tool, args);    assert!(!answer.is_error, "{tool} refused: {}", answer.text);    serde_json::from_str(&answer.text).expect("json")}fn person_of(h: &Harness, handle: &str) -> String {    strings(h, "SELECT person_id AS v FROM cotton_person_handles WHERE id = ?", &[SqlValue::Text(handle.to_string())])        .pop()        .expect("the handle's person")}fn prove(h: &Harness) {    let secret = h.connect(&["read", "write"], "mergefix-proof");    // 1. The counts.    let handles = receiptless_handles(h);    let (money_receiptless, money_stale) = moved_money(h);    println!(        "PROOF counts: receipt-less handles {}, receipt-less money rows {}, money rows whose receipts say another status {}",        handles.len(),        money_receiptless.len(),        money_stale.len()    );    let total_handles_before = h.count("SELECT COUNT(*) AS n FROM cotton_person_handles", &[]);    // 2a. A synthetic duplicate merged INTO a person holding receipt-less handles.    let survivor = person_of(h, handles.first().expect("a receipt-less handle to prove on"));    let survivor_before = handles_of(h, &survivor);    let duplicate = call(        h,        &secret,        "create_person",        json!({ "fullName": "Mergefix Proof Duplicate", "phones": ["+1 555 010 9901"] }),    )["id"]        .as_str()        .expect("an id")        .to_string();    let duplicate_handles = handles_of(h, &duplicate);    call(h, &secret, "merge_people", json!({ "survivorId": survivor, "duplicateId": duplicate }));    let mut expected = [survivor_before.clone(), duplicate_handles].concat();    expected.sort();    assert_eq!(handles_of(h, &survivor), expected, "the survivor holds every handle of both");    // 2b. A person holding receipt-less handles merged into a synthetic survivor.    let other = handles        .iter()        .map(|handle| person_of(h, handle))        .find(|person| *person != survivor);    let moved_into = call(h, &secret, "create_person", json!({ "fullName": "Mergefix Proof Survivor" }))["id"]        .as_str()        .expect("an id")        .to_string();    if let Some(other) = &other {        let carried = handles_of(h, other);        call(h, &secret, "merge_people", json!({ "survivorId": moved_into, "duplicateId": other }));        assert_eq!(handles_of(h, &moved_into), carried, "every receipt-less handle moved, none lost");        for handle in &carried {            assert!(has_create(h, "cotton_person_handles", handle), "the moved handle's create was minted");        }        println!("PROOF moved {} receipt-less handle(s) by merge; each holds a minted create", carried.len());    }    // 2c. One moved money row updated: its status unchanged, its receipts true.    let mut proved_money = None;    for id in money_receiptless.iter().chain(money_stale.iter()) {        let status = strings(h, "SELECT status AS v FROM cotton_money_transactions WHERE id = ?", &[SqlValue::Text(id.clone())]);        let answer = call_tool_in_prepared_file(h, &secret, "update_transaction", json!({ "id": id, "notes": "mergefix proof" }));        if answer.is_error {            // A row its own rules refuse to edit (no account, a booked line)            // is left as it was; the next one is tried.            continue;        }        assert_eq!(            strings(h, "SELECT status AS v FROM cotton_money_transactions WHERE id = ?", &[SqlValue::Text(id.clone())]),            status,            "the status is unchanged"        );        assert!(has_create(h, "cotton_money_transactions", id), "the row holds a create");        let (still_receiptless, still_stale) = moved_money(h);        assert!(!still_receiptless.contains(id) && !still_stale.contains(id), "its receipts now say what it holds");        proved_money = Some(if money_receiptless.contains(id) { "receipt-less" } else { "stale-status" });        break;    }    println!("PROOF update_transaction on a moved money row: {}", proved_money.unwrap_or("none editable"));    // 3. A second merge moves no handle.    let before = h.count("SELECT COUNT(*) AS n FROM cotton_person_handles", &[]);    let survivor_now = handles_of(h, &survivor);    let again = call_tool_in_prepared_file(h, &secret, "merge_people", json!({ "survivorId": survivor, "duplicateId": duplicate }));    assert_eq!(handles_of(h, &survivor), survivor_now, "a second merge is a no-op on handles");    assert_eq!(h.count("SELECT COUNT(*) AS n FROM cotton_person_handles", &[]), before);    assert_eq!(        h.count("SELECT COUNT(*) AS n FROM cotton_person_handles", &[]),        total_handles_before + 1,        "no handle anywhere in the file was lost; one synthetic handle was added"    );    println!(        "PROOF second merge {}; handles before {} after {} (+1 synthetic); receipt-less handles left {}",        if again.is_error { "refused" } else { "answered" },        total_handles_before,        before,        receiptless_handles(h).len()    );}/// The rehearsal: a synthetic file holding what the moves left on the Mac —/// handles of two people written past the receipts, a transaction with none,/// and one whose receipt still says its pre-139 status.#[test]fn rehearsal_on_a_synthetic_file() {    if std::env::var("COTTON_PROOF_FILE").is_ok() {        return;    }    let h = Harness::new();    let at = "2026-08-22T10:00:00.000Z";    let secret = h.connect(&["read", "write"], "mergefix-seed");    let mut people = Vec::new();    for name in ["Proof Person One", "Proof Person Two"] {        people.push(call(&h, &secret, "create_person", json!({ "fullName": name }))["id"].as_str().expect("id").to_string());    }    for (n, (person, kind, value)) in [        (&people[0], "phone", "15550101001"),        (&people[0], "email", "one@proof.example"),        (&people[1], "phone", "15550101002"),    ]    .into_iter()    .enumerate()    {        h.db.run(            "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, position, \             created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'contacts', 0, ?, ?)",            &[                SqlValue::Text(format!("proof-handle-{n}")),                SqlValue::Text(h.workspace_id.clone()),                SqlValue::Text(person.clone()),                SqlValue::Text(kind.into()),                SqlValue::Text(value.into()),                SqlValue::Text(value.into()),                SqlValue::Text(at.into()),                SqlValue::Text(at.into()),            ],        )        .expect("a carried handle");    }    h.db.run(        "INSERT INTO cotton_money_transactions (id, workspace_id, occurred_on, for_period, moves_money, amount_minor, currency, status, \         counterparty_person_id, created_at, updated_at) VALUES ('7a1e0000-0000-4000-8000-00000000f001', ?, '2026-09-01', '2026-09', 0, 500, 'INR', 'actual', ?, ?, ?)",        &[            SqlValue::Text(h.workspace_id.clone()),            SqlValue::Text(people[0].clone()),            SqlValue::Text(at.into()),            SqlValue::Text(at.into()),        ],    )    .expect("a carried transaction");    prove(&h);}#[test]#[ignore = "runs on a copy named by COTTON_PROOF_FILE"]fn proof_on_a_copy() {    let path = std::env::var("COTTON_PROOF_FILE").expect("COTTON_PROOF_FILE names a COPY");    assert!(        !path.contains("/CottonDB/") && !path.contains("Application Support/CottonDB"),        "never the real data folder, only a copy"    );    // The copy is evidence: the whole proof runs in one transaction that is    // rolled back, so the file is left byte for byte as it came.    let h = Harness::open_copy(&path);    let rolled_back = h.db.transaction(|_| -> cotton_store::Result<()> {        prove(&h);        Err(cotton_store::StoreError::refused("the proof is rolled back"))    });    assert!(rolled_back.is_err());}