//! The documents tools, served to an assistant.//!//! THE SHAPE OF THIS GROUP FOR A MODEL. The tools are written for the flow the//! owner described: an assistant opens a mailbox, downloads a year of//! statements, works each password out of the hints in the covering email, and//! files them — a bank or card statement filed this way is read into a pending//! statement automatically. So `request_document_upload` hands back a signed URL//! rather than taking bytes (a 4 MB PDF base64'd into a tool call would cost//! more context than the whole rest of the job), `update_document` takes//! password GUESSES rather than a password (guessing is the actual task, and//! each guess costs half a second of AES), and every tool answers with the//! document's STATUS so the assistant can tell "filed and read" from "filed but//! still locked" without a second call.//!//! ASSISTANTS NEVER SEE A DOCUMENT'S PASSWORD. `get_document` answers//! `wasProtected` — whether Cotton got INTO the file — and never the key; the//! bytes and the link both serve the UNLOCKED rendition when there is one. A//! secret that has been through a model's context is a secret that lives in a//! transcript.usecrate::mcp::writer::Retract;use std::collections::BTreeSet;use base64::Engine;use cotton_store::search::search_all;use serde_json::{json, Map, Value};usecrate::mcp::dispatch::{Ctx, ToolResult};usecrate::mcp::handlers::common::{ bounded_limit, fail, in_chunks, insert_row, int, is_uuid, maybe_row, now_iso, optional_enum, optional_string, require_string, require_uuid, rows, text, update_row, Valid,};usecrate::mcp::handlers::documents::paths::{ assert_path_in_workspace, original_path_for, staging_path_for,};usecrate::mcp::handlers::documents::rail::{DocumentsRail, RunOutcome};usecrate::mcp::handlers::money::engine_shim::is_readable_statement_doc_type;usecrate::mcp::handlers::money::rows::{ ensure_pending_statement, id_filter, load_statement_by_document,};usecrate::mcp::protocol::{tool_content, ToolFailure};usecrate::mcp::read_db::{Filter, Order, Query};/// Five minutes on an upload URL, matching the read side.////// An assistant that asked for one is about to use it; a link still live an/// hour later is only useful to whoever finds it in a log.const UPLOAD_URL_TTL_SECONDS: u64 = 300;/// How long a `get_document` file link lives — the bytes route's own number.////// The session bus mints the same five-minute link for a message's image, and/// two numbers would be two answers to "how long is a link good for".pubconst FILE_URL_TTL_SECONDS: u64 = 300;const DOCUMENT_TYPES: [&str; 14] = ["bank_statement","card_statement","invoice","receipt","tax","id","insurance","medical","legal","ticket","statement_other","letter","manual","other",];const DOCUMENT_STATUSES: [&str; 5] = ["processing", "summarizing", "ready", "locked", "failed"];/// Refused over the cap, never truncated. Trying 25 of 30 and answering "still/// locked" would tell the caller all thirty failed, and it would never retry/// the five that were never tried.pub(crate) const DOCUMENT_MAX_PASSWORD_CANDIDATES: usize = 25;const LIST_COLUMNS: &[&str] = &["id","title","original_name","doc_type","issuer","summary","status","failed_stage","error_code","page_count","byte_size","source","created_at",];/// One document as an assistant sees it in a list.fn compact(row: &Map<String, Value>) -> Value {letmut out = Map::new(); out.insert("id".to_string(),Value::from(text(row, "id").unwrap_or_default()), ); out.insert("title".to_string(),Value::from( text(row, "title").unwrap_or_else(|| text(row, "original_name").unwrap_or_default()), ), ); out.insert("docType".to_string(),Value::from(text(row, "doc_type").unwrap_or_default()), ); out.insert("issuer".to_string(), text(row, "issuer").map_or(Value::Null, Value::from), ); out.insert("summary".to_string(), text(row, "summary").map_or(Value::Null, Value::from), );let status = text(row, "status").unwrap_or_default(); out.insert("status".to_string(), Value::from(status.clone())); out.insert("pageCount".to_string(),match row.get("page_count") {None | Some(Value::Null) => Value::Null, _ => Value::from(int(row, "page_count")), }, ); out.insert("createdAt".to_string(),Value::from(text(row, "created_at").unwrap_or_default()), );// Present ONLY when it means something, so a clean listing stays readable.if status == "failed" { out.insert("failedStage".to_string(), text(row, "failed_stage").map_or(Value::Null, Value::from), ); out.insert("errorCode".to_string(), text(row, "error_code").map_or(Value::Null, Value::from), ); }Value::Object(out)}/// Resolve one document inside this workspace, or refuse.////// Every tool addressed by id starts here. The workspace filter is the scope,/// and there is ONE answer for "absent" and "not yours" — the same/// probe-resistance rule the meeting and message tools follow. A document in/// the bin is deleted, waiting: it is read from the bin alone.fn document_scoped( ctx: &Ctx<'_>, document_id: &str, columns: &[&str],) -> Valid<Map<String, Value>> {let found = maybe_row( ctx, &Query::on("cotton_documents") .columns(columns) .eq("id", document_id.to_string()) .filter(Filter::IsNull("trashed_at".to_string())) .limit(1), )?; found.ok_or_else(|| {ToolFailure::new("no such document in this workspace (it may be in the bin — list_bin will say)") })}/// The document tools' shared refusal when the server has no bytes bridge.fn documents_rail<'a>(ctx: &'a Ctx<'a>, what: &str) -> Valid<&'a dynDocumentsRail> {match ctx.services.documents.as_ref() {Some(rail) => Ok(rail.as_ref()),None => fail(format!("{what} needs document storage, which this server is not configured to reach. \ Reading, searching and listing still work. Tell the owner rather than retrying." )), }}fn columns_with(extra: &[&'static str]) -> Vec<&'static str> {letmut columns: Vec<&'static str> = LIST_COLUMNS.to_vec(); columns.extend_from_slice(extra); columns}// ── list_documents ──────────────────────────────────────────────────────────pubfn list_documents(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let doc_type = optional_enum(args, "docType", &DOCUMENT_TYPES)?;let status = optional_enum(args, "status", &DOCUMENT_STATUSES)?;let issuer = optional_string(args, "issuer");// TWENTY-FIVE by default, a THOUSAND at most. The default is unchanged and// is the right size for an assistant answering "do I have my March// statement"; the ceiling was raised from two hundred because the owner's// own vault emits no `LIMIT` at all (`documentsService.list`) and matches// its search hits against the rows it has already loaded — a paper past the// limit is not merely off the list, it cannot be found or opened.let limit = bounded_limit(args, 25, 1000);// ORDERED BY WHAT A PAPER IS ABOUT, then by when it was filed —// `documentsService.list`'s rule, whose own docstring exists to state it:// "a July statement uploaded in November reads as July". Undated papers// sort LAST, which SQLite gives for free on a descending order (NULL is the// smallest value, so it lands at the bottom); the TypeScript spells the// same thing as a leading `document_date IS NULL` because it was written// against PostgREST's `nullsFirst` and kept the belt on.letmut query = Query::on("cotton_documents") .columns(LIST_COLUMNS)// A document in the bin is deleted, waiting: never listed. .filter(Filter::IsNull("trashed_at".to_string())) .order_by("document_date", Order::Desc) .order_by("created_at", Order::Desc) .limit(limit);ifletSome(doc_type) = doc_type { query = query.eq("doc_type", doc_type); }ifletSome(status) = status { query = query.eq("status", status); }// Issuer is what the model wrote on the document ("Harbour Bank"), so it is// matched loosely — an assistant asking for "Harbour" should not miss "Harbour// Bank Ltd".ifletSome(issuer) = issuer { query = query.filter(Filter::Like("issuer".to_string(), format!("%{issuer}%"))); }let found = rows(ctx, &query)?;Ok(json!({"documents": found.iter().map(compact).collect::<Vec<_>>(), }))}// ── search_documents ────────────────────────────────────────────────────────/// PORT CHANGE: the TypeScript called a Postgres RPC (`cotton_documents_search`)/// that ranked the profile and the page text together and answered a snippet/// plus the page it came from. The file has no RPCs; it has FTS5, and the store/// owns the query language (`search::search_all`, which strips FTS syntax out/// of whatever a human typed). So this searches BOTH indexed tables —/// `cotton_documents` (title, issuer, summary, original name) and/// `cotton_document_pages` (the text) — and folds the page hits back onto their/// documents, which is the same answer by a different road: a page hit carries/// its page number as `matchedPage`, a profile hit carries none.pubfn search_documents(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {letSome(query) = require_string(args, "query") else {returnErr(ToolFailure::new("query is required")); };let limit = bounded_limit(args, 20, 50);let tables = vec!["cotton_documents".to_string(),"cotton_document_pages".to_string(), ];let hits = search_all(ctx.db(), &query, Some(&tables), Some(limit)) .map_err(|error| ToolFailure::new(error.to_string()))?;if hits.is_empty() {returnOk(json!({ "documents": [] })); }// A page hit names a PAGE row; the document it belongs to, and which page// it was, come from the page row itself.let page_ids: Vec<String> = hits .iter() .filter(|hit| hit.table == "cotton_document_pages") .map(|hit| hit.row_id.clone()) .collect();letmut page_of: std::collections::BTreeMap<String, (String, i64)> = std::collections::BTreeMap::new();for row in in_chunks(&page_ids, |batch| { rows( ctx, &Query::on("cotton_document_pages") .columns(&["id", "document_id", "page"]) .filter(id_filter("id", batch)), ) })? {let (Some(id), Some(document_id)) = (text(&row, "id"), text(&row, "document_id")) else {continue; }; page_of.insert(id, (document_id, int(&row, "page"))); }// Best hit per document, in rank order — the ranking is the store's and is// not re-derived here.letmut order: Vec<(String, Option<i64>, String)> = Vec::new();letmut seen: BTreeSet<String> = BTreeSet::new();for hit in &hits {let (document_id, matched_page) = if hit.table == "cotton_document_pages" {match page_of.get(&hit.row_id) {Some((document_id, page)) => (document_id.clone(), Some(*page)),None => continue, } } else { (hit.row_id.clone(), None) };if !seen.insert(document_id.clone()) {continue; } order.push((document_id, matched_page, hit.snippet.clone())); }let ids: Vec<String> = order.iter().map(|(id, _, _)| id.clone()).collect();let found = in_chunks(&ids, |batch| { rows( ctx, &Query::on("cotton_documents") .columns(LIST_COLUMNS) .filter(id_filter("id", batch))// A document in the bin is deleted, waiting: no search finds it. .filter(Filter::IsNull("trashed_at".to_string())), ) })?;let documents: Vec<Value> = order .iter() .filter_map(|(document_id, matched_page, snippet)| {let row = found .iter() .find(|row| text(row, "id").as_deref() == Some(document_id.as_str()))?;letmut out = compact(row);let object = out.as_object_mut()?;// The words that matched, with the page they were on — an assistant// can often answer from this without opening anything. object.insert("snippet".to_string(), Value::from(snippet.clone())); object.insert("matchedPage".to_string(), matched_page.map_or(Value::Null, Value::from), );Some(out) }) .collect();Ok(json!({ "documents": documents }))}// ── get_document ────────────────────────────────────────────────────────────pubfn get_document(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let document_id = require_uuid(args, "documentId")?;// Anything other than an explicit `true` means no link. A credential is not// something to hand over on a truthy accident.let include_file_url = args.get("includeFileUrl") == Some(&Value::Bool(true));let doc = document_scoped( ctx, &document_id, &columns_with(&["workspace_id","mime","sha256","facts","password","storage_path","decrypted_path","text_extracted", ]), )?;let id = text(&doc, "id").unwrap_or_default();let pages = rows( ctx, &Query::on("cotton_document_pages") .columns(&["id"]) .eq("document_id", id.clone()), )?;letmut base = compact(&doc); {let object = base .as_object_mut() .ok_or_else(|| ToolFailure::new("compact answers an object"))?; object.insert("originalName".to_string(),Value::from(text(&doc, "original_name").unwrap_or_default()), ); object.insert("mime".to_string(),Value::from(text(&doc, "mime").unwrap_or_default()), ); object.insert("byteSize".to_string(), Value::from(int(&doc, "byte_size"))); object.insert("source".to_string(),Value::from(text(&doc, "source").unwrap_or_default()), ); object.insert("facts".to_string(), doc.get("facts").cloned().unwrap_or(Value::Null), );// Whether Cotton got INTO the file, not what the key was. The password// itself stays in the database: an assistant filing statements has no// use for it, and a secret that has been through a model's context is a// secret that lives in a transcript. object.insert("wasProtected".to_string(),Value::from(text(&doc, "password").is_some()), ); object.insert("hasText".to_string(),Value::from(crate::mcp::handlers::common::flag(&doc, "text_extracted")), ); object.insert("extractedPages".to_string(),Value::from(pages.len() as i64), ); }if !include_file_url {returnOk(base); }// Opt-in, and off by default. A signed URL is a bearer credential; minting// one on every `get_document` would scatter live links through transcripts// for calls that only ever wanted the summary.letSome(presign) = ctx.services.presign.as_ref() else {returnErr(ToolFailure::new("this server cannot mint file links yet: document storage is not configured. \ Everything else about this document is above.", )); };// The unlocked copy when there is one — and the password never travels.let decrypted = text(&doc, "decrypted_path");let path = decrypted .clone() .or_else(|| text(&doc, "storage_path")) .unwrap_or_default();// A path READ BACK from a synced, device-writable column needs the same// check as one a caller supplied: a poisoned op could point it anywhere.let path = assert_path_in_workspace(Some(&path), ctx.workspace_id).map_err(ToolFailure::new)?;let file_url = presign(&path, FILE_URL_TTL_SECONDS) .map_err(|_| ToolFailure::new("this document's file is missing"))?;let expires_at = crate::mcp::handlers::common::iso_of_ms( ctx.now.timestamp_millis() + (FILE_URL_TTL_SECONDS as i64) * 1000, );let object = base .as_object_mut() .ok_or_else(|| ToolFailure::new("compact answers an object"))?; object.insert("fileUrl".to_string(), Value::from(file_url)); object.insert("fileExpiresAt".to_string(), Value::from(expires_at)); object.insert("fileVariant".to_string(),Value::from(if decrypted.is_some() {"unlocked" } else {"original" }), );Ok(base)}// ── get_document_bytes ──────────────────────────────────────────────────────/// The most a file may weigh to travel INSIDE a tool result.////// Base64 through the protocol is the one road that works from a sandboxed/// client with no network — but it lands in the conversation at roughly a token/// per three bytes, so 2 MB is already a ~700k-token answer on a client that/// reads the blob as text. Bigger files take the signed-URL road/// (`get_document` with `includeFileUrl`).const BYTES_TOOL_MAX: i64 = 2 * 1024 * 1024;/// `Number.prototype.toLocaleString("en-GB")` for a whole number — thousands/// separated by commas, which is what the refusal quotes.fn grouped(value: i64) -> String {let digits = value.abs().to_string();letmut out = String::new();for (index, character) in digits.chars().enumerate() {if index > 0 && (digits.len() - index).is_multiple_of(3) { out.push(','); } out.push(character); }if value < 0 { format!("-{out}") } else { out }}pubfn get_document_bytes(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let document_id = require_uuid(args, "documentId")?;let doc = document_scoped( ctx, &document_id, &["id","original_name","mime","sha256","byte_size","storage_path","decrypted_path", ], )?;let rail = documents_rail(ctx, "get_document_bytes")?;let byte_size = int(&doc, "byte_size");if byte_size > BYTES_TOOL_MAX {returnErr(ToolFailure::new(format!("this file is {} bytes — over the {}-byte limit for carrying bytes in a tool result. \ Call get_document with includeFileUrl for a five-minute link instead.", grouped(byte_size), grouped(BYTES_TOOL_MAX) ))); }let decrypted = text(&doc, "decrypted_path");let path = decrypted .clone() .or_else(|| text(&doc, "storage_path")) .unwrap_or_default();let path = assert_path_in_workspace(Some(&path), ctx.workspace_id).map_err(ToolFailure::new)?;let bytes = rail .get(&path) .map_err(ToolFailure::new)? .ok_or_else(|| ToolFailure::new("this document's file is missing"))?;// The row's size was the ORIGINAL's; the unlocked rendition is a different// file, so what was actually read gets its own check.if (bytes.len() as i64) > BYTES_TOOL_MAX {returnErr(ToolFailure::new("the unlocked copy is over the byte limit for a tool result. Call get_document with \ includeFileUrl for a five-minute link instead.", )); }let blob = base64::engine::general_purpose::STANDARD.encode(&bytes);let variant = if decrypted.is_some() {"unlocked" } else {"original" };let id = text(&doc, "id").unwrap_or_default();let mime = text(&doc, "mime").unwrap_or_default();// An image travels as the protocol's own image block (clients render those// directly); everything else as an embedded resource blob.let body = if mime.starts_with("image/") { json!({ "type": "image", "data": blob, "mimeType": mime }) } else { json!({"type": "resource","resource": {"uri": format!("cotton://documents/{id}/file"),"mimeType": mime,"blob": blob, }, }) };letmut summary = Map::new(); summary.insert("documentId".to_string(), Value::from(id)); summary.insert("fileName".to_string(),Value::from(text(&doc, "original_name").unwrap_or_default()), ); summary.insert("mime".to_string(), Value::from(mime)); summary.insert("byteSize".to_string(), Value::from(bytes.len() as i64)); summary.insert("variant".to_string(), Value::from(variant));// The stored hash names the ORIGINAL bytes; served an unlocked copy, it// would be the hash of a file that is not in your hands.if variant == "original" { summary.insert("sha256".to_string(),Value::from(text(&doc, "sha256").unwrap_or_default()), ); }Ok(tool_content(vec![ body, json!({"type": "text","text": serde_json::to_string(&Value::Object(summary)) .map_err(|error| ToolFailure::new(error.to_string()))?, }), ]))}// ── request_document_upload ─────────────────────────────────────────────────structUploadArgs { file_name: String, mime: String, byte_size: i64, sha256: String,}fn is_sha256(value: &str) -> bool { value.len() == 64 && value .chars() .all(|character| character.is_ascii_digit() || ('a'..='f').contains(&character))}fn validate_upload(args: &Map<String, Value>) -> Valid<UploadArgs> {letSome(file_name) = require_string(args, "fileName") else {return fail("fileName is required"); };letSome(mime) = require_string(args, "mime") else {return fail("mime is required"); };// Checked HERE rather than at the storage layer because the hash is this// group's dedup key: a mis-cased or truncated one would file a second copy// of a document the workspace already has, silently, and only show up as a// duplicate months later.let sha256 = require_string(args, "sha256").unwrap_or_default();if !is_sha256(&sha256) {return fail("sha256 must be 64 lowercase hex characters over the raw file bytes"); }let byte_size = match args.get("byteSize") {Some(Value::Number(number)) => match number.as_i64() {Some(value) if value > 0 => value, _ => return fail("byteSize must be the file's size in bytes"), }, _ => return fail("byteSize must be the file's size in bytes"), };Ok(UploadArgs { file_name, mime, byte_size, sha256, })}pubfn request_document_upload(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_upload(args)?;// The rail is asked for FIRST even though the sign goes through the shared// signer: "this server has no document storage" is the refusal a caller can// act on, and it must not depend on which of the two capabilities happens// to be missing. documents_rail(ctx, "uploading a document")?;// Already here? Say so and stop, before the assistant spends a download and// an upload on bytes this workspace has had for a year.let existing = document_with_bytes(ctx, &args.sha256)?;ifletSome(row) = existing {let restored = out_of_the_bin_again(ctx, &row)?;letmut out = json!({"alreadyFiled": true,"documentId": text(&row, "id"),"title": text(&row, "title") .unwrap_or_else(|| text(&row, "original_name").unwrap_or_default()),"status": text(&row, "status"),"instructions":"This file is already in the vault — nothing to upload. Use get_document to read it.", });if restored { out["restoredFromBin"] = Value::Bool(true); out["instructions"] = Value::from(RESTORED_NOTE); }returnOk(out); }let path = staging_path_for(ctx.workspace_id, &args.sha256, &args.file_name);// The SHARED signer, not the documents seam's: one answer to "how long is// an upload slot good for", whatever is being uploaded.letSome(presign_put) = ctx.services.presign_put.as_ref() else {returnErr(ToolFailure::new("could not open an upload slot: this server has no object store to upload into", )); }; #[allow(clippy::cast_sign_loss)]let (url, headers) = presign_put( &path, UPLOAD_URL_TTL_SECONDS, &args.mime, args.byte_size.max(0) as u64, ) .map_err(|error| ToolFailure::new(format!("could not open an upload slot: {error}")))?;let expires_at = crate::mcp::handlers::common::iso_of_ms( ctx.now.timestamp_millis() + (UPLOAD_URL_TTL_SECONDS as i64) * 1000, );let headers: Map<String, Value> = headers .into_iter() .map(|(name, value)| (name, Value::from(value))) .collect();Ok(json!({"alreadyFiled": false,"uploadUrl": url,// A presigned PUT has no token — the signature is in the URL — so what// an assistant needs instead is the HEADERS it must send, or the// signature will not match."uploadHeaders": Value::Object(headers),"stagedPath": path,"expiresAt": expires_at,"method": "PUT","contentType": args.mime,"instructions":"PUT the file's bytes to uploadUrl with exactly the uploadHeaders given, then call \ file_document with the same stagedPath, sha256, fileName, mime and byteSize. \ Cotton files it and starts reading it. If the file is password-protected, \ pass your guesses as passwordCandidates to update_document once it is filed.", }))}// ── file_document ───────────────────────────────────────────────────────────/// What a caller is told when the slot is busy.////// WORKSPACE-scoped, and the sentence has to say so. It used to read "that/// document is being read right now — poll get_document", which during a bulk/// harvest is untrue twice over: the pass holding the slot is usually reading/// ten OTHER documents, and polling this one returns the same `processing` it/// returned a second ago, so the advice never resolves and an assistant can/// reasonably conclude its password was unnecessary.pub(crate) const SLOT_BUSY_NOTE: &str = "Cotton is reading documents right now — try again in a minute.";pubfn file_document(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let upload = validate_upload(args)?;letSome(staged_path) = require_string(args, "stagedPath") else {returnErr(ToolFailure::new("stagedPath is required")); };let doc_type = optional_enum(args, "docType", &DOCUMENT_TYPES)?;let title = require_string(args, "title");let notify = args.get("notify") == Some(&Value::Bool(true));let rail = documents_rail(ctx, "filing a document")?;// The one check between a caller and any object in the store. Shared with// the delete path — see `assert_path_in_workspace`.let staged = assert_path_in_workspace(Some(&staged_path), ctx.workspace_id).map_err(ToolFailure::new)?;let existing = document_with_bytes(ctx, &upload.sha256)?;ifletSome(row) = existing {// Tidy the staged copy: the bytes are already filed under the document// we found, and leaving an orphan in `incoming/` would accumulate one// per re-upload forever. Best-effort — an orphan is untidy, never// wrong.let _ = rail.delete(std::slice::from_ref(&staged));let restored = out_of_the_bin_again(ctx, &row)?;letmut out = json!({ "deduped": true, "document": compact(&row) });if restored { out["restoredFromBin"] = Value::Bool(true); out["note"] = Value::from(RESTORED_NOTE); }returnOk(out); }// Derived from (workspace, sha256). The bytes ARE the key — the same file// filed on two devices was always meant to be one row, and// `cotton_documents UNIQUE (workspace_id, sha256)` says so. A document// that was deleted is never written again: the same bytes filed anew are// the next generation of that id, on every device alike.let document_id = new_document_id(ctx, &upload.sha256)?;let storage_path = original_path_for(ctx.workspace_id, &document_id, &upload.file_name);// S3 has no rename: copy server-side, then drop the staged original. The// bytes never come through the server. rail.copy(&staged, &storage_path) .map_err(|_| ToolFailure::new("there is no uploaded file at that stagedPath"))?;let _ = rail.delete(std::slice::from_ref(&staged));let stamp = now_iso(ctx);letmut patch = Map::new(); patch.insert("original_name".to_string(),Value::from(upload.file_name.clone()), ); patch.insert("mime".to_string(), Value::from(upload.mime.clone())); patch.insert("byte_size".to_string(), Value::from(upload.byte_size)); patch.insert("sha256".to_string(), Value::from(upload.sha256.clone())); patch.insert("storage_path".to_string(), Value::from(storage_path));// ALWAYS `agent`. This is provenance the owner reads — "you filed this" vs// "your assistant filed this" — and it used to be set to `app` when the// caller passed `notify: true`, purely because the notification decision// reads it. That bought one push by making the file lie about its own// history permanently. The intent goes to `_document_notify_optin` below// instead, which is the server's own note and never syncs. patch.insert("source".to_string(), Value::from("agent"));// Which connection filed it, so the audit trail survives the token being// revoked and its name reused. The token row lives in the person's// personal database only (`cotton_mcp_tokens` is mine-bound), and the// link rule refuses a shared database's row that points at it — so a// document filed into a shared database carries no token id; its receipt// already names the connection that wrote it.if !ctx.token_id.is_empty() && !matches!(ctx.file_kind()?, cotton_store::link_rule::FileKind::Shared) { patch.insert("mcp_token_id".to_string(),Value::from(ctx.token_id.to_string()), ); } patch.insert("status".to_string(), Value::from("processing")); patch.insert("doc_type".to_string(),Value::from(doc_type.unwrap_or_else(|| "other".to_string())), ); patch.insert("facts".to_string(), json!({})); patch.insert("text_extracted".to_string(), Value::from(false));ifletSome(title) = title { patch.insert("title".to_string(), Value::from(title)); } patch.insert("status_changed_at".to_string(), Value::from(stamp.clone())); insert_row(ctx, "cotton_documents", &document_id, patch)?; ctx.commit()?;// The caller asked for this one to be announced. The pipeline runs in the// WORKER, minutes from now and in another call stack, so the intent is// written down where the worker will look rather than inferred from a// falsified column.if notify {crate::mcp::handlers::documents::notify_optin::mark_notify_opt_in( ctx.db(), &document_id, &stamp, ) .map_err(ToolFailure::new)?; }let filed = document_scoped(ctx, &document_id, LIST_COLUMNS)?;Ok(json!({"deduped": false,"document": compact(&filed),"note":"Filed. Cotton is reading it now — poll get_document for the title, summary and \ facts. If it comes back locked, send your password guesses to update_document.", }))}// ── update_document ─────────────────────────────────────────────────────────/// The passwords a call asks to try, cleaned — `None` when it asks for none.fn password_candidates(args: &Map<String, Value>) -> Valid<Option<Vec<String>>> {letSome(raw) = args.get("passwordCandidates") else {returnOk(None); };letValue::Array(items) = raw else {returnErr(ToolFailure::new("passwordCandidates must be an array of strings", )); };let cleaned: Vec<String> = items .iter() .filter_map(Value::as_str) .map(|candidate| candidate.trim().to_string()) .filter(|candidate| !candidate.is_empty()) .collect();if cleaned.len() > DOCUMENT_MAX_PASSWORD_CANDIDATES {returnErr(ToolFailure::new(format!("at most {DOCUMENT_MAX_PASSWORD_CANDIDATES} passwordCandidates per call — send \ your best {DOCUMENT_MAX_PASSWORD_CANDIDATES} and call again with the rest" ))); }Ok((!cleaned.is_empty()).then_some(cleaned))}/// The passwords an `update_document` call will try, and on which document —/// read the way the handler reads them, BEFORE the file is taken.////// Trying them is the documents pipeline: it downloads the paper, calls a/// model and writes the file many times over, so it cannot run inside the/// file the handler is handed (it would wait on that same file, and on the/// network with it held). A dispatcher asks this first, runs the pipeline with/// nothing held, and hands the call a rail whose/// [`DocumentsRail::run_password_candidates`] answers what that run came to/// (`crate::mcp::dispatch::before_the_file`). `None` for every call the/// handler would refuse before it reached the pipeline's arguments.pubfn password_attempt(args: &Map<String, Value>) -> Option<(String, Vec<String>)> {let document_id = require_uuid(args, "documentId").ok()?; optional_enum(args, "docType", &DOCUMENT_TYPES).ok()?;let candidates = password_candidates(args).ok()??;Some((document_id, candidates))}pubfn update_document(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let document_id = require_uuid(args, "documentId")?;let doc_type = optional_enum(args, "docType", &DOCUMENT_TYPES)?;let password_candidates = password_candidates(args)?;let title = optional_string(args, "title");let issuer = optional_string(args, "issuer");let summary = optional_string(args, "summary");if title.is_none() && issuer.is_none() && summary.is_none() && doc_type.is_none() && password_candidates.is_none() {returnErr(ToolFailure::new("nothing to do — pass a field to change, or passwordCandidates to open a locked \ document", )); }let doc = document_scoped(ctx, &document_id, &columns_with(&["workspace_id"]))?;let id = text(&doc, "id").unwrap_or_default();letmut patch = Map::new();ifletSome(title) = title { patch.insert("title".to_string(), Value::from(title)); }ifletSome(doc_type) = doc_type.clone() { patch.insert("doc_type".to_string(), Value::from(doc_type)); }ifletSome(issuer) = issuer { patch.insert("issuer".to_string(), Value::from(issuer)); }ifletSome(summary) = summary { patch.insert("summary".to_string(), Value::from(summary)); }if !patch.is_empty() { update_row(ctx, "cotton_documents", &id, patch)?; ctx.commit()?; }// Changing a document's type is the third way a statement is born, beside// the pipeline's land and the backfill CLI — so a mis-typed document// becomes readable the moment somebody corrects it, and a document typed// AWAY from a statement takes its unread row with it rather than leaving a// queue entry for a document that is not one.//// Both directions are idempotent, and the delete only ever touches a// `pending` row: one that has been read owns lines, evidence and// transactions, and dropping it would take a person's money with it.letmut statement_note: Option<String> = None;ifletSome(doc_type) = doc_type.as_deref() {if is_readable_statement_doc_type(Some(doc_type)) {let ensured = ensure_pending_statement(ctx, &id)?; ctx.commit()?;let existing = if ensured.created {None } else { load_statement_by_document(ctx, &id)? };// A statement that HAS been read is not re-queued by a re-type: its// lines and money stand, and an assistant expecting a fresh read// would otherwise poll for one that never comes. `read_statement`// is the tool for that. statement_note = Some(match existing {Some(statement) if statement.read_status != "pending" => format!("already read (status {}) — read_statement re-reads it", statement.read_status ), _ => "queued to be read".to_string(), }); } else { remove_pending_statement(ctx, &id)?; ctx.commit()?;if doc_type == "statement_other" {// Said out loud, because it is the one re-type where an// assistant has every reason to expect a read and would// otherwise wait for one. statement_note = Some("no statement queued — only bank and card statements are read".to_string(), ); } } }letSome(candidates) = password_candidates else {let after = document_scoped(ctx, &id, LIST_COLUMNS)?;letmut out = json!({"updated": true,"reran": false,"document": compact(&after), });ifletSome(note) = statement_note { out.as_object_mut() .expect("a json object") .insert("statement".to_string(), Value::from(note)); }returnOk(out); };// Password guesses: run the SAME pipeline the worker and the app's route// run. This is the loop a mailbox harvest depends on — the hint is in the// covering email ("your date of birth in DDMMYYYY"), so the guessing// happens where the hint is, and Cotton just tries them. Inline, not// queued: a candidate that does not open the file is never stored, so there// is nothing a worker could pick up later.//// INLINE IN THE CALL, NOT IN THE FILE. This handler holds the file, and// the pipeline needs it — so the dispatcher ran the pipeline before it// took the file (`dispatch::before_the_file`, `password_attempt`), and the// rail below answers what that run came to. Its slot is the dispatcher's// too: `take_slot` says whether the dispatcher got it.let rail = documents_rail(ctx, "trying a document's password")?;// THE SAME SLOT the worker and the HTTP routes queue on. Run ungated, this// pipeline spends model-seconds with the row reading `summarizing` — which// is in the worker's pending statuses — so the sweep starts a second// pipeline over it. That bills the owner twice and lands two profile// batches, each minting fresh page ids for the same page numbers, so the// document ends up showing every page twice.//// Busy: told, not queued. Chaining here would hold this MCP call open for// the length of a whole pass, and an assistant has a better option than// waiting, which is to ask again in a moment.if !rail.take_slot(ctx.workspace_id).map_err(ToolFailure::new)? {returnErr(ToolFailure::new(format!("{SLOT_BUSY_NOTE} Send the password again when you retry." ))); }let outcome = rail.run_password_candidates(ctx.workspace_id, &id, &candidates); rail.release_slot(ctx.workspace_id);let outcome = outcome.map_err(ToolFailure::new)?;let after = document_scoped(ctx, &id, LIST_COLUMNS)?;letmut out = json!({"updated": true,"reran": true,"unlocked": outcome == RunOutcome::Ready,"document": compact(&after), });let object = out.as_object_mut().expect("a json object");ifletSome(note) = statement_note { object.insert("statement".to_string(), Value::from(note)); }if outcome.status() == "locked" { object.insert("note".to_string(),Value::from("None of those passwords opened it. The document is still locked — try other \ spellings of the hint (case, date format, name order).", ), ); }Ok(out)}/// Drop the UNREAD statement row a document is no longer entitled to.////// Only ever a `pending` row: one that has been read owns lines, evidence and/// transactions, and dropping it would take a person's money with it.fn remove_pending_statement(ctx: &mutCtx<'_>, document_id: &str) -> Valid<()> {letSome(statement) = load_statement_by_document(ctx, document_id)? else {returnOk(()); };if statement.read_status != "pending" {returnOk(()); } ctx.writer()? .retract("cotton_money_statements", &statement.id, Retract::Relation);Ok(())}/// The document these bytes already name, including a document in the bin./// Phone capture and MCP intake use the same lookup before minting an id.pubfn document_with_bytes(ctx: &Ctx<'_>, sha256: &str) -> Valid<Option<Map<String, Value>>> { maybe_row( ctx, &Query::on("cotton_documents") .columns(&columns_with(&["trashed_at", "storage_path", "mime"])) .eq("sha256", sha256.to_string()) .limit(1), )}/// New bytes use a deterministic id; erased bytes use its next generation./// Call after `document_with_bytes`: existing rows keep their original ids.pubfn new_document_id(ctx: &Ctx<'_>, sha256: &str) -> Valid<String> { cotton_store::erase::generation_id( ctx.db(),"cotton_documents", &[ctx.file.namespace().as_str(), sha256], ) .map_err(|error| ToolFailure::new(error.to_string()))}// ── delete_document ─────────────────────────────────────────────────────────/// What a re-upload answers when its bytes were a document in the bin.const RESTORED_NOTE: &str = "This file was in the bin, and filing it again took it back out — \ nothing to upload. Use get_document to read it.";/// The same bytes filed again while their document waits in the bin: the/// bytes are the document's key (`UNIQUE (workspace_id, sha256)`), so there/// is no second row to file — the binned one comes back out, as the bin's/// Restore would bring it, and the caller is told so. Answers whether it did.pubfn out_of_the_bin_again(ctx: &mutCtx<'_>, row: &Map<String, Value>) -> Valid<bool> {let (Some(id), Some(_)) = (text(row, "id"), text(row, "trashed_at")) else {returnOk(false); }; set_document_trashed(ctx, &id, false)?; ctx.audit("restore_from_bin", &format!("document {id}"));Ok(true)}/// Why this document may not go to the bin, nor be erased from it — or `None`.////// A statement that has been READ carries lines, and its lines are the/// evidence behind the owner's money: the file cascades the statement and its/// lines with the document, which would leave transactions pointing at/// nothing. Refused, with the count that says what is at stake. A pending row/// has no lines and goes with the paper.pub(crate) fn kept_for_its_statement(ctx: &Ctx<'_>, document_id: &str) -> Valid<Option<String>> {letSome(statement) = load_statement_by_document(ctx, document_id)? else {returnOk(None); };if statement.read_status != "read" && statement.read_status != "mismatch" {returnOk(None); }let evidenced = evidenced_transaction_count(ctx, &statement.id)?;Ok(Some(format!("this document is a statement Cotton has read (status {}) — its entries are \ evidence for {evidenced} transaction{} in the user's money. Deleting it would \ leave that money pointing at nothing. Remove those transactions first \ (delete_transaction), or keep the paper.", statement.read_status,if evidenced == 1 { "" } else { "s" } )))}/// Put a document in the bin, or take it out: its Delete, its Undo,/// `delete_document` and a re-upload of its bytes (the bin's Restore clears/// the same column). A read statement's paper is refused the bin/// ([`kept_for_its_statement`]); nothing leaves the disk here either way.pubfn set_document_trashed(ctx: &mutCtx<'_>, id: &str, trashed: bool) -> Valid<()> {if trashed {ifletSome(refusal) = kept_for_its_statement(ctx, id)? {returnErr(ToolFailure::new(refusal)); } }let kind = cotton_core::constants::BinKind::Document;if trashed {crate::mcp::handlers::bin::put_away(ctx, kind, id) } else {let args = serde_json::json!({"kind": kind.as_str(), "id": id});crate::mcp::handlers::bin::restore_from_bin(ctx, args.as_object().unwrap()).map(|_| ()) }}/// Erase binned documents for good — the bin's erase for this kind/// (`bin::erase`), IN THE DOCUMENTS SLOT. A read statement's paper is never/// erased ([`kept_for_its_statement`]: the caller leaves it in the bin). The/// slot is about a race that corrupts rather than double-bills: an erase/// landing while a pipeline holds already-downloaded bytes leaves that/// pipeline's apply folding against a tombstone. `None` when the slot is busy/// and nothing was erased.////// NO BYTES ARE TOUCHED HERE (slice 7). Each erase writes one erasure fact for/// `storage_path` and one for `decrypted_path` — the document's holder columns/// — and each device unlinks a key once nothing names it. A stored path/// outside this database's own folder is never unlinked/// (`cotton_store::media_unlink::may_unlink_key`).pub(crate) fn erase_documents( ctx: &mutCtx<'_>, ids: &[String], erase_one: implFn(&mutCtx<'_>, &str) -> Valid<()>,) -> Valid<Option<()>> {for id in ids {ifletSome(refusal) = kept_for_its_statement(ctx, id)? {returnErr(ToolFailure::new(refusal)); } }// A server with no document storage runs no pipeline to race.let rail = ctx.services.documents.clone();ifletSome(rail) = &rail {if !rail.take_slot(ctx.workspace_id).map_err(ToolFailure::new)? {returnOk(None); } }let erased = ids.iter().try_for_each(|id| erase_one(ctx, id)).and_then(|()| ctx.commit());ifletSome(rail) = &rail { rail.release_slot(ctx.workspace_id); } erased.map(Some)}/// `delete_document` — move a document to the bin (6 Oct 2026: a document/// waits there as a photo does). Its file and pages wait with it;/// `restore_from_bin` brings it back, and only the bin's erase removes it for/// good. A document already in the bin answers as deleted and stays there.pubfn delete_document(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let document_id = require_uuid(args, "documentId")?;// The confirmation is a hard gate rather than a default — and it must be// the boolean, not any truthy value.if args.get("confirm") != Some(&Value::Bool(true)) {returnErr(ToolFailure::new("deleting a document moves it to the bin — pass confirm: true if the user asked for it", )); }let doc = maybe_row( ctx, &Query::on("cotton_documents") .columns(&columns_with(&["trashed_at"])) .eq("id", document_id.clone()) .limit(1), )? .ok_or_else(|| ToolFailure::new("no such document in this workspace"))?;let id = text(&doc, "id").unwrap_or_default();if text(&doc, "trashed_at").is_none() { set_document_trashed(ctx, &id, true)?; }Ok(json!({"deleted": true,"trashed": true,"documentId": id,"title": text(&doc, "title") .unwrap_or_else(|| text(&doc, "original_name").unwrap_or_default()), }))}/// How many transactions cite one statement's lines as evidence.fn evidenced_transaction_count(ctx: &Ctx<'_>, statement_id: &str) -> Valid<usize> {let lines = rows( ctx, &Query::on("cotton_money_statement_lines") .columns(&["id"]) .eq("statement_id", statement_id.to_string()), )?;let line_ids: Vec<String> = lines.iter().filter_map(|row| text(row, "id")).collect();let cited = in_chunks(&line_ids, |batch| { rows( ctx, &Query::on("cotton_money_evidence") .columns(&["transaction_id"]) .eq("kind", "statement_line".to_string()) .filter(id_filter("ref_id", batch)), ) })?;let transactions: BTreeSet<String> = cited .iter() .filter_map(|row| text(row, "transaction_id")) .collect();Ok(transactions.len())}// ── notify_owner ────────────────────────────────────────────────────────────/// The push type the app's `NOTIFICATION_ROUTES` maps to the note this tool/// files.////// A CONSTANT rather than the inline literal it was until 4j, because/// `cotton-server`'s vocabulary guard holds every emitter against/// `cotton_core::rules::notifications::SERVER_PUSH_TYPES` by NAME — and a/// literal buried in a handler body is exactly the sender that lands without/// its map entry and its test.pubconst AGENT_NOTE_PUSH_TYPE: &str = "cotton_agent_note";/// An assistant's one way to interrupt the owner.////// The server has no notifications table, so it goes straight down the rail —/// same type, same title convention (the connection's name first, so the owner/// reads "Gmail harvester: …" rather than an anonymous ping from their own/// phone), same deep-link payload.////// No dedupe key, deliberately: two genuinely separate jobs that happen to/// report the same sentence are two things the owner asked to hear about.pubfn notify_owner(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {letSome(title) = require_string(args, "title") else {returnErr(ToolFailure::new("title is required")); };letSome(body) = require_string(args, "body") else {returnErr(ToolFailure::new("body is required")); };let document_id = optional_string(args, "documentId");ifletSome(value) = document_id.as_ref() {if !is_uuid(value) {returnErr(ToolFailure::new("documentId must be a uuid")); } }// B3: never a push from a connection that has been reading chats.ifcrate::mcp::chat_reads::read_chat_lately(ctx.workspace_id, ctx.token_id, ctx.now) {returnErr(ToolFailure::new(crate::mcp::chat_reads::REFUSAL)); }letSome(notify) = ctx.services.notify.as_ref() else {returnErr(ToolFailure::new("this Cotton server cannot send notifications — it has no push credentials \ configured. Tell the owner what you were going to say instead; do not retry.", )); };// Trimmed to what a lock screen shows. A notification is not a report.let title = crate::mcp::handlers::common::utf16_clip(&title, 80);let body = crate::mcp::handlers::common::utf16_clip(&body, 240);let data = match document_id {Some(document_id) => json!({ "documentId": document_id }),None => json!({}), };let result = notify(&json!({"type": AGENT_NOTE_PUSH_TYPE,"title": format!("{}: {title}", ctx.agent),"body": body,"data": data, })) .map_err(ToolFailure::new)?;let outcome = result .get("outcome") .and_then(Value::as_str) .unwrap_or_default() .to_string();// `queued` is a SENT one whose outcome nobody waited for: the rail was// called from inside the workspace's own write lock, so the send was put on// a task that runs the instant that write commits. This tool declares// `outsideWriteLock` precisely so that is not the ordinary path — but a// server that ever reaches it must not tell the assistant to retry, because// retrying is a second notification.if outcome == "sent" || outcome == "deduped" || outcome == "queued" {returnOk(json!({ "sent": true })); }if outcome == "no_tokens" {returnErr(ToolFailure::new("the owner has no device registered for notifications right now, so this could not \ be delivered. Say it in your reply instead.", )); }Err(ToolFailure::new(format!("the notification could not be delivered ({outcome}). Do not retry." )))}