//! The document tools, over `dispatch::call_tool` on a real file with a fake //! `ToolServices` behind it. //! //! What these pin is the part a model depends on: the SHAPE of each answer, and //! the refusals. An assistant reads `alreadyFiled`, `deduped`, `unlocked` and //! `status` to decide what to do next, so a field that quietly changed name //! would break a harvest without breaking a type. //! //! WHAT CHANGES SHAPE, AND WHY. The TypeScript builds a whole documents WORKER //! per harness and parks a real pass inside the model call, because there the //! slot and the pipeline are the same object. Here the tools reach a seam — //! `DocumentsRail` — whose store half this server can fill and whose PIPELINE //! half belongs to the worker slice (2f). So: //! //! * the two SLOT cases script the rail BUSY, which is what a tool sees of //! a pass holding the slot, rather than parking a pass in a model call //! there is no model for; //! * the two PASSWORD RE-RUN cases assert the refusal the rail gives by name //! today, and that nothing half-ran; the unlocked and paywalled outcomes //! belong to the worker that produces them, and are tested with it; //! * "keeps the row when the object cannot be removed" reaches the same //! property through a server with NO object store, which is the strongest //! form of "the bytes could not go": the row is still there afterwards. //! //! Bytes live in the DOCUMENTS rail here, not in the shared object store: the //! server builds one from the other, and in this crate they are two doubles. //! //! Every institution, file name and hash is invented. mod support; use base64::Engine; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use support::fakes::FakeServices; use support::harness::{synthetic_uuid, Harness}; use support::mcp::{call_tool, call_tool_as_owner, call_tool_raw, call_tool_result, mint_token}; /// When every seeded row says it was written. const AT: &str = "2026-08-23T03:00:00.000Z"; /// The bytes every seeded document is made of. const BYTES: &[u8] = b"HARBOUR BANK statement\nClosing balance 12,845.00\n"; // ── the fixture ───────────────────────────────────────────────────────────── fn text(value: &str) -> SqlValue { SqlValue::Text(value.to_string()) } fn run(h: &Harness, sql: &str, params: Vec) { h.run(sql, ¶ms); } fn maybe_one(h: &Harness, sql: &str, params: Vec) -> Option { h.with(|db| db.get(sql, ¶ms)).expect("the read runs") } fn one(h: &Harness, sql: &str, params: Vec) -> cotton_store::driver::Row { maybe_one(h, sql, params).expect("the row is there") } fn document_row(h: &Harness, columns: &str, id: &str) -> Option { maybe_one( h, &format!("SELECT {columns} FROM cotton_documents WHERE id = ?"), vec![text(id)], ) } /// The whole `tools/call` result, not the JSON its text block carries. /// /// `get_document_bytes` answers protocol CONTENT — a resource block and a text /// block beside it — which is the seam `server.rs` passes through untouched, so /// the shared `call_tool` (which parses `content[0].text`) cannot see it. fn call_tool_content(h: &Harness, secret: &str, name: &str, args: Value) -> Value { let result = call_tool_result(h, secret, name, args); assert!(result.is_object(), "no result in {result}"); assert_ne!( result["isError"], Value::Bool(true), "the tool refused: {result}" ); result } struct Filed { id: String, storage_path: String, } /// One filed document, its bytes in the store beside it. fn seed_document(h: &Harness, label: &str, overrides: Value) -> Filed { seed_document_by(h, label, overrides, Harness::run) } /// [`seed_document`], its row written by `write`. fn seed_document_by(h: &Harness, label: &str, overrides: Value, write: fn(&Harness, &str, &[SqlValue])) -> Filed { let id = synthetic_uuid(label); let storage_path = format!("{}/{id}/original.pdf", h.workspace_id); let mut columns: Vec<(String, SqlValue)> = vec![ ("id".into(), text(&id)), ("workspace_id".into(), text(&h.workspace_id)), ("original_name".into(), text("Harbour-Jul2026.pdf")), ("mime".into(), text("application/pdf")), ("byte_size".into(), SqlValue::Integer(4096)), ("sha256".into(), text(&"b".repeat(64))), ("storage_path".into(), text(&storage_path)), ("status".into(), text("ready")), ("doc_type".into(), text("bank_statement")), ("title".into(), text("Harbour savings statement — July 2026")), ("facts".into(), text("{}")), ("source".into(), text("app")), ("text_extracted".into(), SqlValue::Integer(1)), ("status_changed_at".into(), text(AT)), ("created_at".into(), text(AT)), ("updated_at".into(), text(AT)), ]; for (key, value) in overrides.as_object().expect("an object") { let stored = match value { Value::Null => SqlValue::Null, Value::Number(number) => SqlValue::Integer(number.as_i64().unwrap_or(0)), Value::Bool(flag) => SqlValue::Integer(i64::from(*flag)), other => text(other.as_str().unwrap_or_default()), }; match columns.iter_mut().find(|(name, _)| name == key) { Some(slot) => slot.1 = stored, None => columns.push((key.clone(), stored)), } } let names: Vec<&str> = columns.iter().map(|(name, _)| name.as_str()).collect(); let holes = vec!["?"; names.len()].join(", "); write( h, &format!( "INSERT INTO cotton_documents ({}) VALUES ({holes})", names.join(", ") ), &columns.into_iter().map(|(_, value)| value).collect::>(), ); let path = document_row(h, "storage_path", &id) .expect("the document is there") .text("storage_path") .unwrap_or_default() .to_string(); h.services.documents.put(&path, BYTES.to_vec()); Filed { id, storage_path: path, } } fn harness_with(scopes: &[&str]) -> (Harness, String) { let mut h = Harness::new(); let secret = mint_token(&mut h, scopes, "Gmail harvester"); (h, secret) } /// The slot, held by somebody else — which is the whole of what a tool sees of /// a worker pass running: `take_slot` answers `false`. /// /// The real gate is `ObjectStoreDocuments`'s, process-wide and keyed by /// workspace; a server crate holds it by taking it. Here the rail is a double, /// so the same state is scripted, and [`free_the_slot`] is its release. fn hold_the_slot(h: &Harness) { h.services.documents.set_slot_busy(true); } fn free_the_slot(h: &Harness) { h.services.documents.set_slot_busy(false); } /// What a server whose object store carries no reading pipeline answers when a /// password re-run is asked for — `ObjectStoreDocuments::run_password_candidates` /// with `pipeline: None`, verbatim. Scripted here because the pipeline, and the /// rail that composes one, are the worker slice's (2f). const NO_PIPELINE: &str = "Cotton cannot open a locked document on this server yet — its reading \ pipeline is not configured. The document is safe and untouched."; // ── the library ───────────────────────────────────────────────────────────── #[test] fn hands_the_file_itself_through_the_tool_result_as_protocol_content() { let (h, secret) = harness_with(&["read", "write"]); let filed = seed_document(&h, "documents-bytes", json!({})); let result = call_tool_content( &h, &secret, "get_document_bytes", json!({ "documentId": filed.id }), ); // Content blocks, not a JSON object — the seam `server.rs` passes through. let content = result["content"].as_array().expect("content blocks"); assert_eq!(content[0]["type"], json!("resource")); let resource = &content[0]["resource"]; assert_eq!(resource["mimeType"], json!("application/pdf")); assert_eq!( resource["uri"], json!(format!("cotton://documents/{}/file", filed.id)) ); let blob = base64::engine::general_purpose::STANDARD .decode(resource["blob"].as_str().expect("a blob")) .expect("the blob decodes"); assert!(String::from_utf8_lossy(&blob).contains("HARBOUR BANK statement")); let parsed: Value = serde_json::from_str(content[1]["text"].as_str().expect("a text block")).expect("JSON"); assert_eq!(parsed["variant"], json!("original")); assert_eq!(parsed["sha256"], json!("b".repeat(64))); assert_eq!(parsed["fileName"], json!("Harbour-Jul2026.pdf")); // The bytes travelled through the protocol — no signed link was minted. assert!(h.services.media.presigns().is_empty()); } #[test] fn serves_the_unlocked_copy_when_there_is_one_without_the_originals_hash() { let (h, secret) = harness_with(&["read", "write"]); let decrypted = format!( "{}/{}/decrypted.pdf", h.workspace_id, synthetic_uuid("documents-unlocked-key") ); let filed = seed_document( &h, "documents-unlocked", json!({ "decrypted_path": decrypted }), ); h.services.documents.put(&decrypted, BYTES.to_vec()); assert!(!filed.storage_path.is_empty()); let result = call_tool_content( &h, &secret, "get_document_bytes", json!({ "documentId": filed.id }), ); let content = result["content"].as_array().expect("content blocks"); let parsed: Value = serde_json::from_str(content[1]["text"].as_str().expect("a text block")).expect("JSON"); assert_eq!(parsed["variant"], json!("unlocked")); // The stored sha256 names the ORIGINAL bytes; handing it with a different // file would be an integrity claim that fails the first check. assert!(parsed.get("sha256").is_none(), "{parsed}"); } #[test] fn refuses_a_file_over_the_byte_limit_and_names_the_url_route() { let (h, secret) = harness_with(&["read", "write"]); let filed = seed_document( &h, "documents-too-big", json!({ "byte_size": 3 * 1024 * 1024, "sha256": "d".repeat(64) }), ); let answer = call_tool_raw( &h, &secret, "get_document_bytes", json!({ "documentId": filed.id }), ); assert!(answer.is_error, "{}", answer.text); assert!(answer.text.contains("includeFileUrl"), "{}", answer.text); } #[test] fn hands_out_an_upload_slot_and_says_so_when_the_file_is_already_filed() { let (h, secret) = harness_with(&["read", "write"]); let sha = "c".repeat(64); let slot = call_tool( &h, &secret, "request_document_upload", json!({ "fileName": "Harbour-Aug2026.pdf", "mime": "application/pdf", "byteSize": 4096, "sha256": sha, }), ); assert_eq!(slot["alreadyFiled"], json!(false)); assert_eq!( slot["stagedPath"], json!(format!("{}/incoming/{sha}.pdf", h.workspace_id)) ); assert_eq!( slot["uploadHeaders"]["content-type"], json!("application/pdf") ); assert_eq!(slot["method"], json!("PUT")); assert!( slot["instructions"] .as_str() .is_some_and(|note| note.contains("file_document")), "{slot}" ); assert_eq!(h.services.media.presigns().len(), 1); // The same hash again: nothing to upload, and the assistant is told so. seed_document(&h, "documents-already-filed", json!({ "sha256": sha })); let again = call_tool( &h, &secret, "request_document_upload", json!({ "fileName": "Harbour-Aug2026.pdf", "mime": "application/pdf", "byteSize": 4096, "sha256": sha, }), ); assert_eq!(again["alreadyFiled"], json!(true)); assert!(again["documentId"].is_string(), "{again}"); assert_eq!(h.services.media.presigns().len(), 1); } // ── the slot ──────────────────────────────────────────────────────────────── #[test] fn refuses_a_password_re_run_while_a_pass_holds_the_slot() { // C2 + I8. The slot stops a second pipeline opening over one row. But an // MCP call that CHAINED on the slot would sit inside `files.with_write` for // the length of a whole pass, and while that lock is held a phone's push // cannot be accepted — the owner sees a sync failure for a workspace that // is working perfectly. // // So this lane TRIES the slot and is told no. An assistant is a poller; a // person is not, which is why the app's route chains and this does not. // // The I8 half — that this lane does not hold the workspace write lock — is // pinned in `tests/mcp.rs`, at the HTTP surface where the lock is taken. let (h, secret) = harness_with(&["read", "write"]); let filed = seed_document( &h, "documents-slot-password", json!({ "mime": "text/plain", "original_name": "Harbour-Sep2026.txt", "status": "locked" }), ); hold_the_slot(&h); let answer = call_tool_raw( &h, &secret, "update_document", json!({ "documentId": filed.id, "passwordCandidates": ["hunter2"] }), ); assert!(answer.is_error, "{}", answer.text); assert!( answer .text .to_lowercase() .contains("reading documents right now"), "{}", answer.text ); // Nothing ran: the row is exactly as it was. let row = document_row(&h, "status", &filed.id).expect("the document is there"); assert_eq!(row.text("status"), Some("locked")); free_the_slot(&h); } #[test] fn the_bin_erases_no_document_while_a_pass_holds_the_slot() { // N3. An erase that lands mid-pass is the worst of the races: the pass's // next patch either throws in the apply or FOLDS THE ROW BACK from a // partial patch — a document the owner deleted, reappearing with half its // columns. Binning one touches neither bytes nor tombstones, so it needs // no slot; the bin's erase takes it. let (h, secret) = harness_with(&["read", "write"]); let doomed = seed_document( &h, "documents-slot-delete", json!({ "decrypted_path": null }), ); hold_the_slot(&h); let binned = call_tool( &h, &secret, "delete_document", json!({ "documentId": doomed.id, "confirm": true }), ); assert_eq!(binned["trashed"], json!(true), "{binned}"); let kept = empty_the_bin(&h); assert_eq!(kept["keptDocuments"], json!(1), "{kept}"); assert!( kept["keptDocumentsNote"].as_str().unwrap_or_default().contains("reading documents right now"), "{kept}" ); // Nothing went: the object is still in the store and the row is in the bin. assert!(h .services .documents .bytes_at(&doomed.storage_path) .is_some()); assert!(document_row(&h, "trashed_at", &doomed.id).is_some_and(|row| row.text("trashed_at").is_some())); assert!(queued(&h).is_empty()); // And once the pass is done the erase goes through — kept, never lost. free_the_slot(&h); let after = empty_the_bin(&h); assert_eq!(after["erased"]["document"], json!(1), "{after}"); assert!(document_row(&h, "id", &doomed.id).is_none()); assert_eq!(queued(&h), vec![doomed.storage_path.clone()]); } /// The owner's own Empty Bin. fn empty_the_bin(h: &Harness) -> Value { let answer = call_tool_as_owner(h, "device:phone", "empty_bin", json!({})); assert!(!answer.is_error, "empty_bin refused: {}", answer.text); answer.json() } // ── the password re-run ───────────────────────────────────────────────────── #[test] fn runs_the_password_re_run_when_the_slot_is_free() { // THE PIPELINE IS OWED, NOT DROPPED. The TypeScript asserts the re-run // really opened the file — `unlocked: true`, the bytes downloaded once, a // statement queued, `status: ready` with the model's title on the row. // Every one of those is the documents WORKER's (2f); the rail this server // hands the tool refuses that one method BY NAME, which is the honest // answer while there is no pipeline — a stub reporting "still locked" would // tell an assistant its passwords were wrong. // // What IS asserted here is everything around it: the slot was free and was // TAKEN and RELEASED (a second call gets the same refusal, never the busy // note), and the document is untouched. let (h, secret) = harness_with(&["read", "write"]); let filed = seed_document( &h, "documents-rerun", json!({ "mime": "text/plain", "original_name": "Harbour-Sep2026.txt", "status": "locked" }), ); h.services.documents.refuse_run_with(NO_PIPELINE); let first = call_tool_raw( &h, &secret, "update_document", json!({ "documentId": filed.id, "passwordCandidates": ["hunter2"] }), ); assert!(first.is_error, "{}", first.text); assert!( first.text.contains("reading pipeline is not configured"), "{}", first.text ); // The slot was released on the way out: a second call reaches the same // refusal rather than the busy note. let second = call_tool_raw( &h, &secret, "update_document", json!({ "documentId": filed.id, "passwordCandidates": ["hunter2"] }), ); assert!(second.is_error, "{}", second.text); assert_eq!(second.text, first.text); let row = document_row(&h, "status, title", &filed.id).expect("the document is there"); assert_eq!(row.text("status"), Some("locked")); assert_eq!( row.text("title"), Some("Harbour savings statement — July 2026") ); } #[test] fn hands_an_assistant_the_refusal_rather_than_a_half_run() { // The TypeScript's case is a PAYWALLED re-run: the pipeline records // `ai_unavailable` on the row and rethrows the gate's own sentence, so the // assistant is told the owner's trial ended rather than "document run // aborted". Both halves of that are the worker's (2f). // // The half this server can hold today is the one that matters most on the // way there: whatever stops a re-run, the refusal reaches the assistant // whole and the document is NOT left stamped with a failure it did not // suffer. A refused re-run writes no `error_code` and moves no status. let (h, secret) = harness_with(&["read", "write"]); let filed = seed_document( &h, "documents-paywalled", json!({ "mime": "text/plain", "original_name": "Harbour-Sep2026.txt", "status": "locked" }), ); h.services.documents.refuse_run_with(NO_PIPELINE); let answer = call_tool_raw( &h, &secret, "update_document", json!({ "documentId": filed.id, "passwordCandidates": ["hunter2"] }), ); assert!(answer.is_error, "{}", answer.text); // Not a wrapper's word: the sentence the caller could relay to their user. assert!(!answer.text.contains("run aborted"), "{}", answer.text); assert!( answer.text.contains("safe and untouched"), "{}", answer.text ); let row = document_row(&h, "status, error_code", &filed.id).expect("the document is there"); assert_eq!(row.text("status"), Some("locked")); assert_eq!(row.text("error_code"), None); } // ── filing ────────────────────────────────────────────────────────────────── #[test] fn records_an_agent_filing_as_an_agent_filing_whatever_the_caller_asked_for() { let (h, secret) = harness_with(&["read", "write"]); let sha = "e".repeat(64); let staged = format!("{}/incoming/{sha}.pdf", h.workspace_id); h.services.documents.put(&staged, BYTES.to_vec()); // `notify: true` used to flip `source` to "app", which bought one push by // making the owner's own file claim THEY filed a document their assistant // filed — permanently. The intent belongs to the server; the provenance // belongs to the owner. let filed = call_tool( &h, &secret, "file_document", json!({ "stagedPath": staged, "fileName": "Harbour-Oct2026.pdf", "mime": "application/pdf", "byteSize": 2048, "sha256": sha, "notify": true, }), ); let id = filed["document"]["id"] .as_str() .expect("a document id") .to_string(); let row = one( &h, "SELECT source, mcp_token_id FROM cotton_documents WHERE id = ?", vec![text(&id)], ); assert_eq!(row.text("source"), Some("agent")); // And which connection filed it, so the trail survives the token being // revoked and its name reused. assert!(row .text("mcp_token_id") .is_some_and(|value| !value.is_empty())); // The notify intent is remembered server-locally, for the worker to honour // when the read finishes — never on the record, and never synced. let opt_in = one( &h, "SELECT document_id FROM _document_notify_optin WHERE document_id = ?", vec![text(&id)], ); assert_eq!(opt_in.text("document_id"), Some(id.as_str())); } #[test] fn files_an_uploaded_document_and_dedupes_a_second_filing_onto_the_same_one() { let (h, secret) = harness_with(&["read", "write"]); let sha = "d".repeat(64); let staged = format!("{}/incoming/{sha}.pdf", h.workspace_id); h.services.documents.put(&staged, BYTES.to_vec()); let args = json!({ "stagedPath": staged, "fileName": "Harbour-Sep2026.pdf", "mime": "application/pdf", "byteSize": 4096, "sha256": sha, }); let filed = call_tool(&h, &secret, "file_document", args.clone()); assert_eq!(filed["deduped"], json!(false)); assert_eq!(filed["document"]["status"], json!("processing")); let id = filed["document"]["id"].as_str().expect("an id").to_string(); // The bytes moved to their permanent home rather than travelling through // this process, and the staged copy did not survive. let home = format!("{}/{id}/original.pdf", h.workspace_id); assert_eq!(h.services.documents.bytes_at(&home).as_deref(), Some(BYTES)); assert!(h.services.documents.bytes_at(&staged).is_none()); // The staged object is gone, so the second filing has nothing to copy — // which is fine, because it never gets that far: the hash is already filed. let second = call_tool(&h, &secret, "file_document", args); assert_eq!(second["deduped"], json!(true)); assert_eq!(second["document"]["id"], json!(id)); // One document, and no orphan left behind. assert_eq!( one( &h, "SELECT COUNT(*) AS n FROM cotton_documents WHERE sha256 = ?", vec![text(&sha)] ) .int("n"), Some(1) ); assert!(h.services.documents.bytes_at(&staged).is_none()); } /// RULE: A deleted document waits in the bin, so the same bytes filed or asked to upload again take it back out under its own id and say so; once the bin erases it, the same bytes take the next generation of its derived id. #[test] fn reingested_document_after_delete_takes_the_next_generation() { let (h, secret) = harness_with(&["read", "write"]); let sha = "e".repeat(64); let staged = format!("{}/incoming/{sha}.pdf", h.workspace_id); let args = json!({ "stagedPath": staged, "fileName": "Harbour-Oct2026.pdf", "mime": "application/pdf", "byteSize": 4096, "sha256": sha, }); h.services.documents.put(&staged, BYTES.to_vec()); let first = call_tool(&h, &secret, "file_document", args.clone()); let old_id = first["document"]["id"].as_str().expect("an id").to_string(); let delete = || { let deleted = call_tool( &h, &secret, "delete_document", json!({ "documentId": old_id, "confirm": true }), ); assert_eq!(deleted["deleted"], json!(true)); assert_eq!(deleted["trashed"], json!(true)); }; let in_the_bin = || { document_row(&h, "trashed_at", &old_id).is_some_and(|row| row.text("trashed_at").is_some()) }; // Filed again while it waits in the bin: the binned one comes back out. delete(); assert!(in_the_bin()); h.services.documents.put(&staged, BYTES.to_vec()); let back = call_tool(&h, &secret, "file_document", args.clone()); assert_eq!(back["deduped"], json!(true), "{back}"); assert_eq!(back["restoredFromBin"], json!(true), "{back}"); assert_eq!(back["document"]["id"], json!(old_id)); assert!(!in_the_bin(), "the re-filed document is still in the bin"); // Asked to upload again while it waits in the bin: the same. delete(); let asked = call_tool( &h, &secret, "request_document_upload", json!({ "fileName": "Harbour-Oct2026.pdf", "mime": "application/pdf", "byteSize": 4096, "sha256": sha }), ); assert_eq!(asked["alreadyFiled"], json!(true), "{asked}"); assert_eq!(asked["restoredFromBin"], json!(true), "{asked}"); assert!(!in_the_bin(), "the re-asked document is still in the bin"); // Erased from the bin: the same bytes are the next generation. delete(); empty_the_bin(&h); assert!(document_row(&h, "id", &old_id).is_none()); h.services.documents.put(&staged, BYTES.to_vec()); let again = call_tool(&h, &secret, "file_document", args); assert_eq!(again["deduped"], json!(false)); let new_id = again["document"]["id"].as_str().expect("an id").to_string(); assert_ne!(new_id, old_id, "the erased id is never written again"); assert!(document_row(&h, "id", &new_id).is_some()); assert!(document_row(&h, "id", &old_id).is_none()); } #[test] fn refuses_a_staged_path_outside_the_callers_own_workspace() { let (h, secret) = harness_with(&["read", "write"]); let answer = call_tool_raw( &h, &secret, "file_document", json!({ "stagedPath": format!("{}/incoming/{}.pdf", synthetic_uuid("documents-other-ws"), "e".repeat(64)), "fileName": "someone-elses.pdf", "mime": "application/pdf", "byteSize": 10, "sha256": "e".repeat(64), }), ); assert!(answer.is_error, "{}", answer.text); assert!( answer.text.to_lowercase().contains("your own workspace"), "{}", answer.text ); assert_eq!( one( &h, "SELECT COUNT(*) AS n FROM cotton_documents WHERE workspace_id = ?", vec![text(&h.workspace_id)] ) .int("n"), Some(0) ); } // ── editing ───────────────────────────────────────────────────────────────── #[test] fn edits_a_document_without_re_reading_it_when_no_password_is_offered() { let (h, secret) = harness_with(&["read", "write"]); let filed = seed_document(&h, "documents-edit", json!({})); let result = call_tool( &h, &secret, "update_document", json!({ "documentId": filed.id, "issuer": "Harbour Bank Ltd", "docType": "card_statement", }), ); assert_eq!(result["updated"], json!(true)); assert_eq!(result["reran"], json!(false)); assert_eq!(result["document"]["docType"], json!("card_statement")); assert_eq!(result["document"]["issuer"], json!("Harbour Bank Ltd")); } #[test] fn queues_a_statement_when_a_document_is_re_typed_into_one_and_drops_it_when_re_typed_away() { // Spec §4.1's third birth. A document the pipeline mis-read is corrected by // hand, and the correction is what should start the reading — nobody should // have to send the document anywhere. let (h, secret) = harness_with(&["read", "write"]); let filed = seed_document(&h, "documents-retype", json!({ "doc_type": "invoice" })); let queued = call_tool( &h, &secret, "update_document", json!({ "documentId": filed.id, "docType": "bank_statement" }), ); assert_eq!(queued["statement"], json!("queued to be read")); assert_eq!( one( &h, "SELECT read_status FROM cotton_money_statements WHERE document_id = ?", vec![text(&filed.id)] ) .text("read_status"), Some("pending") ); // Re-stating the same type mints no twin. call_tool( &h, &secret, "update_document", json!({ "documentId": filed.id, "docType": "bank_statement" }), ); assert_eq!( one( &h, "SELECT COUNT(*) AS n FROM cotton_money_statements WHERE document_id = ?", vec![text(&filed.id)] ) .int("n"), Some(1) ); // And typing it away takes the unread row with it — a pending statement has // no lines, so nothing is lost, and leaving it would queue a read of a // document that is not a statement. call_tool( &h, &secret, "update_document", json!({ "documentId": filed.id, "docType": "invoice" }), ); assert!(maybe_one( &h, "SELECT id FROM cotton_money_statements WHERE document_id = ?", vec![text(&filed.id)] ) .is_none()); } #[test] fn says_a_statement_that_has_been_read_is_not_re_queued_by_re_typing() { // read_statement is. let (h, secret) = harness_with(&["read", "write"]); let filed = seed_document( &h, "documents-read-statement", json!({ "doc_type": "invoice" }), ); let statement_id = synthetic_uuid("documents-read-statement-row"); run( &h, "INSERT INTO cotton_money_statements \ (id, workspace_id, document_id, kind, currency, read_status, line_count, created_at, \ updated_at) \ VALUES (?, ?, ?, 'bank', 'INR', 'read', 0, ?, ?)", vec![ text(&statement_id), text(&h.workspace_id), text(&filed.id), text(AT), text(AT), ], ); let result = call_tool( &h, &secret, "update_document", json!({ "documentId": filed.id, "docType": "bank_statement" }), ); assert_eq!( result["statement"], json!("already read (status read) — read_statement re-reads it") ); assert_eq!( one( &h, "SELECT read_status FROM cotton_money_statements WHERE id = ?", vec![text(&statement_id)] ) .text("read_status"), Some("read") ); } #[test] fn says_out_loud_that_a_statement_other_document_is_not_read() { let (h, secret) = harness_with(&["read", "write"]); let filed = seed_document( &h, "documents-statement-other", json!({ "doc_type": "invoice" }), ); let result = call_tool( &h, &secret, "update_document", json!({ "documentId": filed.id, "docType": "statement_other" }), ); assert_eq!( result["statement"], json!("no statement queued — only bank and card statements are read") ); assert!(maybe_one( &h, "SELECT id FROM cotton_money_statements WHERE document_id = ?", vec![text(&filed.id)] ) .is_none()); } // ── deleting ──────────────────────────────────────────────────────────────── #[test] fn refuses_to_delete_a_document_whose_statement_has_been_read_naming_what_it_evidences() { let (h, secret) = harness_with(&["read", "write"]); let filed = seed_document(&h, "documents-evidenced", json!({ "decrypted_path": null })); let statement_id = synthetic_uuid("documents-evidenced-statement"); let line_id = synthetic_uuid("documents-evidenced-line"); let transaction_id = synthetic_uuid("documents-evidenced-transaction"); let evidence_id = synthetic_uuid("documents-evidenced-evidence"); run( &h, "INSERT INTO cotton_money_statements \ (id, workspace_id, document_id, kind, currency, read_status, line_count, created_at, \ updated_at) \ VALUES (?, ?, ?, 'bank', 'INR', 'mismatch', 1, ?, ?)", vec![ text(&statement_id), text(&h.workspace_id), text(&filed.id), text(AT), text(AT), ], ); run( &h, "INSERT INTO cotton_money_statement_lines \ (id, workspace_id, statement_id, page, line_no, posted_on, text, amount_minor, \ direction, fingerprint, created_at) \ VALUES (?, ?, ?, 1, 1, '2026-07-03', 'UPI/ALDER GROCERS', 128000, 'out', ?, ?)", vec![ text(&line_id), text(&h.workspace_id), text(&statement_id), text(&format!("stl:{line_id}")), text(AT), ], ); run( &h, "INSERT INTO cotton_money_transactions \ (id, workspace_id, occurred_on, created_at, updated_at) VALUES (?, ?, '2026-07-03', ?, ?)", vec![ text(&transaction_id), text(&h.workspace_id), text(AT), text(AT), ], ); run( &h, "INSERT INTO cotton_money_evidence \ (id, workspace_id, transaction_id, kind, ref_id, excerpt, attached_by, created_at) \ VALUES (?, ?, ?, 'statement_line', ?, 'UPI/ALDER GROCERS', 'import', ?)", vec![ text(&evidence_id), text(&h.workspace_id), text(&transaction_id), text(&line_id), text(AT), ], ); let answer = call_tool_raw( &h, &secret, "delete_document", json!({ "documentId": filed.id, "confirm": true }), ); assert!(answer.is_error, "{}", answer.text); assert!( answer .text .contains("statement Cotton has read (status mismatch)"), "{}", answer.text ); assert!( answer.text.contains("evidence for 1 transaction in"), "{}", answer.text ); // Nothing went: not the bytes, not the row, not the statement. assert!(h.services.documents.bytes_at(&filed.storage_path).is_some()); assert!(document_row(&h, "id", &filed.id).is_some()); assert!(maybe_one( &h, "SELECT id FROM cotton_money_statements WHERE id = ?", vec![text(&statement_id)] ) .is_some()); } /// RULE: A stored path outside this database's own folder — another workspace's, or one climbing out with `..` — is never queued to unlink when the bin erases its document, though the document is erased: the unlink queue takes only keys under this file's prefix. #[test] fn never_queues_a_path_outside_the_workspaces_own_folder() { // `storage_path` is a SYNCED, DEVICE-WRITABLE column, and the unlink pass // reaches storage with full authority. let (h, secret) = harness_with(&["read", "write"]); for (label, path) in [ ("documents-foreign-path", "some-other-workspace/secret/original.pdf".to_string()), ("documents-traversal", format!("{}/../other/original.pdf", h.workspace_id)), ] { // Mint refuses another workspace's path now; a file that held one from // before takes it as the serving Mac's answer. let filed = seed_document_by(&h, label, json!({ "storage_path": path, "decrypted_path": null }), Harness::run_held); let answer = call_tool( &h, &secret, "delete_document", json!({ "documentId": filed.id, "confirm": true }), ); assert_eq!(answer["deleted"], json!(true)); empty_the_bin(&h); assert!(h.services.documents.bytes_at(&path).is_some()); assert!(document_row(&h, "id", &filed.id).is_none()); } assert!(queued(&h).is_empty(), "a path outside the folder was queued: {:?}", queued(&h)); } #[test] fn refuses_to_delete_without_an_explicit_confirmation() { let (h, secret) = harness_with(&["read", "write"]); let filed = seed_document(&h, "documents-unconfirmed", json!({})); let answer = call_tool_raw( &h, &secret, "delete_document", json!({ "documentId": filed.id }), ); assert!(answer.is_error, "{}", answer.text); assert!( answer.text.contains("confirm: true"), "{}", answer.text ); assert!(h.services.documents.bytes_at(&filed.storage_path).is_some()); } /// Every key waiting in this file's unlink queue, sorted. fn queued(h: &Harness) -> Vec { let mut keys: Vec = h .with(cotton_store::media_erasure::pending_unlinks) .expect("the queue reads") .into_iter() .map(|pending| pending.key) .collect(); keys.sort(); keys } /// RULE: delete_document only bins a document and the bin's erase deletes no bytes through any rail: it writes one erasure fact each for storage_path and decrypted_path, naming the document, and both keys are dead and queued for each device's unlink pass. #[test] fn delete_document_writes_erasure_facts() { let (h, secret) = harness_with(&["read", "write"]); let decrypted = format!("{}/{}/unlocked.pdf", h.workspace_id, synthetic_uuid("documents-erased")); let filed = seed_document(&h, "documents-erased", json!({ "decrypted_path": decrypted })); h.services.documents.put(&decrypted, BYTES.to_vec()); // `confirm` is the protocol's own guard on a destructive tool — a model // that merely mentioned a document must not be able to delete it. let result = call_tool( &h, &secret, "delete_document", json!({ "documentId": filed.id, "confirm": true }), ); assert_eq!(result["deleted"], json!(true)); assert_eq!(result["documentId"], json!(filed.id)); // In the bin, its file with it: no erasure fact yet, nothing queued. assert!(document_row(&h, "id", &filed.id).is_some()); assert!(queued(&h).is_empty(), "a binned document's keys were queued"); let emptied = empty_the_bin(&h); assert_eq!(emptied["erased"]["document"], json!(1), "{emptied}"); assert!(document_row(&h, "id", &filed.id).is_none()); for key in [&filed.storage_path, &decrypted] { let facts = h.count( "SELECT COUNT(*) AS n FROM cotton_media_erasures WHERE key = ? AND record_table = 'cotton_documents' AND record_id = ?", &[text(key), text(&filed.id)], ); assert_eq!(facts, 1, "{key} has no erasure fact naming the document"); assert!(h.with(|db| cotton_store::media_erasure::is_dead(db, key)).expect("reads"), "{key} is not dead"); assert!(h.services.documents.bytes_at(key).is_some(), "{key} was deleted by the tool"); } let mut want = vec![filed.storage_path.clone(), decrypted.clone()]; want.sort(); assert_eq!(queued(&h), want); assert!( !h.services.documents.calls().iter().any(|(kind, _)| kind == "delete"), "the documents rail was asked to delete: {:?}", h.services.documents.calls() ); } #[test] fn bins_a_document_with_no_document_storage() { // Binning touches no bytes and races no pass, so a server with no // document storage still moves a document to the bin. let mut bag = FakeServices::new(); bag.without_media(); let mut h = Harness::with_services(bag); let secret = mint_token(&mut h, &["read", "write"], "Gmail harvester"); let filed = seed_document( &h, "documents-unreachable", json!({ "decrypted_path": null }), ); let answer = call_tool( &h, &secret, "delete_document", json!({ "documentId": filed.id, "confirm": true }), ); assert_eq!(answer["trashed"], json!(true), "{answer}"); assert!(document_row(&h, "trashed_at", &filed.id).is_some_and(|row| row.text("trashed_at").is_some())); } // ── the link ──────────────────────────────────────────────────────────────── #[test] fn mints_a_file_link_only_when_asked_and_says_which_rendition_it_is() { // The link comes from the PRESIGN rail, which only a store that can sign // fills — the shared signer on `ToolServices`, never the documents seam, // so that there is one answer to "how long is a link good for". let (h, secret) = harness_with(&["read", "write"]); let filed = seed_document(&h, "documents-link", json!({})); let plain = call_tool( &h, &secret, "get_document", json!({ "documentId": filed.id }), ); assert!(plain.get("fileUrl").is_none(), "{plain}"); let with_url = call_tool( &h, &secret, "get_document", json!({ "documentId": filed.id, "includeFileUrl": true }), ); let url = with_url["fileUrl"].as_str().expect("a link came back"); assert!(url.contains(&filed.storage_path), "{url}"); assert_eq!(with_url["fileVariant"], json!("original")); // Five minutes from the harness clock, said out loud rather than implied. assert_eq!(with_url["fileExpiresAt"], json!("2026-09-08T10:05:00.000Z")); } /// RULE: An agent files a document into a shared database as it does into the personal one: the token that filed it is a personal-database row the link rule will not let a shared row point at, so the filing lands without `mcp_token_id` instead of being refused. #[test] fn files_a_document_into_a_shared_database_without_pointing_at_the_personal_token() { let (h, secret) = harness_with(&["read", "write"]); run( &h, "UPDATE cotton_workspaces SET kind = 'shared' WHERE id = ?", vec![SqlValue::Text(h.workspace_id.clone())], ); let sha = "f".repeat(64); let staged = format!("{}/incoming/{sha}.png", h.workspace_id); h.services.documents.put(&staged, BYTES.to_vec()); let filed = call_tool( &h, &secret, "file_document", json!({ "stagedPath": staged, "fileName": "09-film-absent-slip.png", "mime": "image/png", "byteSize": BYTES.len(), "sha256": sha, "title": "viewers: 09-film-absent-slip.png", "docType": "other", }), ); let id = filed["document"]["id"].as_str().expect("a document id").to_string(); let row = one( &h, "SELECT source, mcp_token_id FROM cotton_documents WHERE id = ?", vec![text(&id)], ); assert_eq!(row.text("source"), Some("agent")); assert!(row.text("mcp_token_id").is_none_or(str::is_empty)); }