Cotton code
444 lines · 15.7 KB · RustRaw
//! Evidence, meaning, the chart and the audit — over `dispatch::call_tool`.//!//! Every case drives the tool through `dispatch::call_tool` over a fake//! `ToolServices` rather than the `/v1/mcp` endpoint, so the validators, the//! dispatch arm and the handler are all under test together: a tool that works//! when its handler is called directly and refuses at the envelope is the bug//! this suite exists to catch.//!//! The TypeScript's fixture builds its rows through `ensureUnaccountedAccount`//! / `createMoneyAccountRow` / `postDraft` — server-side writers it can reach//! in-process. This suite seeds the SAME shape through the fold a phone's push//! runs, which needs no handler of its own to be correct first. Every//! institution, payee and amount is invented.mod support;use std::sync::atomic::{AtomicU64, Ordering};use cotton_store::schema::ddl::SCHEMA_VERSION;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::{synthetic_uuid, Harness};use support::mcp::{call_tool, call_tool_raw, mint_token};/// When every seeded row says it was written. The TypeScript's `NOW`.const AT: &str = "2026-04-01T09:00:00.000Z";/// A uuid this workspace has never issued.const NOBODY: &str = "00000000-0000-4000-8000-000000000000";// ── the fixture ─────────────────────────────────────────────────────────────/// An op the way a device would mint one. The ids are DERIVED from a/// per-process counter, never random.fn op(table: &str, row_id: &str, patch: Value) -> Value {    static NEXT: AtomicU64 = AtomicU64::new(0);    let n = NEXT.fetch_add(1, Ordering::Relaxed);    json!({        "opId": format!("01J{:023}", n),        "deviceId": "device:seed",        "kind": "upsert",        "table": table,        "rowId": row_id,        "patch": patch,        "hlc": format!("1700000000{:03}:0000:device:seed", n),        "schemaVersion": SCHEMA_VERSION,    })}/// Every row one column of one table, read off the file itself.fn one(h: &Harness, sql: &str, id: &str) -> Option<cotton_store::driver::Row> {    h.with(|db| db.get(sql, &[SqlValue::Text(id.to_string())]))        .expect("the read runs")}fn all(h: &Harness, sql: &str, id: &str) -> Vec<cotton_store::driver::Row> {    h.with(|db| db.all(sql, &[SqlValue::Text(id.to_string())]))        .expect("the read runs")}struct Spend {    h: Harness,    secret: String,    transaction_id: String,}fn unaccounted_spend() -> Spend {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let transaction_id = synthetic_uuid("meaning-transaction");    h.run("INSERT INTO cotton_money_transactions (id,workspace_id,occurred_on,status,amount_minor,amount_known,direction,currency,created_at,updated_at) VALUES (?,?,'2026-03-03','actual',245000,1,'out','INR',?,?)",&[SqlValue::Text(transaction_id.clone()),SqlValue::Text(h.workspace_id.clone()),SqlValue::Text(AT.into()),SqlValue::Text(AT.into())]);    Spend {        h,        secret,        transaction_id,    }}fn seed_statement_line(spend: &Spend) -> String {    let workspace_id = spend.h.workspace_id.clone();    let document_id = synthetic_uuid("meaning-doc");    let statement_id = synthetic_uuid("meaning-statement");    let line_id = synthetic_uuid("meaning-statement-line");    let ops = vec![        op(            "cotton_documents",            &document_id,            json!({                "workspace_id": workspace_id,                "original_name": "march.pdf",                "mime": "application/pdf",                "byte_size": 1024,                "sha256": document_id.replace('-', "").repeat(2),                "storage_path": format!("{workspace_id}/{document_id}/original.pdf"),                "source": "app",                "status": "ready",                "status_changed_at": AT,                "doc_type": "bank_statement",                "text_extracted": true,                "created_at": AT,                "updated_at": AT,            }),        ),        op(            "cotton_money_statements",            &statement_id,            json!({                "workspace_id": workspace_id,                "document_id": document_id,                "kind": "bank",                "currency": "INR",                "read_status": "read",                "line_count": 1,                "created_at": AT,                "updated_at": AT,            }),        ),        op(            "cotton_money_statement_lines",            &line_id,            json!({                "workspace_id": workspace_id,                "statement_id": statement_id,                "page": 1,                "line_no": 1,                "posted_on": "2026-03-03",                "text": "UPI/ALDER GROCERS",                "amount_minor": 245_000,                "direction": "out",                "fingerprint": format!("stl:{line_id}"),                "created_at": AT,            }),        ),    ];    spend.h.seed(&ops);    line_id}/// One archived email, in its thread.fn seed_email(spend: &Spend) -> String {    let workspace_id = spend.h.workspace_id.clone();    let thread_id = synthetic_uuid("meaning-thread");    let email_id = synthetic_uuid("meaning-email");    let ops = vec![        op(            "cotton_email_threads",            &thread_id,            json!({                "workspace_id": workspace_id,                "external_key": format!("thr:{thread_id}"),                "subject": "Your Alder Grocers receipt",                "first_at": AT,                "last_at": AT,                "email_count": 1,                "created_at": AT,                "updated_at": AT,            }),        ),        op(            "cotton_emails",            &email_id,            json!({                "workspace_id": workspace_id,                "thread_id": thread_id,                "external_id": format!("mid:{email_id}"),                "subject": "Your Alder Grocers receipt",                "from_email": "receipts@alder.example",                "from_name": "Alder Grocers",                "recipients": [],                "sent_at": AT,                "body": "Total 2450.00 on 3 March",                "snippet": "Total 2450.00",                "attachments": [],                "created_at": AT,            }),        ),    ];    spend.h.seed(&ops);    email_id}// ── evidence tools ──────────────────────────────────────────────────────────#[test]fn attach_evidence_records_an_excerpt_and_who_attached_it() {    let spend = unaccounted_spend();    let answer = call_tool(        &spend.h,        &spend.secret,        "attach_evidence",        json!({            "transactionId": spend.transaction_id,            "kind": "external",            "excerpt": "Splitwise: Alder Grocers, 2450.00, 3 Mar",            "sourceLabel": "Splitwise CSV",        }),    );    assert_eq!(answer["attached"], json!(true));    let row = one(        &spend.h,        "SELECT attached_by, attached_by_label FROM cotton_money_evidence WHERE transaction_id = ?",        &spend.transaction_id,    )    .expect("the evidence row is there");    assert_eq!(row.text("attached_by"), Some("assistant"));    assert_eq!(row.text("attached_by_label"), Some("Claude"));}#[test]fn attach_evidence_refuses_a_kind_that_needs_a_ref_id_without_one() {    let spend = unaccounted_spend();    let answer = call_tool_raw(        &spend.h,        &spend.secret,        "attach_evidence",        json!({            "transactionId": spend.transaction_id,            "kind": "document",            "excerpt": "the March statement",        }),    );    assert!(answer.is_error, "{}", answer.text);    assert!(answer.text.contains("refId"), "{}", answer.text);}/// RULE: A statement line proves actual money movement; a forecast or non-moving row must not consume its booking marker and hide the real statement movement.#[test]fn statement_evidence_never_books_a_forecast_or_non_moving_row() {    for (status, certainty, moves) in [("expected", SqlValue::Text("estimate".into()), 1), ("actual", SqlValue::Null, 0)] {        let spend = unaccounted_spend();        let line_id = seed_statement_line(&spend);        spend.h.run("UPDATE cotton_money_transactions SET status=?,certainty=?,moves_money=? WHERE id=?", &[SqlValue::Text(status.into()), certainty, SqlValue::Integer(moves), SqlValue::Text(spend.transaction_id.clone())]);        let answer = call_tool_raw(&spend.h, &spend.secret, "attach_evidence", json!({"transactionId":spend.transaction_id,"kind":"statement_line","refId":line_id,"excerpt":"Synthetic bank movement"}));        assert!(answer.is_error, "{}", answer.text);        assert!(all(&spend.h, "SELECT id FROM cotton_money_evidence WHERE transaction_id=?", &spend.transaction_id).is_empty());    }}#[test]fn attach_evidence_files_a_statement_entry_under_that_entrys_own_id() {    // The positive half of the ref check: a kind that points at a row is    // stored pointing at exactly the row it was given, not at a derived hash.    let spend = unaccounted_spend();    let line_id = seed_statement_line(&spend);    let answer = call_tool(        &spend.h,        &spend.secret,        "attach_evidence",        json!({            "transactionId": spend.transaction_id,            "kind": "statement_line",            "refId": line_id,            "excerpt": "03/03 UPI/ALDER GROCERS 2,450.00",        }),    );    assert_eq!(answer["attached"], json!(true));    let row = one(        &spend.h,        "SELECT kind, ref_id FROM cotton_money_evidence WHERE transaction_id = ?",        &spend.transaction_id,    )    .expect("the evidence row is there");    assert_eq!(row.text("kind"), Some("statement_line"));    assert_eq!(row.text("ref_id"), Some(line_id.as_str()));}#[test]fn attach_evidence_files_an_archived_email_that_is_really_there() {    let spend = unaccounted_spend();    let email_id = seed_email(&spend);    let answer = call_tool(        &spend.h,        &spend.secret,        "attach_evidence",        json!({            "transactionId": spend.transaction_id,            "kind": "email",            "refId": email_id,            "excerpt": "Total 2450.00 on 3 March",        }),    );    assert_eq!(answer["attached"], json!(true));    let row = one(        &spend.h,        "SELECT ref_id FROM cotton_money_evidence WHERE transaction_id = ? AND kind = 'email'",        &spend.transaction_id,    )    .expect("the evidence row is there");    assert_eq!(row.text("ref_id"), Some(email_id.as_str()));}#[test]fn attach_evidence_refuses_a_ref_id_that_points_at_nothing() {    // The table has no foreign key on `ref_id`, so a hallucinated uuid would    // otherwise mark a record verified for ever and take it off the audit's    // unverified list — with nothing anywhere to say what it was verified by.    let spend = unaccounted_spend();    let answer = call_tool_raw(        &spend.h,        &spend.secret,        "attach_evidence",        json!({            "transactionId": spend.transaction_id,            "kind": "document",            "refId": NOBODY,            "excerpt": "the March statement",        }),    );    assert!(answer.is_error, "{}", answer.text);    assert!(answer.text.contains(NOBODY), "{}", answer.text);    assert!(answer.text.contains("document"), "{}", answer.text);    let rows = all(        &spend.h,        "SELECT id FROM cotton_money_evidence WHERE transaction_id = ?",        &spend.transaction_id,    );    assert!(rows.is_empty());}#[test]fn attach_evidence_sent_twice_for_one_external_row_attaches_one_row() {    // Annotated idempotent, so it has to be: the same export re-sent after a    // dropped connection must not double the evidence behind one amount.    let spend = unaccounted_spend();    let args = json!({        "transactionId": spend.transaction_id,        "kind": "external",        "excerpt": "Splitwise: Alder Grocers, 2450.00, 3 Mar",        "sourceLabel": "Splitwise CSV",    });    let first = call_tool(&spend.h, &spend.secret, "attach_evidence", args.clone());    let second = call_tool(&spend.h, &spend.secret, "attach_evidence", args);    assert_eq!(second["id"], first["id"]);    assert_eq!(second["alreadyThere"], json!(true));    let rows = all(        &spend.h,        "SELECT id FROM cotton_money_evidence WHERE transaction_id = ?",        &spend.transaction_id,    );    assert_eq!(rows.len(), 1);}// ── meaning tools ───────────────────────────────────────────────────────────/// RULE: An account keeps its identity through a rename, and a blank name is refused because it cannot identify where money sits.#[test]fn create_and_update_money_account_work_and_a_blank_name_is_refused() {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let made = call_tool(        &h,        &secret,        "create_money_account",        json!({            "name": "Harbour current",            "kind": "bank",            "currency": "INR",            "institution": "Harbour Bank",            "numberMask": "9001",        }),    );    let id = made["id"].as_str().expect("an id came back").to_string();    let renamed = call_tool(        &h,        &secret,        "update_money_account",        json!({ "id": id, "name": "Harbour current account" }),    );    assert_eq!(renamed["name"], json!("Harbour current account"));    let blank = call_tool_raw(        &h,        &secret,        "create_money_account",        json!({ "name": "   ", "kind": "bank", "currency": "INR" }),    );    assert!(blank.is_error, "{}", blank.text);}#[test]fn create_money_account_refuses_an_identity_another_account_already_has() {    // The bank and the last four digits ARE the account. A second row for one    // identity is a balance that is wrong on both halves and obviously wrong    // on neither — and the refusal has to name the account that is already    // there, not hand back the file's constraint text.    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let made = call_tool(        &h,        &secret,        "create_money_account",        json!({            "name": "Harbour current",            "kind": "bank",            "currency": "INR",            "institution": "Harbour Bank",            "numberMask": "9001",        }),    );    let id = made["id"].as_str().expect("an id came back").to_string();    // Lower-case AND a masked number: the institution is folded and the mask    // is reduced to its digits, so neither spelling makes a second account.    let again = call_tool_raw(        &h,        &secret,        "create_money_account",        json!({            "name": "Harbour savings",            "kind": "bank",            "currency": "INR",            "institution": "harbour bank",            "numberMask": "XX9001",        }),    );    assert!(again.is_error, "{}", again.text);    assert!(again.text.contains("Harbour current"), "{}", again.text);    assert!(again.text.contains(&id), "{}", again.text);    assert!(        !again.text.to_lowercase().contains("unique constraint"),        "{}",        again.text    );    let rows = h        .with(|db| {            db.all(                "SELECT id FROM cotton_money_accounts WHERE number_mask = '9001'",                &[],            )        })        .expect("the read runs");    assert_eq!(rows.len(), 1);}