//! Records filled in by the model (the junk lane, brief 2, 12 Oct 2026). The//! rules in [`super::record_fields`] are conservative: a subject that names no//! kind leaves a service's thread a `notice`, and a field the rules are unsure//! of stays empty. Once, the hourly junk worker asks the household's//! Connected AI about such a thread — its subject and the first//! [`BODY_BYTES`] of its newest service mail — for the kind, the amount and//! currency, the merchant, the date the record is about and its reference.//! The call is the server's (`cotton_server::junk`); what is asked, what may//! be written and what is never touched are here.//!//! - **Never a person's thread.** Only a thread whose sender is a service is//! asked about, and [`apply`] re-reads the kind before it writes.//! - **Never over the owner.** A thread whose record the owner wrote at one of//! their screens is theirs: never asked, never written ([`edited_fields`]//! reads the file's own write log). And the model only ever fills a field//! that is still empty.//! - **Never a one-time code.** A thread the rules typed `code` is never//! asked; a model's `code` keeps the kind and the merchant and nothing else;//! a reference that is a short digit run in mail that speaks of a code is//! dropped; the reason line names fields, never values.//! - **Validated before written.** Every field is checked against its column//! ([`answers`]): a field that fails is dropped, never coerced.//! - **Once.** `record_reason` (v121) says what was asked and what was taken;//! a thread with one is not asked again until the rules type it afresh from//! new mail, which clears it.use std::collections::{BTreeSet, HashSet};use std::sync::LazyLock;use regex::Regex;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};usesuper::kinds::SERVICE;usesuper::record_fields::{minor_units, CODE, KINDS, NOTICE};usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::update_row;usecrate::mcp::protocol::ToolFailure;use cotton_core::rules::mail_predicate;/// Threads asked about in an hour.pubconst PER_HOUR: i64 = 200;/// Threads in one model call.pubconst PER_CALL: usize = 10;/// How much of a body the model sees.pubconst BODY_BYTES: usize = 2048;/// The record columns a model may fill.const FIELDS: &[&str] = &["record_kind", "amount_minor", "currency", "merchant", "record_on", "reference"];const MERCHANT_MAX: usize = 80;const REFERENCE_MAX: usize = 64;/// What the model is shown about one thread.#[derive(Debug, Clone, PartialEq, Eq)]pubstructMaterial {pub thread_id: String,pub subject: String,/// The first [`BODY_BYTES`] of the newest service mail's body.pub body_head: String,/// The sender's display name.pub sender: Option<String>,}/// One thread's answer, every field already checked against its column.#[derive(Debug, Clone, PartialEq, Eq)]pubstructAnswer {pub thread_id: String,pub kind: Option<&'static str>,/// `(currency, minor units)`, only ever the two together.pub amount: Option<(String, i64)>,pub merchant: Option<String>,pub on: Option<String>,pub reference: Option<String>,}/// What [`apply`] did.#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]pubstructExtracted {/// Threads stamped asked.pub asked: i64,/// Fields written.pub fields: i64,/// Answers for a thread no longer the model's to fill.pub skipped: i64,}fn failure(error: impl std::fmt::Display) -> ToolFailure {ToolFailure::new(error.to_string())}/// The record columns of `thread_id` the owner wrote at one of their own/// screens (`owner:<device>`), read from the file's own write log. Every other/// writer of these columns is a reader of mail — a job, an import, an/// assistant's `ingest_emails` — and its values are the rules', not the owner's.pubfn edited_fields(ctx: &Ctx<'_>, thread_id: &str) -> Result<BTreeSet<String>, ToolFailure> {let holes: Vec<String> = (0..FIELDS.len()).map(|i| format!("?{}", i + 2)).collect();letmut params = vec![SqlValue::Text(thread_id.to_string())]; params.extend(FIELDS.iter().map(|field| SqlValue::Text((*field).to_string())));let found = ctx .db() .all( &format!("SELECT DISTINCT f.value AS field FROM _writes w, json_each(w.fields) f \ WHERE w.tbl = 'cotton_email_threads' AND w.row_id = ?1 \ AND w.actor LIKE 'owner:%' AND f.value IN ({})", holes.join(", ") ), ¶ms, ) .map_err(failure)?;Ok(found.iter().filter_map(|row| row.text("field").map(str::to_string)).collect())}/// Service threads the rules left short, never asked, newest first, at most/// `limit` — those a person edited are left out.pubfn due(ctx: &mutCtx<'_>, limit: i64) -> Result<Vec<Material>, ToolFailure> {let workspace = SqlValue::Text(ctx.workspace_id.to_string());let candidates = ctx .db() .all( &format!("SELECT id, subject, sender_address FROM cotton_email_threads \ WHERE workspace_id = ?1 AND sender_kind = ?2 AND {live_thread} \ AND record_reason IS NULL AND (record_kind IS NULL OR record_kind <> ?3) \ AND (record_kind IS NULL OR record_kind = ?4 OR amount_minor IS NULL OR merchant IS NULL \ OR record_on IS NULL OR reference IS NULL) \ ORDER BY last_at DESC, id LIMIT ?5", live_thread = mail_predicate::live_thread("")), &[ workspace.clone(),SqlValue::Text(SERVICE.to_string()),SqlValue::Text(CODE.to_string()),SqlValue::Text(NOTICE.to_string()),// Room for the edited ones left out below.SqlValue::Integer(limit * 2), ], ) .map_err(failure)?;letmut out = Vec::new();for row in &candidates {if out.len() as i64 >= limit {break; }letSome(id) = row.text("id") else { continue };if !edited_fields(ctx, id)?.is_empty() {continue; }let sender = row.text("sender_address").unwrap_or_default().to_string();let newest = ctx .db() .get( &format!("SELECT body, from_name FROM cotton_emails \ WHERE workspace_id = ?1 AND thread_id = ?2 AND from_email = ?3 AND {live_mail} \ ORDER BY sent_at DESC, id DESC LIMIT 1", live_mail = mail_predicate::live("")), &[workspace.clone(), SqlValue::Text(id.to_string()), SqlValue::Text(sender)], ) .map_err(failure)?; out.push(Material { thread_id: id.to_string(), subject: row.text("subject").unwrap_or_default().trim().to_string(), body_head: head(newest.as_ref().and_then(|row| row.text("body")).unwrap_or_default(), BODY_BYTES), sender: newest .as_ref() .and_then(|row| row.text("from_name")) .map(|name| name.trim().to_string()) .filter(|name| !name.is_empty()), }); }Ok(out)}/// At most `bytes` of `text`, cut at a character's edge.fn head(text: &str, bytes: usize) -> String {if text.len() <= bytes {return text.to_string(); }letmut end = bytes;while !text.is_char_boundary(end) { end -= 1; } text[..end].to_string()}/// Whether the words speak of a code a person types in.fn speaks_of_a_code(words: &str) -> bool {static CODE_WORDS: LazyLock<Regex> = LazyLock::new(|| {Regex::new(r"(?i)\b(otp|one[- ]time|code|passcode|pin|verification|verify|2fa|sign[- ]?in|log[- ]?in|enter)\b") .expect("the code words compile") }); CODE_WORDS.is_match(words)}fn short_digits(reference: &str) -> bool { (4..=8).contains(&reference.len()) && reference.chars().all(|c| c.is_ascii_digit())}fn text_field(entry: &Value, key: &str) -> Option<String> { entry .get(key) .and_then(|value| match value {Value::String(text) => Some(text.trim().to_string()),Value::Number(number) => Some(number.to_string()), _ => None, }) .filter(|text| !text.is_empty())}fn valid_kind(word: Option<String>) -> Option<&'static str> {let word = word?.to_lowercase(); KINDS.iter().copied().find(|kind| *kind == word)}fn valid_amount(amount: Option<String>, currency: Option<String>) -> Option<(String, i64)> {let currency = currency?.to_uppercase();if currency.len() != 3 || !currency.chars().all(|c| c.is_ascii_uppercase()) {returnNone; }let amount = amount?;if !amount.chars().all(|c| c.is_ascii_digit() || c == '.' || c == ',') || !amount.starts_with(|c: char| c.is_ascii_digit()) {returnNone; }// Never more than a billion in any currency's major unit: a figure like// that in a mail is a reference read as an amount.let minor = minor_units(&amount, ¤cy)?; (minor < 1_000_000_000_000).then_some((currency, minor))}fn valid_date(on: Option<String>) -> Option<String> {let on = on?;let date = chrono::NaiveDate::parse_from_str(&on, "%Y-%m-%d").ok()?; (date.format("%Y-%m-%d").to_string() == on).then_some(on)}fn valid_merchant(merchant: Option<String>) -> Option<String> {let merchant = merchant?; (merchant.chars().count() <= MERCHANT_MAX && !merchant.chars().any(char::is_control)).then_some(merchant)}fn valid_reference(reference: Option<String>) -> Option<String> {let reference = reference?; (reference.len() <= REFERENCE_MAX && reference.chars().all(|c| c.is_ascii_alphanumeric() || "-_/.#".contains(c))) .then_some(reference)}/// The model's answer, read for the threads it was asked about and nothing/// else, every field checked against its column — a field that fails is/// dropped, never coerced — and a code never kept.pubfn answers(input: &Value, asked: &[Material]) -> Vec<Answer> {letmut seen = HashSet::new(); input .get("threads") .and_then(Value::as_array) .into_iter() .flatten() .filter_map(|entry| {let thread_id = entry.get("thread")?.as_str()?.trim().to_string();let material = asked.iter().find(|material| material.thread_id == thread_id)?;if !seen.insert(thread_id.clone()) {returnNone; }let kind = valid_kind(text_field(entry, "kind"));let merchant = valid_merchant(text_field(entry, "merchant"));if kind == Some(CODE) {// A code mail keeps what it is and who sent it, nothing more.returnSome(Answer { thread_id, kind, amount: None, merchant, on: None, reference: None }); }let words = format!("{}\n{}", material.subject, material.body_head);let reference = valid_reference(text_field(entry, "reference")) .filter(|reference| !(short_digits(reference) && speaks_of_a_code(&words)));Some(Answer { thread_id, kind, amount: valid_amount(text_field(entry, "amount"), text_field(entry, "currency")), merchant, on: valid_date(text_field(entry, "on")), reference, }) }) .collect()}/// Write the answers into the threads asked about. Only a thread still a/// service's, still never asked and edited by nobody is written; within it,/// only a field still empty (the kind over nothing or a notice). Every such/// thread asked is stamped, answered or not, so none is asked twice.pubfn apply(ctx: &mutCtx<'_>, asked: &[Material], answers: &[Answer]) -> Result<Extracted, ToolFailure> {letmut done = Extracted::default();for material in asked {let row = ctx .db() .get("SELECT sender_kind, record_kind, amount_minor, currency, merchant, record_on, reference, record_reason \ FROM cotton_email_threads WHERE workspace_id = ?1 AND id = ?2", &[SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(material.thread_id.clone())], ) .map_err(failure)?;letSome(row) = row else { done.skipped += 1;continue; };let open = row.text("sender_kind") == Some(SERVICE) && row.text("record_reason").is_none() && row.text("record_kind") != Some(CODE) && edited_fields(ctx, &material.thread_id)?.is_empty();if !open { done.skipped += 1;continue; }let answer = answers.iter().find(|answer| answer.thread_id == material.thread_id);letmut patch = Map::new();letmut took: Vec<&str> = Vec::new();letmut asked_for: Vec<&str> = Vec::new();let kind_open = row.text("record_kind").is_none_or(|kind| kind == NOTICE);if kind_open { asked_for.push("kind"); }let empty = |column: &str| match column {"amount_minor" => row.int(column).is_none(), _ => row.text(column).is_none(), };for (column, word) in [("amount_minor", "amount"), ("merchant", "merchant"), ("record_on", "on"), ("reference", "reference")] {if empty(column) { asked_for.push(word); } }ifletSome(answer) = answer {let kind = match answer.kind {Some(kind) if kind_open && kind != NOTICE => { patch.insert("record_kind".into(), Value::from(kind)); took.push("kind");Some(kind) } _ => row.text("record_kind").map(|kind| KINDS.iter().copied().find(|k| *k == kind).unwrap_or(NOTICE)), };let is_code = kind == Some(CODE);iflet (Some((currency, minor)), true, false) = (&answer.amount, empty("amount_minor") && empty("currency"), is_code) { patch.insert("amount_minor".into(), Value::from(*minor)); patch.insert("currency".into(), Value::from(currency.clone())); took.push("amount"); }iflet (Some(merchant), true) = (&answer.merchant, empty("merchant")) { patch.insert("merchant".into(), Value::from(merchant.clone())); took.push("merchant"); }iflet (Some(on), true, false) = (&answer.on, empty("record_on"), is_code) { patch.insert("record_on".into(), Value::from(on.clone())); took.push("on"); }iflet (Some(reference), true, false) = (&answer.reference, empty("reference"), is_code) { patch.insert("reference".into(), Value::from(reference.clone())); took.push("reference"); } }// Field names only: a value here could be the very code kept out above.let line = format!("asked: {}; took: {}",if asked_for.is_empty() { "nothing".to_string() } else { asked_for.join(", ") },if took.is_empty() { "nothing".to_string() } else { took.join(", ") } ); done.fields += took.len() as i64; patch.insert("record_reason".into(), Value::from(line)); update_row(ctx, "cotton_email_threads", &material.thread_id, patch)?; done.asked += 1; } ctx.commit()?;Ok(done)}// ── the question the model is asked ─────────────────────────────────────────/// The forced tool the model answers through.pubconst TOOL: &str = "read_records";pubconst SYSTEM_PROMPT: &str = "You read mail from companies to one person and say what record \each one is. For each thread you are given its subject, the sender's name and the start of its \newest mail. Answer for each thread with only what the mail plainly states:\n\- kind: receipt (a payment or purchase made), statement (an account or card statement), ticket \(travel or event tickets), booking (a reservation or stay), code (a one-time or sign-in code), \delivery (a parcel's progress) or notice (anything else).\n\- amount and currency: the total the record is for, as a plain number (\"1240.50\") and its \three-letter ISO code.\n\- merchant: the company the record is with, as the person would name it.\n\- on: the date the record is ABOUT — the travel date, the statement's end, the delivery day — \as YYYY-MM-DD; never the date the mail was sent.\n\- reference: an order, booking, PNR or invoice number.\n\Leave out any field you are not sure of: an empty field is better than a guess. Never give a \one-time code, a PIN or a password as any field. Answer for every thread you are given and for \no other.";/// The tool's schema: one entry per thread asked.pubfn tool_schema() -> Value { json!({"type": "object","properties": {"threads": {"type": "array","items": {"type": "object","properties": {"thread": { "type": "string", "description": "The thread id you were given." },"kind": { "type": "string", "enum": KINDS },"amount": { "type": "string", "description": "A plain number, e.g. \"1240.50\"." },"currency": { "type": "string", "description": "A three-letter ISO code, e.g. \"EUR\"." },"merchant": { "type": "string" },"on": { "type": "string", "description": "YYYY-MM-DD." },"reference": { "type": "string" } },"required": ["thread"],"additionalProperties": false } } },"required": ["threads"],"additionalProperties": false })}/// The user message: one JSON line per thread.pubfn prompt(asked: &[Material]) -> String { asked .iter() .map(|material| { json!({"thread": material.thread_id,"subject": material.subject,"sender": material.sender,"mail": material.body_head, }) .to_string() }) .collect::<Vec<_>>() .join("\n")}