//! The 30-day Junk clock (mail-simplified item 3; architect, 11 Oct 2026,//! decision 4470cfe6): a blocked sender's mail lives in Junk — never the bin —//! for thirty days, and then the serving Mac puts it in the bin.//!//! The clock is the later of two instants: when the block was made, and when//! Cotton stored the thread's newest mail. So the 6,707 mails that came out of//! the bin when blocking stopped binning start their thirty days at the block//! (today for the 76 blocked on 11 Oct), and a blocked sender writing again//! keeps their thread in Junk for thirty days from that mail.//!//! The purge BINS, the app's own delete: recoverable from the bin, erased only//! when the bin is emptied. It goes through `apply_email_state`, so whether//! Gmail hears of it is the account's "Deleting here also deletes in Gmail"//! (`config.gmail_bin`): off, the push sends nothing for it.use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};usesuper::kinds::JUNK;usesuper::shared::{apply_email_state, target_rows};usecrate::mcp::dispatch::{Ctx, ToolResult};usecrate::mcp::handlers::common::{iso_of_ms, now_ms};usecrate::mcp::protocol::ToolFailure;use cotton_core::rules::email_state::EmailStatePatch;use cotton_core::rules::mail_predicate;/// How long a blocked sender's mail waits in Junk.pubconst JUNK_DAYS: i64 = 30;/// Threads binned per step — one short hold of the file each.const PURGE_STEP: i64 = 200;/// The steps one pass may take, so a first purge of thousands finishes over a/// few passes rather than holding a worker.pubconst PURGE_STEPS: usize = 50;/// What one step did.#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]pubstructPurged {/// Junk conversations put in the bin.pub threads: i64,/// Their messages.pub emails: i64,}/// One step of the purge: up to [`PURGE_STEP`] Junk threads whose clock ran/// out go to the bin. Answers whether more may be waiting.pubfn purge_step(ctx: &mutCtx<'_>) -> Result<(Purged, bool), ToolFailure> {let cutoff = iso_of_ms(now_ms(ctx) - JUNK_DAYS * 24 * 60 * 60 * 1000);let threads = ids( ctx, &format!("SELECT t.id FROM cotton_email_threads t JOIN cotton_blocked_senders b ON b.workspace_id = t.workspace_id AND b.address = t.sender_address WHERE t.workspace_id = ?1 AND t.sender_kind = ?2 AND {live_thread} AND b.created_at < ?3 AND NOT EXISTS (SELECT 1 FROM cotton_emails e WHERE e.thread_id = t.id AND e.created_at >= ?3) LIMIT ?4", live_thread = mail_predicate::live_thread("t.")), &[SqlValue::Text(cutoff)], )?; bin_threads(ctx, &threads)}/// Empty Junk now (the sweep lane, 12 Oct 2026): every Junk conversation goes/// to the bin at once, clock or no clock — the same bin as the purge's, so it/// can be brought back, and Gmail hears of it only when the account's/// "Deleting here also deletes in Gmail" is on. The owner's act only/// (`McpScope::Owner`).pubfn empty_junk(ctx: &mutCtx<'_>, _args: &Map<String, Value>) -> ToolResult {letmut all = Purged::default();loop {let threads = ids( ctx, &format!("SELECT id FROM cotton_email_threads WHERE workspace_id = ?1 AND sender_kind = ?2 AND {live_thread} LIMIT ?3", live_thread = mail_predicate::live_thread("")), &[], )?;let (step, more) = bin_threads(ctx, &threads)?; all.threads += step.threads; all.emails += step.emails;if !more {break; } } ctx.audit("empty_junk", &format!("{} conversation(s) from Junk to the bin", all.threads));Ok(json!({ "threads": all.threads, "emails": all.emails }))}/// The Junk threads one step takes: `sql` binds the workspace as `?1`, the/// junk kind as `?2`, then `more`, then the step's size.fn ids(ctx: &Ctx<'_>, sql: &str, more: &[SqlValue]) -> Result<Vec<String>, ToolFailure> {letmut params = vec![SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(JUNK.to_string())]; params.extend_from_slice(more); params.push(SqlValue::Integer(PURGE_STEP));Ok(ctx .db() .all(sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string()))? .iter() .filter_map(|row| row.text("id").map(str::to_string)) .collect())}/// Bin `threads`' live mail through the app's own delete and commit.fn bin_threads(ctx: &mutCtx<'_>, threads: &[String]) -> Result<(Purged, bool), ToolFailure> {if threads.is_empty() {returnOk((Purged::default(), false)); }let live: Vec<_> = target_rows(ctx, &[], threads)? .into_iter() .filter(|row| row.get("trashed_at").is_none_or(serde_json::Value::is_null)) .collect();let emails = apply_email_state( ctx, &live,EmailStatePatch { bin: Some(true), ..EmailStatePatch::default() }, )?; ctx.commit()?;let purged = Purged { threads: threads.len() as i64, emails };Ok((purged, threads.len() as i64 == PURGE_STEP))}