Cotton code
695 lines · 25.6 KB · RustRaw
//! `submit_statement_reading`: the assistant read the paper in its own session;//! the server does everything it does after its own read — the check, the//! account, the recording, the meaning pass — from the reading handed in.//!//! Five things this tool gets wrong if nobody pins them: it must run the whole//! pipeline (not a second copy of it), it must record NOTHING on a mismatch and//! hand the numbers back, a contract failure must name the field and never the//! value, a second submission over recorded entries must add nothing twice,//! and it must never reach for the model reader.//!//! ALL FIVE ARE ASSERTED HERE.//!//! `never touches the pages or the model reader` is structural rather than//! spied: `run_statement` here has no reader dependency to reach for.//!//! Every case drives the tool through `dispatch::call_tool` over a fake//! `ToolServices`, where the TypeScript calls `submitStatementReading(ctx, …)`//! in-process — the same request, one more contract under test.mod support;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, 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 sentence the worker leaves on a statement it cannot read itself.////// `AWAITING_READING_REASON` in `packages/server/src/workers/statements.ts`,/// whose permanent home is the worker slice (2f). Copied as a LITERAL rather/// than imported, because there is nothing to import it from yet — and the case/// below is about clearing whatever sentence is there, not about this wording.const AWAITING_READING_REASON: &str =    "waiting for a reading — no key of the owner's is configured on this server";const CLEAN_PDF: &[u8] = include_bytes!("fixtures/statement_visual_clean.pdf");const DECOY_PDF: &[u8] = include_bytes!("fixtures/statement_visual_decoy.pdf");// ── the fixture ─────────────────────────────────────────────────────────────fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}fn run(h: &Harness, sql: &str, params: Vec<SqlValue>) {    h.with(|db| db.run(sql, &params)).expect("the write runs");}fn maybe_one(h: &Harness, sql: &str, params: Vec<SqlValue>) -> Option<cotton_store::driver::Row> {    h.with(|db| db.get(sql, &params)).expect("the read runs")}fn one(h: &Harness, sql: &str, params: Vec<SqlValue>) -> cotton_store::driver::Row {    maybe_one(h, sql, params).expect("the row is there")}fn count(h: &Harness, sql: &str) -> i64 {    one(h, sql, vec![text(&h.workspace_id)])        .int("n")        .unwrap_or(-1)}fn transactions_in(h: &Harness) -> i64 {    count(        h,        "SELECT COUNT(*) AS n FROM cotton_money_transactions WHERE workspace_id = ?",    )}fn statement_lines(h: &Harness, statement_id: &str) -> Vec<cotton_store::driver::Row> {    h.with(|db| {        db.all(            "SELECT id, text FROM cotton_money_statement_lines WHERE statement_id = ? \             ORDER BY line_no",            &[text(statement_id)],        )    })    .expect("the read runs")}/// The `meridian-savings-2026-03` fixture's header.fn meridian_header() -> Value {    json!({        "institution": "Meridian Bank",        "number_mask": "4417",        "kind": "bank",        "period_start": "2026-03-01",        "period_end": "2026-03-31",        "opening_balance_minor": 12_045_000,        "closing_balance_minor": 10_520_000,        "currency": "INR",        "account_name": "Meridian savings",    })}/// The same fixture's six printed lines, in printed order.fn meridian_lines() -> Vec<Value> {    vec![        json!({ "page": 1, "posted_on": "2026-03-01", "text": "OPENING BALANCE", "amount_minor": 12_045_000, "direction": "in", "balance_after_minor": 12_045_000, "reference": null, "ignored_reason": "opening balance row" }),        json!({ "page": 1, "posted_on": "2026-03-03", "text": "UPI/ALDER GROCERS/402213", "amount_minor": 245_000, "direction": "out", "balance_after_minor": 11_800_000, "reference": "402213", "ignored_reason": null }),        json!({ "page": 1, "posted_on": "2026-03-07", "text": "NEFT/BRIGHTPATH LABS/SALARY", "amount_minor": 4_500_000, "direction": "in", "balance_after_minor": 16_300_000, "reference": null, "ignored_reason": null }),        json!({ "page": 1, "posted_on": "2026-03-12", "text": "IMPS/KESTREL BANK CARD 8802", "amount_minor": 1_280_000, "direction": "out", "balance_after_minor": 15_020_000, "reference": null, "ignored_reason": null }),        json!({ "page": 2, "posted_on": "2026-03-19", "text": "UPI/QUILL STATIONERS/771004", "amount_minor": 100_000, "direction": "out", "balance_after_minor": 14_920_000, "reference": "771004", "ignored_reason": null }),        json!({ "page": 2, "posted_on": "2026-03-26", "text": "ACH/HARBOUR RENT", "amount_minor": 4_400_000, "direction": "out", "balance_after_minor": 10_520_000, "reference": null, "ignored_reason": null }),    ]}/// RULE: The default test paper has recorded figures independent of the candidate, so an unbound test double cannot bless a changed amount (18 Oct 2026, headless_seed red on 8455).#[test]fn default_fixture_never_echoes_a_changed_candidate() {    use cotton_tools::mcp::handlers::money::{engine_shim::parse_read_output, statement_visual_check::{verify_visual_facts, visual_facts_from_output}};    let renderer = support::fakes::FakeStatementVisual::new();    let reading = parse_read_output(&meridian_header(), &json!(meridian_lines())).unwrap();    let mut candidate = visual_facts_from_output(&reading);    assert!(verify_visual_facts(Some(renderer.as_ref()), "fixture-db", "fixture-statement", &candidate).is_ok());    candidate.lines[1].amount_minor += 1;    assert!(verify_visual_facts(Some(renderer.as_ref()), "fixture-db", "fixture-statement", &candidate).is_err());}/// The first reading loses the rent line, so the closing balance is wrong.fn broken_lines() -> Vec<Value> {    let mut lines = meridian_lines();    lines.truncate(5);    lines}/// One filed bank statement — the paper, and two pages of text on it.fn seed_statement_document(h: &Harness, label: &str) -> String {    let document_id = synthetic_uuid(label);    run(        h,        "INSERT INTO cotton_documents \           (id, workspace_id, original_name, mime, byte_size, sha256, storage_path, source, \            status, status_changed_at, doc_type, text_extracted, created_at, updated_at) \         VALUES (?, ?, 'march.pdf', 'application/pdf', 1024, ?, ?, 'app', 'ready', ?, \                 'bank_statement', 1, ?, ?)",        vec![            text(&document_id),            text(&h.workspace_id),            text(&document_id.replace('-', "").repeat(2)),            text(&format!("{}/{document_id}/original.pdf", h.workspace_id)),            text(AT),            text(AT),            text(AT),        ],    );    for page in 1..=2 {        run(            h,            "INSERT INTO cotton_document_pages (id, workspace_id, document_id, page, text, created_at) \             VALUES (?, ?, ?, ?, ?, ?)",            vec![                text(&synthetic_uuid(&format!("{label}-page-{page}"))),                text(&h.workspace_id),                text(&document_id),                SqlValue::Integer(page),                text(&format!("MERIDIAN BANK — page {page}")),                text(AT),            ],        );    }    document_id}struct Pending {    h: Harness,    secret: String,    statement_id: String,    document_id: String,}/// A filed statement, marked pending, with nothing read off it yet.////// The TypeScript reaches for `ensurePendingStatement` in-process; here the/// tool that mints the row does it, which is `read_statement` — the same writer/// this port's `ensure_pending_statement` serves.fn pending_statement(label: &str) -> Pending {    pending_on(Harness::new(), label)}fn pending_on(h: Harness, label: &str) -> Pending {    let mut h = h;    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let document_id = seed_statement_document(&h, label);    let answer = call_tool(        &h,        &secret,        "read_statement",        json!({ "documentId": document_id }),    );    let statement_id = answer["statementId"]        .as_str()        .expect("a statement id came back")        .to_string();    Pending {        h,        secret,        statement_id,        document_id,    }}// ── submit_statement_reading ────────────────────────────────────────────────/// RULE: A PDF text layer can be a decoy, so a rendered page disagreement/// names its page and creates no account, line, or money row.#[test]fn decoy_pdf_text_layer_is_refused_before_any_money_is_written() {    let p = pending_statement("visual-decoy");    assert!(DECOY_PDF.starts_with(b"%PDF-"), "fixture is a PDF");    p.h.services.statement_visual.fixture_for(&p.statement_id, DECOY_PDF);    let refused = call_tool_raw(        &p.h,        &p.secret,        "submit_statement_reading",        json!({ "statementId": p.statement_id, "header": meridian_header(), "lines": meridian_lines() }),    );    assert!(refused.is_error);    assert!(refused.text.contains("page 2 amount"), "{}", refused.text);    assert_eq!(transactions_in(&p.h), 0);    assert_eq!(statement_lines(&p.h, &p.statement_id).len(), 0);    assert_eq!(count(&p.h, "SELECT COUNT(*) AS n FROM cotton_money_accounts WHERE workspace_id = ?"), 0);    let statement = one(&p.h, "SELECT read_error FROM cotton_money_statements WHERE id = ?", vec![text(&p.statement_id)]);    let reason: Value = serde_json::from_str(statement.text("read_error").unwrap()).unwrap();    assert_eq!(reason, json!({"code":"visual_mismatch","field":"amount","page":2}));}/// RULE: A host without a page renderer must never book from text alone: it rests with visual_unavailable (18 Oct 2026, headless_seed red on 8455); synthetic tests supply fixture readings, never weaken this refusal.#[test]fn unavailable_visual_verifier_refuses_and_leaves_a_typed_rest_reason() {    let mut p = pending_statement("visual-unavailable");    p.h.services.services.statement_visual = None;    let refused = call_tool_raw(        &p.h,        &p.secret,        "submit_statement_reading",        json!({ "statementId": p.statement_id, "header": meridian_header(), "lines": meridian_lines() }),    );    assert!(refused.is_error);    assert!(refused.text.contains("cannot verify the rendered statement pages"));    assert_eq!(transactions_in(&p.h), 0);    let statement = one(&p.h, "SELECT read_status, read_error FROM cotton_money_statements WHERE id = ?", vec![text(&p.statement_id)]);    assert_eq!(statement.text("read_status"), Some("failed"));    assert_eq!(statement.text("read_error"), Some(r#"{"code":"visual_unavailable"}"#));}/// RULE: A statement's own totals must agree before anything from it is recorded.#[test]fn records_nothing_on_a_mismatch_saves_the_lines_and_answers_with_the_numbers() {    let p = pending_statement("submit-mismatch");    let paper = cotton_tools::mcp::handlers::money::engine_shim::parse_read_output(&meridian_header(), &json!(broken_lines())).unwrap();    p.h.services.statement_visual.recording_for(&p.statement_id, cotton_tools::mcp::handlers::money::statement_visual_check::visual_facts_from_output(&paper));    let answer = call_tool(        &p.h,        &p.secret,        "submit_statement_reading",        json!({            "statementId": p.statement_id,            "header": meridian_header(),            "lines": broken_lines(),            "readBy": "assistant",        }),    );    assert_eq!(answer["readStatus"], json!("mismatch"));    assert_eq!(        answer["transactions"],        json!({ "actual": 0, "alreadyBooked": 0 })    );    assert_eq!(        answer["lines"],        json!({ "read": 5, "booked": 0, "ignored": 1 })    );    // Printed 1,05,200.00; the five lines add up to 1,49,200.00 — the rent is    // what is missing, and the running balance agrees up to the last line read.    assert_eq!(        answer["discrepancy"],        json!({            "statedClosingMinor": 10_520_000,            "expectedClosingMinor": 14_920_000,            "sumInMinor": 4_500_000,            "sumOutMinor": 1_625_000,            "firstBreakLineNo": Value::Null,        })    );    let note = answer["note"].as_str().expect("a note came back");    assert!(        note.to_lowercase().contains("nothing was recorded"),        "{note}"    );    assert!(note.contains("₹1,05,200"), "{note}");    assert!(note.contains("₹1,49,200"), "{note}");    assert!(note.contains("submit_statement_reading again"), "{note}");    let statement = one(        &p.h,        "SELECT read_status, balance_check FROM cotton_money_statements WHERE id = ?",        vec![text(&p.statement_id)],    );    assert_eq!(statement.text("read_status"), Some("mismatch"));    assert_eq!(statement.text("balance_check"), Some("mismatch"));    assert_eq!(statement_lines(&p.h, &p.statement_id).len(), 5);    assert_eq!(transactions_in(&p.h), 0);    // The re-read is the caller's: the corrected reading lands on the SAME    // account and records the lot.    p.h.services.statement_visual.fixture_for(&p.statement_id, CLEAN_PDF);    let again = call_tool(        &p.h,        &p.secret,        "submit_statement_reading",        json!({            "statementId": p.statement_id,            "header": meridian_header(),            "lines": meridian_lines(),            "readBy": "assistant",        }),    );    assert_eq!(again["readStatus"], json!("read"));    assert_eq!(        again["transactions"],        json!({ "actual": 5, "alreadyBooked": 0 })    );    assert_eq!(again["account"]["id"], answer["account"]["id"]);    assert_eq!(again["account"]["created"], json!(false));}#[test]fn refuses_a_reading_that_breaks_the_contract_by_field_never_by_value() {    // …and touches no row.    let p = pending_statement("submit-contract");    let mut line = meridian_lines()[1]        .as_object()        .expect("a line is an object")        .clone();    line.insert(        "direction".to_string(),        Value::from("PAID-QUILL-STATIONERS-771004"),    );    let answer = call_tool_raw(        &p.h,        &p.secret,        "submit_statement_reading",        json!({            "statementId": p.statement_id,            "header": meridian_header(),            "lines": [Value::Object(line)],        }),    );    assert!(answer.is_error, "{}", answer.text);    assert!(        answer.text.contains(            "the statement reading did not match the contract: lines[0].direction: expected one \             of in | out"        ),        "{}",        answer.text    );    assert!(!answer.text.contains("QUILL"), "{}", answer.text);    assert!(!answer.text.contains("771004"), "{}", answer.text);    // A refused reading is the assistant's to fix — the row is exactly as it    // was.    let statement = one(        &p.h,        "SELECT read_status, read_error FROM cotton_money_statements WHERE id = ?",        vec![text(&p.statement_id)],    );    assert_eq!(statement.text("read_status"), Some("pending"));    assert_eq!(statement.text("read_error"), None);    assert!(statement_lines(&p.h, &p.statement_id).is_empty());}#[test]fn adds_nothing_twice_when_the_same_reading_is_submitted_over_recorded_entries() {    let p = pending_statement("submit-twice");    let reading = json!({        "statementId": p.statement_id,        "header": meridian_header(),        "lines": meridian_lines(),        "readBy": "assistant",    });    let first = call_tool(&p.h, &p.secret, "submit_statement_reading", reading.clone());    assert_eq!(first["transactions"]["actual"], json!(5));    let before: Vec<String> = statement_lines(&p.h, &p.statement_id)        .iter()        .filter_map(|row| row.text("id").map(str::to_string))        .collect();    let second = call_tool(&p.h, &p.secret, "submit_statement_reading", reading);    assert_eq!(second["readStatus"], json!("read"));    // Every entry already had its record: nothing posted, five recognised as    // already there.    assert_eq!(        second["transactions"],        json!({ "actual": 0, "alreadyBooked": 5 })    );    assert_eq!(        second["lines"],        json!({ "read": 6, "booked": 5, "ignored": 1 })    );    assert_eq!(transactions_in(&p.h), 5);    // Same rows, same ids — a recorded line is never deleted and re-minted.    let after: Vec<String> = statement_lines(&p.h, &p.statement_id)        .iter()        .filter_map(|row| row.text("id").map(str::to_string))        .collect();    assert_eq!(after, before);}#[test]fn keeps_a_recorded_entrys_content_when_a_second_reading_says_otherwise_about_it() {    let p = pending_statement("submit-respelt");    call_tool(        &p.h,        &p.secret,        "submit_statement_reading",        json!({            "statementId": p.statement_id,            "header": meridian_header(),            "lines": meridian_lines(),            "readBy": "assistant",        }),    );    let grocer = statement_lines(&p.h, &p.statement_id)        .into_iter()        .find(|row| {            row.text("text")                .is_some_and(|value| value.contains("ALDER GROCERS"))        })        .expect("the grocer's line is there")        .text("id")        .expect("it has an id")        .to_string();    // The second reading re-spells the grocer's line. Its transaction was    // posted from the first words, so the row keeps them; the re-spelt line is    // a NEW row beside it, and the totals no longer agree — nothing more is    // recorded.    let respelt: Vec<Value> = meridian_lines()        .into_iter()        .map(|line| {            let mut line = line.as_object().expect("a line is an object").clone();            if line["text"]                .as_str()                .is_some_and(|value| value.contains("ALDER GROCERS"))            {                line.insert(                    "text".to_string(),                    Value::from("UPI/ALDER GROCERS LTD/402213"),                );            }            Value::Object(line)        })        .collect();    let answer = call_tool(        &p.h,        &p.secret,        "submit_statement_reading",        json!({            "statementId": p.statement_id,            "header": meridian_header(),            "lines": respelt,            "readBy": "assistant",        }),    );    assert_eq!(answer["readStatus"], json!("mismatch"));    assert_eq!(transactions_in(&p.h), 5);    let kept = one(        &p.h,        "SELECT text FROM cotton_money_statement_lines WHERE id = ?",        vec![text(&grocer)],    );    assert_eq!(kept.text("text"), Some("UPI/ALDER GROCERS/402213"));}#[test]fn runs_the_whole_reading_as_one_pass() {    let p = pending_statement("submit-slot");    let answer = call_tool(        &p.h,        &p.secret,        "submit_statement_reading",        json!({            "statementId": p.statement_id,            "header": meridian_header(),            "lines": meridian_lines(),            "readBy": "assistant",        }),    );    assert_eq!(answer["readStatus"], json!("read"));    assert_eq!(transactions_in(&p.h), 5);}#[test]fn mints_the_pending_row_when_given_a_document_id_exactly_as_read_statement_does() {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let document_id = seed_statement_document(&h, "submit-by-document");    let answer = call_tool(        &h,        &secret,        "submit_statement_reading",        json!({            "documentId": document_id,            "header": meridian_header(),            "lines": meridian_lines(),        }),    );    assert_eq!(answer["readStatus"], json!("read"));    let statement_id = answer["statementId"]        .as_str()        .expect("a statement id came back")        .to_string();    let statement = one(        &h,        "SELECT document_id, read_by FROM cotton_money_statements WHERE id = ?",        vec![text(&statement_id)],    );    assert_eq!(statement.text("document_id"), Some(document_id.as_str()));    // The default label, when the caller gave none.    assert_eq!(statement.text("read_by"), Some("assistant"));    // And read_statement on the same document reaches the same statement.    let same = call_tool(        &h,        &secret,        "read_statement",        json!({ "documentId": document_id }),    );    assert_eq!(same["statementId"], answer["statementId"]);}#[test]fn wants_exactly_one_of_statement_id_and_document_id_and_a_short_read_by() {    let p = pending_statement("submit-validation");    let reading = || -> Map<String, Value> {        json!({ "header": meridian_header(), "lines": meridian_lines() })            .as_object()            .expect("an object")            .clone()    };    let with = |extra: Value| -> Value {        let mut args = reading();        for (key, value) in extra.as_object().expect("an object") {            args.insert(key.clone(), value.clone());        }        Value::Object(args)    };    let both = call_tool_raw(        &p.h,        &p.secret,        "submit_statement_reading",        with(json!({ "statementId": p.statement_id, "documentId": p.document_id })),    );    assert!(both.is_error, "{}", both.text);    assert!(both.text.contains("exactly one"), "{}", both.text);    let neither = call_tool_raw(        &p.h,        &p.secret,        "submit_statement_reading",        Value::Object(reading()),    );    assert!(neither.is_error, "{}", neither.text);    let long = call_tool_raw(        &p.h,        &p.secret,        "submit_statement_reading",        with(json!({ "statementId": p.statement_id, "readBy": "x".repeat(81) })),    );    assert!(long.is_error, "{}", long.text);    assert!(long.text.contains("80"), "{}", long.text);    let not_a_statement = call_tool_raw(        &p.h,        &p.secret,        "submit_statement_reading",        with(json!({ "statementId": NOBODY })),    );    assert!(not_a_statement.is_error, "{}", not_a_statement.text);    assert!(        not_a_statement.text.contains("no statement"),        "{}",        not_a_statement.text    );}#[test]fn reads_a_statement_the_worker_left_waiting_and_clears_the_waiting_sentence() {    let p = pending_statement("submit-waiting");    run(        &p.h,        "UPDATE cotton_money_statements SET read_error = ? WHERE id = ?",        vec![text(AWAITING_READING_REASON), text(&p.statement_id)],    );    call_tool(        &p.h,        &p.secret,        "submit_statement_reading",        json!({            "statementId": p.statement_id,            "header": meridian_header(),            "lines": meridian_lines(),            "readBy": "assistant",        }),    );    let statement = one(        &p.h,        "SELECT read_status, read_error FROM cotton_money_statements WHERE id = ?",        vec![text(&p.statement_id)],    );    assert_eq!(statement.text("read_status"), Some("read"));    assert_eq!(statement.text("read_error"), None);}#[test]fn a_read_only_token_cannot_submit_a_reading() {    let p = pending_statement("submit-readonly");    let mut h = p.h;    let read_only = mint_token(&mut h, &["read"], "Claude");    let answer = call_tool_raw(        &h,        &read_only,        "submit_statement_reading",        json!({            "statementId": p.statement_id,            "header": meridian_header(),            "lines": meridian_lines(),        }),    );    assert!(answer.is_error, "{}", answer.text);    assert!(answer.text.contains("write"), "{}", answer.text);}// ── the statement run with a reading handed in ──────────────────────────────#[test]fn a_submitted_mismatch_uses_recorded_pages_without_a_model_reread() {    // Verification is mandatory; record this test paper's five visible lines    // independently. Its totals disagree, so nothing books and no model is    // asked to repair the assistant's submission. Keep the reader's name.    let p = pending_statement("submit-no-reader");    let paper = cotton_tools::mcp::handlers::money::engine_shim::parse_read_output(&meridian_header(), &json!(broken_lines())).unwrap();    p.h.services.statement_visual.recording_for(&p.statement_id, cotton_tools::mcp::handlers::money::statement_visual_check::visual_facts_from_output(&paper));    let answer = call_tool(        &p.h,        &p.secret,        "submit_statement_reading",        json!({            "statementId": p.statement_id,            "header": meridian_header(),            "lines": broken_lines(),            "readBy": "claude-code session",        }),    );    assert_eq!(answer["readStatus"], json!("mismatch"));    assert_eq!(        answer["discrepancy"]["expectedClosingMinor"],        json!(14_920_000)    );    let statement = one(        &p.h,        "SELECT read_by FROM cotton_money_statements WHERE id = ?",        vec![text(&p.statement_id)],    );    assert_eq!(statement.text("read_by"), Some("claude-code session"));}#[test]fn read_statement_points_at_this_tool() {    let p = pending_statement("submit-server-reads");    let answer = call_tool(        &p.h,        &p.secret,        "read_statement",        json!({ "documentId": p.document_id }),    );    let note = answer["note"].as_str().expect("a note came back");    assert!(note.contains("submit_statement_reading"), "{note}");}