Cotton code
2922 lines · 146.9 KB · RustRaw
//! Cotton Albums on this phone, stage 1 (tidy): the screens' methods//! (assets/design/albums/DECISIONS.md "SHELL BRIEF"). Every rule is//! `cotton_core::albums`; this module keeps the phone's own index and//! answers what each screen draws.//!//! ```text//! albums.start albums.library.take albums.pass.next albums.look.take//! albums.pass.lines albums.home albums.tidy albums.list albums.sets albums.set//! albums.set.keep albums.keep albums.bin.move albums.undo albums.bin//! albums.bin.bring_back albums.bin.delete albums.bin.clear_other albums.platform.done albums.work//! albums.waiting albums.you albums.face.align//! ```//!//! **The index is this phone's alone** (`albums-library.sqlite` beside the//! layout). It holds what was measured (the library's facts, what the core saw//! in each photo, the sets, what each list offers: all recomputable) and his//! choices: marks and the act rows that made them (CORE 2 syncs the acts). It//! is not a cache: it lives where the phone never clears it and backs it up//! (SHELL BRIEF).//!//! **The shape (the coordinator's decisions for ALBUMS CORE 1d, 27 Nov 2026):**//! 1. Every item has one **library state**, only from the shell's reads://!    `present`, `trashed` (in the phone's trash) or `absent`.//! 2. **One function decides what may be handed to the phone: [`free_plan`].**//!    Nothing else makes a platform list (a test reads this file to prove it).//!    An id is handed only if, at that moment, it is binned, present, was on//!    the screen the tap came from, and, if it is a copy, its original is//!    present, not binned, not handed and not trashed. Anything else is held//!    back with a reason.//! 3. **Handed is a state.** An item in a waiting Delete is `handed`: no act//!    touches it. Only a library read of that act's ids settles it: absent or//!    trashed → freed; present → back in the Bin. A kill anywhere heals at//!    the next read (`albums.waiting` says what to read).//! 4. Freed and present again (restored from the phone's trash) → kept, one//!    act row "came back".//! 5. Absence is believed only after two reports with different tokens;//!    sweeps also agree in the hash of their ids. Absence removes no choice.//! 6. Every act carries a request id: the same id again returns the first//!    answer and writes nothing.//! 7. A large act's tap writes one act row; its plan and its marks are made//!    in slices by `albums.work`.//! 8. A mark follows an item to a new id only by its exact cloud id.use std::cell::Cell;use std::collections::{BTreeMap, BTreeSet};use std::path::{Path, PathBuf};use base64::Engine;use rusqlite::{params, Connection, OptionalExtension};use serde_json::{json, Value};use cotton_core::albums::bin::{self, Mark};use cotton_core::albums::handing as core_handing;use cotton_core::albums::look::{self, Grey, Level, Look, PlatformLook};use cotton_core::albums::pass::{self, Progress, State};use cotton_core::albums::picks::picks;use cotton_core::albums::sets::{self, Shot};use cotton_core::albums::tidy::{self, Entry, List};use cotton_core::albums::{face, parts, size, words, Item, Kind, Platform};use crate::methods::MethodError;use crate::shell::client::ClientController;pub const METHODS: [&str; 24] = [    "albums.start",    "albums.library.take",    "albums.pass.next",    "albums.look.take",    "albums.pass.lines",    "albums.home",    "albums.tidy",    "albums.list",    "albums.sets",    "albums.set",    "albums.set.keep",    "albums.keep",    "albums.bin.move",    "albums.undo",    "albums.bin",    "albums.bin.bring_back",    "albums.bin.delete",    "albums.bin.clear_other",    "albums.you.clear_gone",    "albums.platform.done",    "albums.work",    "albums.waiting",    "albums.you",    "albums.face.align",];const FILE: &str = "albums-library.sqlite";const PAGE: usize = 60;/// Items an explicit choice may name and still be planned inside the tap.pub const TAP_IDS: usize = 200;/// Items an act applies inside the tap; the rest runs in `albums.work`.pub const TAP_BUDGET: usize = 500;/// Items one `albums.work` call plans or applies.pub const WORK_BUDGET: usize = 2_000;/// Methods that write his choices: each needs a `request_id`, and is written/// with `synchronous=FULL`.pub(crate) const ACTS: [&str; 9] = ["albums.set.keep", "albums.keep", "albums.bin.move", "albums.undo", "albums.bin.bring_back", "albums.bin.delete", "albums.bin.clear_other", "albums.you.clear_gone", "albums.platform.done"];pub fn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    let path = client.layout().client_dir().join(FILE);    let now = client.now().timestamp_millis();    // the index stays open between calls: a tap never pays for opening it    let mut open = OPEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner);    if open.as_ref().map_or(true, |ix| ix.path != path) {        *open = None;        *open = Some(Index::open(&path)?);    }    answer(open.as_mut().expect("opened above"), method, request, now)}/// The one open index of this process (calls take turns; each is one transaction).static OPEN: std::sync::Mutex<Option<Index>> = std::sync::Mutex::new(None);/// Answer one method against an index (the tests drive this directly). Each/// method is one transaction: an act lands whole or not at all. An act sent/// again with the same `request_id` answers what it answered the first time.pub fn answer(ix: &mut Index, method: &str, request: &Value, now: i64) -> Result<Value, MethodError> {    // his choices and a Delete's handing are flushed at once; a library read is    // not: settling from it is safe to repeat, and a lost one is read again    let act = ACTS.contains(&method) || method == "albums.work";    let sync = if act { "FULL" } else { "NORMAL" };    ix.conn.execute_batch(&format!("PRAGMA synchronous={sync}; BEGIN IMMEDIATE")).map_err(db)?;    let out = (|| {        if !ACTS.contains(&method) {            return dispatch(ix, method, request, now);        }        let rid = request["request_id"].as_str().filter(|r| !r.is_empty()).ok_or_else(|| bad("request_id: one per tap, made by the shell"))?;        let before: Option<(String, String)> = ix.conn.query_row("SELECT method, answer FROM request WHERE id = ?1", [rid], |r| Ok((r.get(0)?, r.get(1)?))).optional().map_err(db)?;        if let Some((m, a)) = before {            if m != method {                return Err(bad(format!("request_id {rid} was {m}")));            }            // the first answer again, said to be a replay (it may no longer be current)            let mut first: Value = serde_json::from_str(&a).map_err(|e| bad(e.to_string()))?;            if let Some(refused) = first.get("refused") {                return Err(MethodError::new(refused["code"].as_str().unwrap_or("refused"), refused["message"].as_str().unwrap_or("").to_string()));            }            if let Some(o) = first.as_object_mut() {                o.insert("replayed".to_string(), json!(true));            }            return Ok(first);        }        // answered requests are kept 30 days, a bounded few pruned per act        ix.conn.prepare_cached("DELETE FROM request WHERE id IN (SELECT id FROM request WHERE at < ?1 ORDER BY at LIMIT 50)").map_err(db)?.execute([now - REQUEST_DAYS * 86_400_000]).map_err(db)?;        let out = dispatch(ix, method, request, now)?;        ix.conn.execute("INSERT INTO request (id, method, answer, at) VALUES (?1, ?2, ?3, ?4)", params![rid, method, out.to_string(), now]).map_err(db)?;        Ok(out)    })();    match &out {        Ok(_) => ix.conn.execute_batch("COMMIT").map_err(db)?,        Err(e) => {            ix.conn.execute_batch("ROLLBACK").map_err(db)?;            // a refused act is answered the same way when its request comes again;            // a passing refusal (still working, the disk) is not: a retry may pass            if let Some(rid) = request["request_id"].as_str().filter(|r| ACTS.contains(&method) && !r.is_empty() && !TRANSIENT.contains(&e.code.as_str())) {                let refusal = json!({ "refused": { "code": e.code, "message": e.message } });                ix.conn.execute("INSERT OR IGNORE INTO request (id, method, answer, at) VALUES (?1, ?2, ?3, ?4)", params![rid, method, refusal.to_string(), now]).map_err(db)?;            }        }    }    if CHECKPOINTS.contains(&method) && std::fs::metadata(&ix.wal).map_or(false, |m| m.len() > WAL_MAX) {        ix.conn.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(())).map_err(db)?;    }    out}/// Methods the shell calls off the tap, after which the write-ahead log is/// folded back into the file once it is large: a tap's commit never pays for/// that (rule 7).const WAL_MAX: u64 = 4 << 20;/// How long an answered request is kept for its replay.const REQUEST_DAYS: i64 = 30;/// Refusals that pass: never stored against a request id.const TRANSIENT: [&str; 2] = ["busy", "unwritable"];const CHECKPOINTS: [&str; 4] = ["albums.start", "albums.library.take", "albums.look.take", "albums.work"];fn dispatch(ix: &Index, method: &str, request: &Value, now: i64) -> Result<Value, MethodError> {    match method {        "albums.start" => start(ix, request),        "albums.library.take" => library_take(ix, request, now),        "albums.pass.next" => pass_next(ix, request),        "albums.look.take" => look_take(ix, request, now),        "albums.pass.lines" => pass_lines(ix, request),        "albums.home" => home(ix, request),        "albums.tidy" => tidy_screen(ix),        "albums.list" => list_screen(ix, request),        "albums.sets" => sets_screen(ix, request),        "albums.set" => set_screen(ix, request),        "albums.set.keep" => set_keep(ix, request, now),        "albums.keep" => keep(ix, request, now),        "albums.bin.move" => bin_move(ix, request, now),        "albums.undo" => undo(ix, request),        "albums.bin" => bin_screen(ix, request, now),        "albums.bin.bring_back" => bring_back(ix, request, now),        "albums.bin.delete" => bin_delete(ix, request, now),        "albums.bin.clear_other" => clear_other(ix, request, now),        "albums.you.clear_gone" => clear_gone(ix, request, now),        "albums.platform.done" => platform_done(ix, request),        "albums.work" => work(ix, now),        "albums.waiting" => waiting(ix),        "albums.you" => you(ix),        "albums.face.align" => face_align(request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not an albums method"))),    }}fn bad(why: impl Into<String>) -> MethodError {    MethodError::new("bad_request", why.into())}fn changed() -> MethodError {    MethodError::new("changed", words::CHANGED)}fn handed() -> MethodError {    MethodError::new("handed", words::HANDED)}fn db(e: rusqlite::Error) -> MethodError {    MethodError::new("unwritable", format!("{FILE}: {e}"))}// ── the index ───────────────────────────────────────────────────────────pub struct Index {    conn: Connection,    /// The file, so [`call`] knows the open index is the right one.    path: PathBuf,    /// The write-ahead log beside the file, folded back once it passes [`WAL_MAX`].    wal: PathBuf,    /// Rows the last refresh read (the tests hold the cost to it).    pub refreshed_rows: Cell<usize>,    /// Items one `albums.work` call plans or applies ([`WORK_BUDGET`]; the    /// tests make it small to cross slice boundaries).    pub work_budget: Cell<usize>,    /// The selection of the act being planned, parsed once.    selection: std::cell::RefCell<Option<(String, std::sync::Arc<BTreeSet<String>>)>>,}const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS item (id TEXT PRIMARY KEY, taken INTEGER NOT NULL, kind TEXT NOT NULL, w INTEGER NOT NULL, h INTEGER NOT NULL, bytes INTEGER, meta TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'present', part_of TEXT, cat TEXT, copy_of TEXT, cloud_id TEXT, fp TEXT NOT NULL DEFAULT '', ident TEXT NOT NULL DEFAULT '', verified INTEGER NOT NULL DEFAULT 1);CREATE INDEX IF NOT EXISTS item_taken ON item (taken);CREATE INDEX IF NOT EXISTS item_part ON item (part_of) WHERE part_of IS NOT NULL;CREATE INDEX IF NOT EXISTS item_copy ON item (copy_of) WHERE copy_of IS NOT NULL;CREATE INDEX IF NOT EXISTS item_cloud ON item (cloud_id) WHERE cloud_id IS NOT NULL;CREATE INDEX IF NOT EXISTS item_fp ON item (fp);CREATE TABLE IF NOT EXISTS look (id TEXT PRIMARY KEY, level INTEGER NOT NULL, dhash INTEGER NOT NULL, data TEXT NOT NULL, asked_net INTEGER NOT NULL DEFAULT 0);CREATE INDEX IF NOT EXISTS look_dhash ON look (dhash);CREATE TABLE IF NOT EXISTS look_band (band INTEGER NOT NULL, v INTEGER NOT NULL, id TEXT NOT NULL, PRIMARY KEY (band, v, id)) WITHOUT ROWID;CREATE TABLE IF NOT EXISTS mark (id TEXT PRIMARY KEY, mark TEXT NOT NULL, state TEXT NOT NULL, at INTEGER NOT NULL, act TEXT NOT NULL DEFAULT '', why TEXT NOT NULL DEFAULT '', seq INTEGER NOT NULL, fp TEXT NOT NULL DEFAULT '', suspended INTEGER NOT NULL DEFAULT 0);CREATE INDEX IF NOT EXISTS mark_state ON mark (state, at);CREATE INDEX IF NOT EXISTS mark_seq ON mark (state, seq, id);CREATE INDEX IF NOT EXISTS mark_why ON mark (why);CREATE INDEX IF NOT EXISTS mark_act ON mark (act, state);CREATE TABLE IF NOT EXISTS member (id TEXT PRIMARY KEY, set_id TEXT NOT NULL, pick INTEGER NOT NULL, rank INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS member_set ON member (set_id);CREATE TABLE IF NOT EXISTS shot_set (set_id TEXT PRIMARY KEY, first INTEGER NOT NULL, count INTEGER NOT NULL, picks INTEGER NOT NULL, sure INTEGER NOT NULL, bytes INTEGER NOT NULL, exact INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS shot_set_order ON shot_set (bytes DESC, first DESC, set_id);CREATE TABLE IF NOT EXISTS offer (id TEXT PRIMARY KEY, list TEXT NOT NULL, bytes INTEGER NOT NULL, exact INTEGER NOT NULL, taken INTEGER NOT NULL, sub TEXT NOT NULL DEFAULT '', of TEXT, seq INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS offer_list ON offer (list, taken);CREATE INDEX IF NOT EXISTS offer_seq ON offer (list, seq, id);CREATE TABLE IF NOT EXISTS act (id TEXT PRIMARY KEY, at INTEGER NOT NULL, by TEXT NOT NULL, kind TEXT NOT NULL, state TEXT NOT NULL, list TEXT, n INTEGER NOT NULL, token INTEGER, shown INTEGER, sel TEXT, cursor_seq INTEGER, cursor_id TEXT, planned INTEGER NOT NULL DEFAULT 0, skipped INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS act_item (act TEXT NOT NULL, pos INTEGER NOT NULL, id TEXT NOT NULL, after_mark TEXT NOT NULL, after_why TEXT NOT NULL, expect TEXT NOT NULL, before_mark TEXT, before_why TEXT, before_act TEXT, applied INTEGER NOT NULL DEFAULT 0, note TEXT, main INTEGER NOT NULL DEFAULT 1, fp TEXT NOT NULL DEFAULT '', PRIMARY KEY (act, pos));CREATE INDEX IF NOT EXISTS act_item_id ON act_item (act, id);CREATE INDEX IF NOT EXISTS act_item_item ON act_item (id);CREATE TABLE IF NOT EXISTS absent (id TEXT PRIMARY KEY, token TEXT NOT NULL);CREATE TABLE IF NOT EXISTS request (id TEXT PRIMARY KEY, method TEXT NOT NULL, answer TEXT NOT NULL, at INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS request_at ON request (at);CREATE TABLE IF NOT EXISTS tally (k TEXT PRIMARY KEY, n INTEGER NOT NULL, bytes INTEGER NOT NULL, inexact INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS kv (k TEXT PRIMARY KEY, v TEXT NOT NULL);";/// act_item.applied (0 while waiting): applied, skipped (his choice or the/// library had changed), undone, settled freed, settled back in the Bin.const APPLIED: i64 = 1;const SKIPPED: i64 = 2;const UNDONE: i64 = 3;const FREED: i64 = 5;const BACK: i64 = 6;/// A photo `free_plan` handed to the phone (waiting for the library to settle it).const HANDED: i64 = 7;impl Index {    pub fn open(path: &Path) -> Result<Index, MethodError> {        if let Some(parent) = path.parent() {            std::fs::create_dir_all(parent).map_err(|e| MethodError::new("unwritable", format!("{}: {e}", parent.display())))?;        }        let conn = Connection::open(path).map_err(db)?;        // the log is folded back into the file off the tap (CHECKPOINTS), never inside one        conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA wal_autocheckpoint=0;").map_err(db)?;        conn.set_prepared_statement_cache_capacity(128);        conn.execute_batch(SCHEMA).map_err(db)?;        let mut wal = path.as_os_str().to_owned();        wal.push("-wal");        let ix = Index { conn, path: path.to_path_buf(), wal: PathBuf::from(wal), refreshed_rows: Cell::new(0), work_budget: Cell::new(WORK_BUDGET), selection: std::cell::RefCell::new(None) };        if ix.get("tally").as_deref() != Some("1") {            rebuild_tally(&ix)?;            ix.set("tally", "1")?;        }        Ok(ix)    }    pub fn path_in(dir: &Path) -> PathBuf {        dir.join(FILE)    }    fn get(&self, k: &str) -> Option<String> {        self.conn.query_row("SELECT v FROM kv WHERE k = ?1", [k], |r| r.get(0)).optional().ok().flatten()    }    fn set(&self, k: &str, v: &str) -> Result<(), MethodError> {        self.conn.execute("INSERT INTO kv (k, v) VALUES (?1, ?2) ON CONFLICT (k) DO UPDATE SET v = excluded.v", [k, v]).map(|_| ()).map_err(db)    }    /// The next number in one sequence shared by offers and marks: a list's    /// or the Bin's snapshot is everything with a number up to its token.    fn next_seq(&self) -> Result<i64, MethodError> {        let n = self.get("seq").and_then(|v| v.parse::<i64>().ok()).unwrap_or(0) + 1;        self.set("seq", &n.to_string())?;        Ok(n)    }    fn seq_now(&self) -> i64 {        self.get("seq").and_then(|v| v.parse().ok()).unwrap_or(0)    }    fn platform(&self) -> Platform {        match self.get("platform").as_deref() {            Some("android") => Platform::Android,            _ => Platform::Ios,        }    }    fn offset(&self) -> i64 {        self.get("offset_s").and_then(|v| v.parse().ok()).unwrap_or(0)    }    fn state(&self) -> State {        self.get("pass_state").and_then(|s| serde_json::from_str(&format!("\"{s}\"")).ok()).unwrap_or(State::NotStarted)    }    fn charging(&self) -> bool {        self.get("charging").as_deref() == Some("1")    }    fn item(&self, id: &str) -> Option<Item> {        self.conn.prepare_cached("SELECT meta FROM item WHERE id = ?1").ok()?.query_row([id], |r| r.get::<_, String>(0)).optional().ok().flatten().and_then(|m| serde_json::from_str(&m).ok())    }    /// The item's library state: `present`, `trashed`, `absent`, or empty    /// when the index has never seen it.    fn lib(&self, id: &str) -> String {        self.conn.prepare_cached("SELECT state FROM item WHERE id = ?1").ok().and_then(|mut s| s.query_row([id], |r| r.get::<_, String>(0)).optional().ok().flatten()).unwrap_or_default()    }    fn present(&self, id: &str) -> bool {        self.lib(id) == "present"    }    fn is_part(&self, id: &str) -> bool {        self.conn.prepare_cached("SELECT part_of IS NOT NULL FROM item WHERE id = ?1").ok().and_then(|mut s| s.query_row([id], |r| r.get::<_, bool>(0)).optional().ok().flatten()).unwrap_or(false)    }    fn copy_of(&self, id: &str) -> Option<String> {        self.conn.prepare_cached("SELECT copy_of FROM item WHERE id = ?1").ok().and_then(|mut s| s.query_row([id], |r| r.get::<_, Option<String>>(0)).optional().ok().flatten().flatten())    }    fn copies_of(&self, id: &str) -> Vec<String> {        let Ok(mut stmt) = self.conn.prepare_cached("SELECT id FROM item WHERE copy_of = ?1 AND state = 'present'") else { return Vec::new() };        stmt.query_map([id], |r| r.get(0)).map(|m| m.filter_map(Result::ok).collect()).unwrap_or_default()    }    fn mark_row(&self, id: &str) -> (Mark, String, String) {        self.conn            .prepare_cached("SELECT mark, why, act FROM mark WHERE id = ?1")            .ok()            .and_then(|mut s| s.query_row([id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?))).optional().ok().flatten())            .map(|(m, w, a)| (serde_json::from_str(&m).unwrap_or(Mark::None), w, a))            .unwrap_or((Mark::None, String::new(), String::new()))    }    fn mark(&self, id: &str) -> Mark {        self.mark_row(id).0    }    /// Whether the last read confirmed this id still names the photo the index    /// holds (decision 1f, tier one). Nothing unverified is planned.    fn verified(&self, id: &str) -> bool {        self.conn.prepare_cached("SELECT verified FROM item WHERE id = ?1").ok().and_then(|mut s| s.query_row([id], |r| r.get::<_, bool>(0)).optional().ok().flatten()).unwrap_or(false)    }    /// The photo's content facts as the reads gave them (empty when never read).    fn fp(&self, id: &str) -> String {        self.conn.prepare_cached("SELECT fp FROM item WHERE id = ?1").ok().and_then(|mut s| s.query_row([id], |r| r.get::<_, String>(0)).optional().ok().flatten()).unwrap_or_default()    }    /// The content facts of the photo a mark was made on.    fn mark_fp(&self, id: &str) -> String {        self.conn.prepare_cached("SELECT fp FROM mark WHERE id = ?1").ok().and_then(|mut s| s.query_row([id], |r| r.get::<_, String>(0)).optional().ok().flatten()).unwrap_or_default()    }    fn parts_of(&self, id: &str) -> Vec<String> {        let Ok(mut stmt) = self.conn.prepare_cached("SELECT id FROM item WHERE part_of = ?1") else { return Vec::new() };        stmt.query_map([id], |r| r.get(0)).map(|m| m.filter_map(Result::ok).collect()).unwrap_or_default()    }    fn look_of(&self, id: &str) -> Option<Look> {        self.conn.prepare_cached("SELECT data FROM look WHERE id = ?1").ok()?.query_row([id], |r| r.get::<_, String>(0)).optional().ok().flatten().and_then(|d| decode_look(&d))    }    fn progress(&self) -> Progress {        let mut p: Progress = self.get("progress").and_then(|v| serde_json::from_str(&v).ok()).unwrap_or_default();        p.total = tally(self, "photos").0;        p.looked = tally(self, "looked").0;        p.cloud_only = tally(self, "cloud").0;        p    }    fn count(&self, sql: &str) -> usize {        self.conn.query_row(sql, [], |r| r.get::<_, i64>(0)).unwrap_or(0) as usize    }    /// The ids an act was given, parsed once and kept while it plans.    fn selection(&self, act: &str) -> std::sync::Arc<BTreeSet<String>> {        if let Some((a, set)) = self.selection.borrow().as_ref() {            if a == act {                return set.clone();            }        }        let sel: Option<String> = self.conn.query_row("SELECT sel FROM act WHERE id = ?1", [act], |r| r.get(0)).optional().ok().flatten().flatten();        let set: std::sync::Arc<BTreeSet<String>> = std::sync::Arc::new(sel.map(|s| serde_json::from_str::<Vec<String>>(&s).unwrap_or_default().into_iter().collect::<BTreeSet<String>>()).unwrap_or_default());        *self.selection.borrow_mut() = Some((act.to_string(), set.clone()));        set    }    fn next_act_id(&self, now: i64) -> String {        format!("act-{now}-{}", self.count("SELECT count(*) FROM act"))    }}fn state_of(m: &Mark) -> &'static str {    match m {        Mark::None => "none",        Mark::Keep { .. } => "keep",        Mark::Bin { .. } => "bin",        Mark::Handed { .. } => "handed",        Mark::Freed { .. } => "freed",    }}/// The marks an act may write. `Handed` is not one of them: only/// [`handing::free_plan`] can hand a photo to the phone (the compiler is the/// lint, rule 2).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) enum Chosen {    None,    Keep { at_ms: i64 },    Bin { at_ms: i64 },    Freed { at_ms: i64 },}impl From<Chosen> for Mark {    fn from(c: Chosen) -> Mark {        match c {            Chosen::None => Mark::None,            Chosen::Keep { at_ms } => Mark::Keep { at_ms },            Chosen::Bin { at_ms } => Mark::Bin { at_ms },            Chosen::Freed { at_ms } => Mark::Freed { at_ms },        }    }}impl Chosen {    /// A stored mark as a choice an act may write back (undo); a handed one is not.    fn from_mark(m: Mark) -> Option<Chosen> {        match m {            Mark::None => Some(Chosen::None),            Mark::Keep { at_ms } => Some(Chosen::Keep { at_ms }),            Mark::Bin { at_ms } => Some(Chosen::Bin { at_ms }),            Mark::Freed { at_ms } => Some(Chosen::Freed { at_ms }),            Mark::Handed { .. } => None,        }    }    fn in_bin(self) -> bool {        matches!(self, Chosen::Bin { .. })    }}/// Write a choice (the row stays when it is none, so the act that set it is/// known: undo is newest first per item). The mark carries the fingerprint of/// the photo it was made on.fn put_mark(ix: &Index, id: &str, mark: Chosen, act: &str, why: &str) -> Result<(), MethodError> {    handing::put_choice(ix, id, mark, act, why)}/// A marked item that joins the Bin or a list again unseen (back in the/// library, or a part whose main went) gets a new number, so no snapshot/// taken before can take it (rule B).fn renumber_mark(ix: &Index, id: &str) -> Result<(), MethodError> {    let seq = ix.next_seq()?;    ix.conn.prepare_cached("UPDATE mark SET seq = ?2 WHERE id = ?1").map_err(db)?.execute(params![id, seq]).map(|_| ()).map_err(db)}// ── counts kept as they change (rule F: no screen call scans the library) ──type Contrib = Vec<(String, i64, i64, i64)>;/// What one item adds to the counts the screens draw.fn contrib(ix: &Index, id: &str) -> Result<Contrib, MethodError> {    type R = (String, bool, String, String, Option<i64>, Option<String>, Option<i64>, Option<bool>, Option<String>, Option<String>, Option<bool>);    let row: Option<R> = ix        .conn        .prepare_cached(            "SELECT item.state, item.part_of IS NULL, item.kind, item.meta, look.level, offer.list, offer.bytes, offer.exact, offer.sub, mark.state, mark.suspended FROM item LEFT JOIN look ON look.id = item.id LEFT JOIN offer ON offer.id = item.id LEFT JOIN mark ON mark.id = item.id WHERE item.id = ?1",        )        .map_err(db)?        .query_row([id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?, r.get(7)?, r.get(8)?, r.get(9)?, r.get(10)?)))        .optional()        .map_err(db)?;    let Some((lib, main, kind, meta, level, list, bytes, exact, sub, state, suspended)) = row else { return Ok(Vec::new()) };    if suspended == Some(true) {        // a choice from another phone or library: counted alone, never in the Bin (decision H.b)        return Ok(vec![("suspended".to_string(), 1, 0, 0)]);    }    if id.contains("#retired-") {        // a choice on a photo no longer on this phone: counted in You, never in the Bin        return Ok(if matches!(state.as_deref(), Some("bin" | "keep")) { vec![("retired".to_string(), 1, 0, 0)] } else { Vec::new() });    }    let present = lib == "present";    let mut out = Vec::new();    if present && main {        out.push(("items".to_string(), 1, 0, 0));        if kind == "photo" {            out.push(("photos".to_string(), 1, 0, 0));            if level.is_some() {                out.push(("looked".to_string(), 1, 0, 0));            }        }    }    if present && level == Some(0) {        out.push(("cloud".to_string(), 1, 0, 0));    }    if let (Some(l), Some(b)) = (list, bytes) {        let inexact = i64::from(!exact.unwrap_or(true));        if sub.as_deref().is_some_and(|s| s.starts_with("copy:")) {            out.push((format!("list:{l}:copy"), 1, b, inexact));        }        out.push((format!("list:{l}"), 1, b, inexact));    }    if present && state.as_deref() == Some("bin") {        let s = serde_json::from_str::<Item>(&meta).map(|i| size::of(&i)).unwrap_or(size::Size::ZERO);        out.push(("bin".to_string(), i64::from(main), s.bytes as i64, i64::from(!s.exact)));    }    if state.as_deref() == Some("handed") {        out.push(("handed".to_string(), 1, 0, 0));    }    Ok(out)}fn apply_tally(ix: &Index, c: &[(String, i64, i64, i64)], sign: i64) -> Result<(), MethodError> {    let mut stmt = ix        .conn        .prepare_cached("INSERT INTO tally (k, n, bytes, inexact) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (k) DO UPDATE SET n = n + excluded.n, bytes = bytes + excluded.bytes, inexact = inexact + excluded.inexact")        .map_err(db)?;    for (k, n, b, i) in c {        stmt.execute(params![k, n * sign, b * sign, i * sign]).map_err(db)?;    }    Ok(())}/// Run a change to one item and move the counts by what it changed.fn track<T>(ix: &Index, id: &str, f: impl FnOnce() -> Result<T, MethodError>) -> Result<T, MethodError> {    let before = contrib(ix, id)?;    let out = f()?;    let after = contrib(ix, id)?;    if before != after {        apply_tally(ix, &before, -1)?;        apply_tally(ix, &after, 1)?;    }    Ok(out)}fn tally(ix: &Index, k: &str) -> (usize, u64, bool) {    ix.conn        .prepare_cached("SELECT n, bytes, inexact FROM tally WHERE k = ?1")        .ok()        .and_then(|mut s| s.query_row([k], |r| Ok((r.get::<_, i64>(0)?.max(0) as usize, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, i64>(2)? == 0))).optional().ok().flatten())        .unwrap_or((0, 0, true))}/// The counts from scratch (once, for an index made before they were kept;/// and by the tests, to prove the running counts true).fn counted(ix: &Index) -> Result<BTreeMap<String, (i64, i64, i64)>, MethodError> {    let ids: Vec<String> = ix.conn.prepare("SELECT id FROM item").map_err(db)?.query_map([], |r| r.get(0)).map_err(db)?.filter_map(Result::ok).collect();    let mut out: BTreeMap<String, (i64, i64, i64)> = BTreeMap::new();    for id in ids {        for (k, n, b, i) in contrib(ix, &id)? {            let e = out.entry(k).or_default();            e.0 += n;            e.1 += b;            e.2 += i;        }    }    out.insert("sets".to_string(), (ix.count("SELECT count(*) FROM shot_set") as i64, 0, 0));    Ok(out)}fn rebuild_tally(ix: &Index) -> Result<(), MethodError> {    ix.conn.execute("DELETE FROM tally", []).map_err(db)?;    for (k, (n, b, i)) in counted(ix)? {        ix.conn.execute("INSERT INTO tally (k, n, bytes, inexact) VALUES (?1, ?2, ?3, ?4)", params![k, n, b, i]).map_err(db)?;    }    Ok(())}/// An item's size with the parts that move with it.fn size_with_parts(ix: &Index, item: &Item) -> size::Size {    with_parts(ix, &item.id).iter().skip(1).filter_map(|p| ix.item(p)).fold(size::of(item), |a, p| a.add(size::of(&p)))}/// An item and its parts that share its choice: a part he chose on its own/// (kept) never follows its main.fn with_parts(ix: &Index, id: &str) -> Vec<String> {    let mine = state_of(&ix.mark(id));    let mut out = vec![id.to_string()];    out.extend(ix.parts_of(id).into_iter().filter(|p| state_of(&ix.mark(p)) == mine && ix.present(p)));    out}fn when_of(ix: &Index, item: &Item, this_year: i64) -> String {    words::when(item.taken_at_ms, item.offset_s.unwrap_or_else(|| ix.offset()), this_year)}// ── storing looks: the core's own measures only ─────────────────────/// A look as the index keeps it. A platform's feature print (Vision's,/// Android's) stays in the shell's own store and never comes here: the core/// groups by its own print and difference hash.fn encode_look(l: &Look) -> String {    let mut bare = l.clone();    bare.platform.print = None;    serde_json::to_string(&bare).unwrap()}fn decode_look(data: &str) -> Option<Look> {    serde_json::from_str(data).ok()}/// The difference hash in 11 bands (nine of 6 bits, two of 5): two hashes/// within [`tidy::COPY_HAMMING_MAX`] (10) share at least one band whole, so/// a copy's original is found by index, never by reading a month of photos.fn bands(h: u64) -> [(i64, i64); 11] {    let mut out = [(0, 0); 11];    let mut shift = 0;    for (b, slot) in out.iter_mut().enumerate() {        let width = if b < 9 { 6 } else { 5 };        *slot = (b as i64, ((h >> shift) & ((1u64 << width) - 1)) as i64);        shift += width;    }    out}/// A short hash of a set of ids (FNV-1a over them sorted): two sweeps agree/// when their hashes match.fn ids_hash(ids: &[&str]) -> String {    let mut sorted: Vec<&str> = ids.to_vec();    sorted.sort_unstable();    sorted.dedup();    let mut h: u64 = 0xcbf2_9ce4_8422_2325;    for id in sorted {        for b in id.bytes().chain(std::iter::once(0)) {            h ^= b as u64;            h = h.wrapping_mul(0x0100_0000_01b3);        }    }    format!("{h:016x}")}// ── start and the library ───────────────────────────────────────────────/// What the app opens on: `first_run`, `no_permission`, `limited` or `home`./// Request: `{platform: ios|android, permission: none|full|limited|denied,/// chosen?, offset_s, library?}` (`library`: the library's identity, see/// [`check_library`]).fn start(ix: &Index, r: &Value) -> Result<Value, MethodError> {    check_library(ix, r)?;    if let Some(p) = r["platform"].as_str() {        if p != "ios" && p != "android" {            return Err(bad("platform is ios or android"));        }        ix.set("platform", p)?;    }    if let Some(o) = r["offset_s"].as_i64() {        ix.set("offset_s", &o.to_string())?;    }    let permission = r["permission"].as_str().unwrap_or("none");    if !matches!(permission, "none" | "full" | "limited" | "denied") {        return Err(bad("permission is none, full, limited or denied"));    }    ix.set("permission", permission)?;    let screen = match (permission, ix.state()) {        ("denied", _) => "no_permission",        ("none", State::NotStarted) => "first_run",        ("limited", _) => "limited",        _ => "home",    };    let mut out = json!({ "screen": screen });    match screen {        "first_run" => {            out["lines"] = json!(words::WELCOME_LINES);            out["promise"] = json!(words::WELCOME_PROMISE);            out["start"] = json!(words::START);            out["permission_why"] = json!(words::PERMISSION_WHY);        }        "no_permission" => {            out["line"] = json!(words::NO_PERMISSION);            out["act"] = json!(words::OPEN_SETTINGS);        }        "limited" => {            out["line"] = json!(words::limited(r["chosen"].as_u64().unwrap_or(0) as usize));            out["act"] = json!(words::OPEN_SETTINGS);        }        _ => {}    }    if (permission == "full" || permission == "limited") && ix.state() == State::NotStarted {        ix.set("pass_state", "running")?;    }    out["waiting"] = json!(tally(ix, "handed").0);    out["other_library"] = json!(tally(ix, "suspended").0);    out["rechecking"] = json!(rechecking(ix));    Ok(out)}/// Whether this phone may Delete: the iPhone with full access only. Android/// stays look-only for now (owner decision, 27 Nov 2026: its id reuse and/// MediaStore versions are made safe by never handing it anything).fn deletes_here(ix: &Index) -> bool {    ix.platform() == Platform::Ios && ix.get("permission").as_deref() == Some("full")}/// After the library's identity changed, until a full read (a sweep) has/// re-matched what it can.fn rechecking(ix: &Index) -> bool {    ix.get("rechecking").as_deref() == Some("1")}/// The identity of the library the ids belong to (Android: the MediaStore/// version and volume; iPhone: the library's id where readable). When it/// changes (another phone, a restored backup, or simply an Android update: the/// MediaStore version changes with it), no id is trusted until read again/// (decision 1f, finding 2): every item is unverified and offered nowhere,/// every choice waits (suspended), and the shell reads everything again. Each/// id read again is decided by its identity: the same photo gets its choices/// back; another photo starts clean, and the old one's choices wait for a/// photo with the same cloud id or exact facts. What no full read re-matched/// stays suspended until he clears it.fn check_library(ix: &Index, r: &Value) -> Result<(), MethodError> {    let Some(id) = r["library"].as_str().filter(|l| !l.is_empty()) else { return Ok(()) };    match ix.get("library") {        Some(old) if old != id => {            // a Delete the phone may have been answering: settled as gone (1e)            let handed: Vec<(String, String)> = ix.conn.prepare("SELECT id, act FROM mark WHERE state = 'handed'").map_err(db)?.query_map([], |q| Ok((q.get(0)?, q.get(1)?))).map_err(db)?.filter_map(Result::ok).collect();            for (h, by) in handed {                handing::settle_one(ix, &by, &h, "absent", 0)?;            }            ix.conn.execute_batch("UPDATE mark SET suspended = 1 WHERE state IN ('bin', 'keep'); UPDATE item SET verified = 0; DELETE FROM offer; DELETE FROM absent").map_err(db)?;            rebuild_tally(ix)?;            ix.set("rechecking", "1")?;            ix.set("library", id)        }        Some(_) => Ok(()),        None => ix.set("library", id),    }}/// Identity (decision 1f, tier one): facts an edit cannot change. Kind, cloud/// id, and on Android when the photo joined the library (`DATE_ADDED`,/// `GENERATION_ADDED`). An iPhone's `localIdentifier` is the id itself.fn identity(it: &Item) -> String {    format!("{}|{}|{}|{}", kind_key(it.kind), it.cloud_id.as_deref().unwrap_or(""), known(it.added_ms), known(it.generation_added))}/// Content (tier two): what an edit changes. Size, pixel size, date taken,/// the modification stamp; zero or missing is unknown.fn content(it: &Item) -> String {    let nz = |v: i64| if v == 0 { String::new() } else { v.to_string() };    format!("{}|{}|{}|{}|{}", known(it.bytes.filter(|b| *b > 0).map(|b| b as i64)), nz(i64::from(it.width)), nz(i64::from(it.height)), nz(it.taken_at_ms), known(it.modified))}fn known(v: Option<i64>) -> String {    v.map_or(String::new(), |v| v.to_string())}/// A read laid over the stored facts: a fact the read does not know keeps the/// stored one, so facts never drift A → unknown → B unseen; a fact that/// arrives later fills in.fn merge_facts(old: &str, new: &str) -> String {    let (o, n): (Vec<&str>, Vec<&str>) = (old.split('|').collect(), new.split('|').collect());    if old.is_empty() || o.len() != n.len() {        return new.to_string();    }    o.iter().zip(&n).map(|(o, n)| if n.is_empty() { *o } else { *n }).collect::<Vec<_>>().join("|")}/// The facts a choice was made on, with what it did not know filled in.fn fill_in(chosen: &str, now: &str) -> String {    let (c, n): (Vec<&str>, Vec<&str>) = (chosen.split('|').collect(), now.split('|').collect());    if chosen.is_empty() || c.len() != n.len() {        return chosen.to_string();    }    c.iter().zip(&n).map(|(c, n)| if c.is_empty() { *n } else { *c }).collect::<Vec<_>>().join("|")}/// What tier one says of an id read again.#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Ident {    Same,    Other,    /// Nothing known on both sides proves it either way.    Unknown,}/// Whether a read of an id names the photo the index holds. A fact both know/// that differs is another photo; one both know that agrees (or, on an/// iPhone, the id itself) proves the same; an unknown fact proves nothing./// `across` a library change the id proves nothing and generations are not/// comparable.fn same_identity(old: &str, new: &str, id_is_identity: bool, across: bool) -> Ident {    let (o, n): (Vec<&str>, Vec<&str>) = (old.split('|').collect(), new.split('|').collect());    if o.len() != 4 || n.len() != 4 {        return Ident::Unknown;    }    if o[0] != n[0] {        return Ident::Other;    }    let mut agree = 0;    for k in 1..4 {        if across && k == 3 {            continue;        }        if !o[k].is_empty() && !n[k].is_empty() {            if o[k] != n[k] {                return Ident::Other;            }            agree += 1;        }    }    if agree > 0 || (id_is_identity && !across) {        Ident::Same    } else {        Ident::Unknown    }}/// A content fact both know differs.fn facts_differ(a: &str, b: &str) -> bool {    let (a, b): (Vec<&str>, Vec<&str>) = (a.split('|').collect(), b.split('|').collect());    a.len() != b.len() || a.iter().zip(&b).any(|(x, y)| !x.is_empty() && !y.is_empty() && x != y)}/// Whether the photo changed since a choice was made on it (tier two): a fact/// both know differs; facts wholly unknown on either side match nothing.fn content_changed(chosen: &str, now: &str) -> bool {    let empty = |f: &str| f.split('|').all(str::is_empty);    empty(chosen) || empty(now) || facts_differ(chosen, now)}/// A binned photo he edited after binning it: it stays in the Bin, and no/// Delete hands it until he bins it again.fn edited(ix: &Index, id: &str) -> bool {    ix.mark(id).in_bin() && content_changed(&ix.mark_fp(id), &ix.fp(id))}/// An id that now names another photo (tier one): the old item becomes absent/// under a retired key that no read can name, with its marks (never applied/// to the new photo); what pointed at it as an original now points at the/// retired key. A handed one is settled as gone first. Answers the key.fn retire(ix: &Index, id: &str, dates: &mut Vec<i64>) -> Result<Option<String>, MethodError> {    let Some(taken) = ix.conn.prepare_cached("SELECT taken FROM item WHERE id = ?1").map_err(db)?.query_row([id], |q| q.get::<_, i64>(0)).optional().map_err(db)? else { return Ok(None) };    dates.push(taken);    let (m, _, by) = ix.mark_row(id);    if m.handed() {        handing::settle_one(ix, &by, id, "absent", 0)?;    }    let key = format!("{id}#retired-{}", ix.next_seq()?);    track(ix, id, || {        for sql in ["DELETE FROM look WHERE id = ?1", "DELETE FROM look_band WHERE id = ?1", "DELETE FROM member WHERE id = ?1", "DELETE FROM offer WHERE id = ?1", "DELETE FROM absent WHERE id = ?1"] {            ix.conn.prepare_cached(sql).map_err(db)?.execute([id]).map_err(db)?;        }        Ok(())    })?;    for p in ix.parts_of(id) {        track(ix, &p, || ix.conn.execute("UPDATE item SET part_of = NULL WHERE id = ?1", [&p]).map(|_| ()).map_err(db))?;        renumber_mark(ix, &p)?;    }    // its copies keep it as their original: the retired one, gone (held_reason)    let copies: Vec<(String, i64)> = ix.conn.prepare_cached("SELECT id, taken FROM item WHERE copy_of = ?1").map_err(db)?.query_map([id], |q| Ok((q.get(0)?, q.get(1)?))).map_err(db)?.filter_map(Result::ok).collect();    for (c, t) in &copies {        track(ix, c, || ix.conn.prepare_cached("UPDATE item SET copy_of = ?2 WHERE id = ?1").map_err(db)?.execute(params![c, key]).map(|_| ()).map_err(db))?;        dates.push(*t);    }    let (was, now_why) = (format!("copy:{id}"), format!("copy:{key}"));    ix.conn.prepare_cached("UPDATE mark SET why = ?2 WHERE why = ?1").map_err(db)?.execute(params![was, now_why]).map_err(db)?;    ix.conn.prepare_cached("UPDATE act_item SET after_why = ?2 WHERE after_why = ?1").map_err(db)?.execute(params![was, now_why]).map_err(db)?;    track(ix, id, || {        ix.conn.prepare_cached("UPDATE item SET id = ?2, state = 'absent', part_of = NULL, copy_of = NULL WHERE id = ?1").map_err(db)?.execute(params![id, key]).map_err(db)?;        ix.conn.prepare_cached("UPDATE mark SET id = ?2 WHERE id = ?1").map_err(db)?.execute(params![id, key]).map(|_| ()).map_err(db)    })?;    // the retired row counts under its own key (You, or a waiting choice)    apply_tally(ix, &contrib(ix, &key)?, 1)?;    Ok(Some(key))}/// A suspended choice whose photo a read shows under another id, by its exact/// cloud id or its exact content (size and date known, and the same kind),/// comes back onto it (decision H.b). Facts wholly unknown match nothing.fn rematch_suspended(ix: &Index, it: &Item, fp: &str) -> Result<(), MethodError> {    if ix.conn.prepare_cached("SELECT 1 FROM mark WHERE id = ?1").map_err(db)?.exists([&it.id]).map_err(db)? {        return Ok(());    }    let cloud = it.cloud_id.as_deref().filter(|c| !c.is_empty());    let f: Vec<&str> = fp.split('|').collect();    let exact = (f.len() == 5 && !f[0].is_empty() && !f[3].is_empty()).then_some(fp);    if cloud.is_none() && exact.is_none() {        return Ok(());    }    let found: Vec<String> = ix        .conn        .prepare_cached("SELECT mark.id FROM mark JOIN item ON item.id = mark.id WHERE mark.suspended = 1 AND mark.id <> ?3 AND item.kind = ?4 AND ((?1 IS NOT NULL AND item.cloud_id = ?1) OR (?2 IS NOT NULL AND item.fp = ?2))")        .map_err(db)?        .query_map(params![cloud, exact, it.id, kind_key(it.kind)], |q| q.get(0))        .map_err(db)?        .filter_map(Result::ok)        .collect();    if let [from] = found.as_slice() {        track(ix, from, || ix.conn.prepare_cached("UPDATE mark SET id = ?2, suspended = 0 WHERE id = ?1").map_err(db)?.execute(params![from, it.id]).map(|_| ()).map_err(db))?;        renumber_mark(ix, &it.id)?;    }    Ok(())}/// The library no longer shows an item as present (`absent` or `trashed`):/// drop what was measured (rule A); its row and his marks stay; its parts/// become items of their own.fn leave_library(ix: &Index, id: &str, to: &str, now: i64, dates: &mut Vec<i64>) -> Result<(), MethodError> {    if let Some(t) = ix.conn.prepare_cached("SELECT taken FROM item WHERE id = ?1").map_err(db)?.query_row([id], |r| r.get::<_, i64>(0)).optional().map_err(db)? {        dates.push(t);    }    // a handed photo the library no longer shows is settled at once (rule 3)    let (m, _, by) = ix.mark_row(id);    if m.handed() {        handing::settle_one(ix, &by, id, to, now)?;    }    track(ix, id, || {        ix.conn.prepare_cached("UPDATE item SET state = ?2 WHERE id = ?1").map_err(db)?.execute(params![id, to]).map_err(db)?;        for sql in ["DELETE FROM look WHERE id = ?1", "DELETE FROM look_band WHERE id = ?1", "DELETE FROM member WHERE id = ?1", "DELETE FROM offer WHERE id = ?1"] {            ix.conn.prepare_cached(sql).map_err(db)?.execute([id]).map_err(db)?;        }        Ok(())    })?;    for p in ix.parts_of(id) {        track(ix, &p, || ix.conn.execute("UPDATE item SET part_of = NULL WHERE id = ?1", [&p]).map(|_| ()).map_err(db))?;        renumber_mark(ix, &p)?;    }    Ok(())}/// A report that an item is not in the library: believed only when a report/// with another token said so before (rule 5). Answers whether it was believed.fn report_absent(ix: &Index, id: &str, token: &str, now: i64, dates: &mut Vec<i64>) -> Result<bool, MethodError> {    if ix.lib(id).is_empty() || ix.lib(id) == "absent" || ix.get("permission").as_deref() != Some("full") {        return Ok(false);    }    let before: Option<String> = ix.conn.prepare_cached("SELECT token FROM absent WHERE id = ?1").map_err(db)?.query_row([id], |r| r.get(0)).optional().map_err(db)?;    match before {        Some(t) if t != token => {            ix.conn.prepare_cached("DELETE FROM absent WHERE id = ?1").map_err(db)?.execute([id]).map_err(db)?;            leave_library(ix, id, "absent", now, dates)?;            Ok(true)        }        Some(_) => Ok(false),        None => {            ix.conn.prepare_cached("INSERT INTO absent (id, token) VALUES (?1, ?2)").map_err(db)?.execute(params![id, token]).map_err(db)?;            Ok(false)        }    }}/// The shell's reading of the library:/// `{items?: [Item], states?: [{id, state: present|trashed|absent}], removed?: [id],/// all_ids?: [id], complete?: bool, token?: string, act_id?: string}`.////// - `items`: what the library shows, in batches; Android includes its trash,///   flagged `trashed`. An item seen again is believed at once./// - `states`: each id read on its own. With `act_id` (after a Delete) it///   settles that act's handed items: absent or trashed → freed; present →///   back in the Bin. This is the only way a Delete ends./// - `removed` (the library's change report), `states` absent without an///   act, and a sweep (`all_ids`, needs full permission, `complete: true` and///   the library's change `token`) are believed only when two reports with///   different tokens agree (rule 5). Absence removes no choice (rule A).fn library_take(ix: &Index, r: &Value, now: i64) -> Result<Value, MethodError> {    check_library(ix, r)?;    let items: Vec<Item> = serde_json::from_value(if r["items"].is_null() { json!([]) } else { r["items"].clone() }).map_err(|e| bad(format!("items: {e}")))?;    if items.iter().any(|it| it.id.is_empty()) {        return Err(bad("an item has no id"));    }    let states: Vec<(String, String)> = r["states"]        .as_array()        .map(|a| a.iter().map(|s| (s["id"].as_str().unwrap_or("").to_string(), s["state"].as_str().unwrap_or("").to_string())).collect())        .unwrap_or_default();    if states.iter().any(|(id, st)| id.is_empty() || !matches!(st.as_str(), "present" | "trashed" | "absent")) {        return Err(bad("states: [{id, state: present|trashed|absent}]"));    }    let token = r["token"].as_str().filter(|t| !t.is_empty());    let removed: Vec<String> = serde_json::from_value(r["removed"].clone()).unwrap_or_default();    let mut dates = Vec::new();    let mut came_back = Vec::new();    let mut renamed = 0usize;    let mut edits = 0usize;    let ios = ix.platform() == Platform::Ios;    let across_all = rechecking(ix);    for it in &items {        let (ident_new, fp_new) = (identity(it), content(it));        type Old = (String, String, String, bool);        let mut old: Option<Old> = ix.conn.prepare_cached("SELECT state, ident, fp, verified FROM item WHERE id = ?1").map_err(db)?.query_row([&it.id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))).optional().map_err(db)?;        let to = if it.has("trashed") { "trashed" } else { "present" };        let mut verified = true;        if let Some((_, oi, of, ov)) = old.clone() {            // the first read of an id since the library changed is decisive            let across = across_all && !ov;            match same_identity(&oi, &ident_new, ios, across) {                Ident::Other => {                    retire(ix, &it.id, &mut dates)?;                    renamed += 1;                    old = None;                }                Ident::Unknown if across => {                    // not proven the same photo: its choices wait for one that is                    retire(ix, &it.id, &mut dates)?;                    old = None;                }                Ident::Unknown => verified = false,                Ident::Same => {                    if across {                        track(ix, &it.id, || ix.conn.prepare_cached("UPDATE mark SET suspended = 0 WHERE id = ?1").map_err(db)?.execute([&it.id]).map(|_| ()).map_err(db))?;                        renumber_mark(ix, &it.id)?;                    }                    // an edit on the same photo (tier two): a Keep stays; a binned                    // one stays in the Bin, held from Delete until he bins it again;                    // it is looked at again and its set worked out again                    if !facts_differ(&of, &fp_new) {                        // facts that arrived later fill in what the choice was made on too                        let chosen = ix.mark_fp(&it.id);                        let filled = fill_in(&chosen, &merge_facts(&of, &fp_new));                        if filled != chosen {                            ix.conn.prepare_cached("UPDATE mark SET fp = ?2 WHERE id = ?1").map_err(db)?.execute(params![it.id, filled]).map_err(db)?;                        }                    } else {                        edits += 1;                        track(ix, &it.id, || {                            for sql in ["DELETE FROM look WHERE id = ?1", "DELETE FROM look_band WHERE id = ?1", "DELETE FROM member WHERE id = ?1"] {                                ix.conn.prepare_cached(sql).map_err(db)?.execute([&it.id]).map_err(db)?;                            }                            Ok(())                        })?;                    }                }            }        }        let (ident, fp) = match &old {            Some((_, oi, of, _)) => (merge_facts(oi, &ident_new), merge_facts(of, &fp_new)),            None => (ident_new.clone(), fp_new.clone()),        };        if old.is_none() {            track(ix, &it.id, || follow_cloud_id(ix, it))?;        }        track(ix, &it.id, || rematch_suspended(ix, it, &fp))?;        track(ix, &it.id, || {            ix.conn                .prepare_cached("INSERT INTO item (id, taken, kind, w, h, bytes, meta, state, cloud_id, fp, ident, verified) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) ON CONFLICT (id) DO UPDATE SET taken = excluded.taken, kind = excluded.kind, w = excluded.w, h = excluded.h, bytes = excluded.bytes, meta = excluded.meta, state = excluded.state, cloud_id = excluded.cloud_id, fp = excluded.fp, ident = excluded.ident, verified = excluded.verified")                .map_err(db)?                .execute(params![it.id, it.taken_at_ms, kind_key(it.kind), it.width, it.height, it.bytes.map(|b| b as i64), serde_json::to_string(it).unwrap(), to, it.cloud_id, fp, ident, verified])                .map(|_| ())                .map_err(db)        })?;        ix.conn.prepare_cached("DELETE FROM absent WHERE id = ?1").map_err(db)?.execute([&it.id]).map_err(db)?;        let was_present = old.as_ref().is_some_and(|(s, ..)| s == "present");        if to == "trashed" {            if was_present || old.is_none() || ix.mark(&it.id).handed() {                leave_library(ix, &it.id, "trashed", now, &mut dates)?;            }        } else {            if !was_present && old.is_some() {                // back in the library: a snapshot taken before never takes it                renumber_mark(ix, &it.id)?;            }            if matches!(ix.mark(&it.id), Mark::Freed { .. }) {                came_back.push(it.id.clone());            }        }        dates.push(it.taken_at_ms);    }    // parts: the same second, one RAW beside its JPEG, or an original beside its edit    for it in items.iter().filter(|i| i.path.is_some() && !i.has("trashed")) {        let second = it.taken_at_ms.div_euclid(1000) * 1000;        let near: Vec<Item> = ix            .conn            .prepare_cached("SELECT meta FROM item WHERE taken BETWEEN ?1 AND ?2 AND id <> ?3 AND state = 'present'")            .map_err(db)?            .query_map(params![second, second + 999, it.id], |r| r.get::<_, String>(0))            .map_err(db)?            .filter_map(Result::ok)            .filter_map(|m| serde_json::from_str(&m).ok())            .collect();        for other in &near {            let (part, main) = if parts::is_part_of(it, other) {                (&it.id, &other.id)            } else if parts::is_part_of(other, it) {                (&other.id, &it.id)            } else {                continue;            };            track(ix, part, || ix.conn.execute("UPDATE item SET part_of = ?1 WHERE id = ?2", params![main, part]).map(|_| ()).map_err(db))?;        }    }    // a Delete's own read settles its handed items (rule 3)    let mut settled = Value::Null;    if let Some(act) = r["act_id"].as_str() {        let trusted = ix.get("permission").as_deref() == Some("full") && r["complete"].as_bool() == Some(true);        settled = handing::settle(ix, act, &states, trusted, now, &mut dates)?;    } else {        for (id, st) in &states {            match st.as_str() {                "trashed" if ix.present(id) || ix.mark(id).handed() => leave_library(ix, id, "trashed", now, &mut dates)?,                "absent" => {                    let t = token.ok_or_else(|| bad("an absent state needs the library's token"))?;                    report_absent(ix, id, t, now, &mut dates)?;                }                "present" if !ix.lib(id).is_empty() && !ix.present(id) => {                    set_present(ix, id)?;                    if matches!(ix.mark(id), Mark::Freed { .. }) {                        came_back.push(id.clone());                    }                }                _ => {}            }        }    }    // Freed and present again: restored from the phone's trash: an ordinary    // photo again, his mark cleared, in one act row "came back" (rule 4)    if !came_back.is_empty() {        let changes: Vec<Change> = came_back.iter().map(|id| Change { id: id.clone(), after: Chosen::None, why: String::new(), expect: "freed", main: true, note: None }).collect();        let act = new_act(ix, "came_back", "applying", &ActSpec::default(), &changes, now)?;        run(ix, &act, usize::MAX)?;    }    if !removed.is_empty() {        let t = token.ok_or_else(|| bad("removed needs the library's token"))?;        for id in &removed {            report_absent(ix, id, t, now, &mut dates)?;        }    }    let mut sweep = Value::Null;    if let Some(all) = r["all_ids"].as_array() {        let full = ix.get("permission").as_deref() == Some("full");        let complete = r["complete"].as_bool() == Some(true);        let last_token = ix.get("sweep_token");        let why = match (full, complete, token) {            (false, _, _) => Some("not_full_access"),            (_, false, _) => Some("not_complete"),            (_, _, None) => Some("no_token"),            (_, _, Some(t)) if last_token.as_deref() == Some(t) => Some("same_token"),            _ => None,        };        match why {            Some(why) => sweep = json!({ "swept": false, "why": why }),            None => {                let t = token.unwrap();                let ids: Vec<&str> = all.iter().filter_map(Value::as_str).chain(items.iter().map(|i| i.id.as_str())).collect();                let hash = ids_hash(&ids);                let agrees = ix.get("sweep_hash").as_deref() == Some(hash.as_str());                let keep: BTreeSet<&str> = ids.iter().copied().collect();                let have: Vec<String> = ix.conn.prepare("SELECT id FROM item WHERE state <> 'absent'").map_err(db)?.query_map([], |row| row.get(0)).map_err(db)?.filter_map(Result::ok).collect();                let missing: Vec<String> = have.into_iter().filter(|id| !keep.contains(id.as_str())).collect();                let (mut gone, mut waiting) = (0, 0);                if !agrees {                    // the library changed between the two: start again from this one                    ix.conn.execute("DELETE FROM absent", []).map_err(db)?;                }                for id in &missing {                    if report_absent(ix, id, t, now, &mut dates)? {                        gone += 1;                    } else {                        waiting += 1;                    }                }                sweep = json!({ "swept": true, "gone": gone, "waiting": waiting });                // the full read after a library change is done: what it did not                // re-match is from another phone or library (decision H.b)                ix.set("rechecking", "0")?;                ix.set("sweep_token", t)?;                ix.set("sweep_hash", &hash)?;            }        }    }    refresh_dates(ix, &dates)?;    let changed_ids: Vec<String> = items.iter().map(|i| i.id.clone()).chain(states.iter().map(|s| s.0.clone())).chain(removed.iter().cloned()).collect();    reoffer_dependents(ix, &changed_ids)?;    let p = ix.progress();    Ok(json!({        "items": tally(ix, "items").0,        "photos": p.total,        "looked": p.looked,        "sweep": sweep,        "settled": settled,        "came_back": (!came_back.is_empty()).then(|| words::came_back(came_back.len())),        "waiting": tally(ix, "handed").0,        "renamed": renamed,        "edited": edits,        "other_library": tally(ix, "suspended").0,        "rechecking": rechecking(ix),    }))}/// A new id whose exact cloud id is an item that left the library: its marks/// follow it (rule 8). Nothing else ever moves a mark to another id.fn follow_cloud_id(ix: &Index, it: &Item) -> Result<(), MethodError> {    let Some(cloud) = it.cloud_id.as_deref().filter(|c| !c.is_empty()) else { return Ok(()) };    let old: Vec<String> = ix        .conn        .prepare_cached("SELECT item.id FROM item JOIN mark ON mark.id = item.id WHERE item.cloud_id = ?1 AND item.id <> ?2 AND item.state <> 'present' AND mark.suspended = 0")        .map_err(db)?        .query_map(params![cloud, it.id], |r| r.get(0))        .map_err(db)?        .filter_map(Result::ok)        .collect();    if let [from] = old.as_slice() {        if ix.conn.prepare_cached("SELECT 1 FROM mark WHERE id = ?1").map_err(db)?.query_row([&it.id], |_| Ok(())).optional().map_err(db)?.is_none() {            ix.conn.execute("UPDATE mark SET id = ?2 WHERE id = ?1", params![from, it.id]).map_err(db)?;            renumber_mark(ix, &it.id)?;        }    }    Ok(())}fn kind_key(k: Kind) -> &'static str {    match k {        Kind::Photo => "photo",        Kind::Video => "video",    }}// ── the pass ────────────────────────────────────────────────────────────/// Which photos to look at next, newest first, and how to ask for each:/// `{limit, on_wifi}` → `{asks: [{id, px, network}], left}`.fn pass_next(ix: &Index, r: &Value) -> Result<Value, MethodError> {    let limit = r["limit"].as_u64().unwrap_or(pass::CHECKPOINT as u64).min(1000) as i64;    let on_wifi = r["on_wifi"].as_bool().unwrap_or(false);    let mut asks = Vec::new();    let fresh: Vec<String> = ix        .conn        .prepare_cached("SELECT id FROM item WHERE kind = 'photo' AND state = 'present' AND part_of IS NULL AND id NOT IN (SELECT id FROM look) ORDER BY taken DESC LIMIT ?1")        .map_err(db)?        .query_map([limit], |row| row.get(0))        .map_err(db)?        .filter_map(Result::ok)        .collect();    for id in fresh {        if let Some(a) = pass::next_ask(None, false, on_wifi) {            asks.push(json!({ "id": id, "px": a.px, "network": a.network }));        }    }    if (asks.len() as i64) < limit && on_wifi {        let again: Vec<String> = ix            .conn            .prepare_cached("SELECT look.id FROM look JOIN item USING (id) WHERE level = 0 AND asked_net = 0 AND item.state = 'present' ORDER BY item.taken DESC LIMIT ?1")            .map_err(db)?            .query_map([limit - asks.len() as i64], |row| row.get(0))            .map_err(db)?            .filter_map(Result::ok)            .collect();        for id in again {            if let Some(a) = pass::next_ask(Some(Level::None), false, true) {                asks.push(json!({ "id": id, "px": a.px, "network": a.network }));            }        }    }    let p = ix.progress();    Ok(json!({ "asks": asks, "left": p.total.saturating_sub(p.looked) }))}/// What the shell got for each ask: `{looks: [{id, grey|rgba: {width, height, pixels (base64)} | null, platform?, network}]}`./// A platform feature print is never kept: it stays in the shell's own store.fn look_take(ix: &Index, r: &Value, now: i64) -> Result<Value, MethodError> {    let looks = r["looks"].as_array().ok_or_else(|| bad("looks is a list"))?;    let b64 = base64::engine::general_purpose::STANDARD;    let (mut dates, mut ids, mut empty) = (Vec::new(), Vec::new(), 0usize);    for l in looks {        let id = l["id"].as_str().ok_or_else(|| bad("a look has no id"))?;        let Some(taken) = ix.conn.prepare_cached("SELECT taken FROM item WHERE id = ?1 AND state = 'present'").map_err(db)?.query_row([id], |r| r.get::<_, i64>(0)).optional().map_err(db)? else { continue };        let picture = |key: &str| -> Result<Option<(u32, u32, Vec<u8>)>, MethodError> {            let g = &l[key];            if g.is_null() {                return Ok(None);            }            let (w, h) = (g["width"].as_u64().unwrap_or(0) as u32, g["height"].as_u64().unwrap_or(0) as u32);            let px = b64.decode(g["pixels"].as_str().unwrap_or("")).map_err(|e| bad(format!("{key} pixels: {e}")))?;            Ok(Some((w, h, px)))        };        let grey = match (picture("grey")?, picture("rgba")?) {            (Some((w, h, px)), _) => Some(Grey::new(w, h, px).ok_or_else(|| bad("grey pixels do not fill width x height"))?),            (None, Some((w, h, px))) => Some(Grey::from_rgba(w, h, &px).ok_or_else(|| bad("rgba pixels do not fill width x height"))?),            _ => None,        };        let mut platform: PlatformLook = serde_json::from_value(l["platform"].clone()).unwrap_or_default();        platform.print = None;        let seen = look::analyse(grey.as_ref(), platform);        empty += usize::from(seen.level == Level::None);        let asked_net = l["network"].as_bool().unwrap_or(false);        let data = encode_look(&seen);        track(ix, id, || {            ix.conn                .prepare_cached("INSERT INTO look (id, level, dhash, data, asked_net) VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT (id) DO UPDATE SET level = excluded.level, dhash = excluded.dhash, data = excluded.data, asked_net = max(look.asked_net, excluded.asked_net)")                .map_err(db)?                .execute(params![id, seen.level as i64, seen.dhash as i64, data, asked_net])                .map_err(db)?;            ix.conn.prepare_cached("DELETE FROM look_band WHERE id = ?1").map_err(db)?.execute([id]).map_err(db)?;            if seen.level != Level::None {                let mut stmt = ix.conn.prepare_cached("INSERT OR IGNORE INTO look_band (band, v, id) VALUES (?1, ?2, ?3)").map_err(db)?;                for (b, v) in bands(seen.dhash) {                    stmt.execute(params![b, v, id]).map_err(db)?;                }            }            Ok(())        })?;        dates.push(taken);        ids.push(id.to_string());    }    // the rate: only the times are kept; counts are always read from the index    let mut rate = Progress { recent_ms: ix.progress().recent_ms, ..Progress::default() };    rate.looked_at(looks.len(), empty, now);    ix.set("progress", &serde_json::to_string(&Progress { recent_ms: rate.recent_ms, ..Progress::default() }).unwrap())?;    refresh_dates(ix, &dates)?;    reoffer_dependents(ix, &ids)?;    let p = ix.progress();    if p.looked >= p.total && ix.state() != State::NotStarted {        ix.set("pass_state", "done")?;    }    Ok(json!({ "looked": p.looked, "total": p.total }))}/// The progress lines: `{state?: running|paused_battery|paused_closed, charging?}`.fn pass_lines(ix: &Index, r: &Value) -> Result<Value, MethodError> {    if let Some(s) = r["state"].as_str() {        if !matches!(s, "running" | "paused_battery" | "paused_closed") {            return Err(bad("state is running, paused_battery or paused_closed"));        }        if ix.state() != State::Done {            ix.set("pass_state", s)?;        }    }    if let Some(c) = r["charging"].as_bool() {        ix.set("charging", if c { "1" } else { "0" })?;    }    Ok(lines_value(ix))}fn lines_value(ix: &Index) -> Value {    match pass::lines(&ix.progress(), ix.state(), ix.charging(), ix.platform()) {        Some(l) => json!(l),        None => Value::Null,    }}// ── keeping the sets and offers true (rule F: only the changed ranges) ──struct Row {    item: Item,    look: Option<Look>,    mark: Mark,    part: bool,}fn rows_between(ix: &Index, lo: i64, hi: i64) -> Result<Vec<Row>, MethodError> {    let rows = ix        .conn        .prepare_cached(            "SELECT item.meta, look.data, mark.mark, item.part_of IS NOT NULL FROM item LEFT JOIN look USING (id) LEFT JOIN mark USING (id) WHERE item.taken BETWEEN ?1 AND ?2 AND item.state = 'present' ORDER BY item.taken, item.id",        )        .map_err(db)?        .query_map([lo, hi], |r| Ok((r.get::<_, String>(0)?, r.get::<_, Option<String>>(1)?, r.get::<_, Option<String>>(2)?, r.get::<_, bool>(3)?)))        .map_err(db)?        .filter_map(Result::ok)        .filter_map(|(m, d, k, part)| {            let item: Item = serde_json::from_str(&m).ok()?;            let look = d.and_then(|d| decode_look(&d));            let mark = k.and_then(|k| serde_json::from_str(&k).ok()).unwrap_or(Mark::None);            Some(Row { item, look, mark, part })        })        .collect();    Ok(rows)}/// Refresh around each cluster of changed dates, never one span from the/// oldest to the newest change.fn refresh_dates(ix: &Index, dates: &[i64]) -> Result<(), MethodError> {    let mut d: Vec<i64> = dates.to_vec();    d.sort_unstable();    d.dedup();    ix.refreshed_rows.set(0);    let mut i = 0;    while i < d.len() {        let (a, mut b) = (d[i], d[i]);        while i + 1 < d.len() && d[i + 1] - b <= 2 * sets::WINDOW_MS {            i += 1;            b = d[i];        }        refresh(ix, a, b)?;        i += 1;    }    Ok(())}/// Regroup the sets around `[lo, hi]` and recompute what each list offers there.fn refresh(ix: &Index, lo: i64, hi: i64) -> Result<(), MethodError> {    // widen to whole sets: a set touching the span is regrouped whole    let (mut a, mut b) = (lo - sets::WINDOW_MS, hi + sets::WINDOW_MS);    loop {        let (na, nb): (Option<i64>, Option<i64>) = ix            .conn            .prepare_cached("SELECT min(i2.taken), max(i2.taken) FROM member m1 JOIN item i1 ON i1.id = m1.id JOIN member m2 ON m2.set_id = m1.set_id JOIN item i2 ON i2.id = m2.id WHERE i1.taken BETWEEN ?1 AND ?2")            .map_err(db)?            .query_row([a, b], |r| Ok((r.get(0)?, r.get(1)?)))            .map_err(db)?;        let (na, nb) = (na.unwrap_or(a).min(a), nb.unwrap_or(b).max(b));        if na == a && nb == b {            break;        }        (a, b) = (na, nb);    }    let rows = rows_between(ix, a, b)?;    ix.refreshed_rows.set(ix.refreshed_rows.get() + rows.len());    let mut shots: Vec<Shot<'_>> = rows        .iter()        .enumerate()        .filter(|(_, r)| !r.part && r.mark.offered() && sets::groupable(&r.item, r.look.as_ref()))        .map(|(i, r)| Shot { index: i, taken_at_ms: r.item.taken_at_ms, look: r.look.as_ref().unwrap() })        .collect();    let found = sets::group(&mut shots);    let old: Vec<String> = ix        .conn        .prepare_cached("SELECT DISTINCT member.set_id FROM member JOIN item USING (id) WHERE item.taken BETWEEN ?1 AND ?2")        .map_err(db)?        .query_map([a, b], |r| r.get(0))        .map_err(db)?        .filter_map(Result::ok)        .collect();    for s in &old {        ix.conn.prepare_cached("DELETE FROM member WHERE set_id = ?1").map_err(db)?.execute([s]).map_err(db)?;        ix.conn.prepare_cached("DELETE FROM shot_set WHERE set_id = ?1").map_err(db)?.execute([s]).map_err(db)?;    }    for set in &found {        let sid = sets::set_id(&rows[set[0]].item.id);        let members: Vec<&Look> = set.iter().map(|&i| rows[i].look.as_ref().unwrap()).collect();        let p = picks(&members);        let mut total = size::Size::ZERO;        for (k, &i) in set.iter().enumerate() {            let rank = p.keep.iter().position(|&x| x == k).map_or(-1, |x| x as i64);            ix.conn.prepare_cached("INSERT OR REPLACE INTO member (id, set_id, pick, rank) VALUES (?1, ?2, ?3, ?4)").map_err(db)?.execute(params![rows[i].item.id, sid, rank >= 0, rank]).map_err(db)?;            if rank < 0 {                total = total.add(size::of(&rows[i].item));            }        }        ix.conn            .prepare_cached("INSERT OR REPLACE INTO shot_set (set_id, first, count, picks, sure, bytes, exact) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)")            .map_err(db)?            .execute(params![sid, rows[set[0]].item.taken_at_ms, set.len() as i64, p.keep.len() as i64, p.sure, total.bytes as i64, total.exact])            .map_err(db)?;    }    apply_tally(ix, &[("sets".to_string(), found.len() as i64 - old.len() as i64, 0, 0)], 1)?;    for r in &rows {        offer_one(ix, &r.item, r.look.as_ref(), r.mark, r.part)?;    }    Ok(())}/// Whether an original is here: present, not a part, not in the Bin, not/// handed, not deleted (rule E).fn original_here(ix: &Index, id: &str) -> bool {    ix.present(id) && !ix.is_part(id) && matches!(ix.mark(id), Mark::None | Mark::Keep { .. })}/// Recompute what one item is a copy of (whatever his choices) and what it/// offers (which depends on them).fn offer_one(ix: &Index, item: &Item, look: Option<&Look>, mark: Mark, part: bool) -> Result<(), MethodError> {    let (set_offer, set_pick) = ix.conn.prepare_cached("SELECT pick FROM member WHERE id = ?1").map_err(db)?.query_row([&item.id], |q| q.get::<_, bool>(0)).optional().map_err(db)?.map_or((false, false), |pick| (!pick, pick));    let wa = tidy::whatsapp(item);    let found = match (part, wa) {        (true, _) => None,        (false, true) => whatsapp_original(ix, item, look)?,        (false, false) => exact_original(ix, item, look)?,    };    // an original that left the library stays this copy's original (rule E: its    // only copy is never offered or deleted as "a copy")    let copy_of = found.or_else(|| ix.copy_of(&item.id).filter(|o| !ix.present(o)));    ix.conn.prepare_cached("UPDATE item SET copy_of = ?1, cat = ?2 WHERE id = ?3").map_err(db)?.execute(params![copy_of, wa.then_some("whatsapp"), item.id]).map_err(db)?;    let here = copy_of.as_deref().is_some_and(|o| original_here(ix, o));    let e = Entry { item, look, mark, set_offer, set_pick, exact_copy: here && !wa };    // nothing unverified is offered (decision 1f): it may name another photo    let list = if part || !ix.verified(&item.id) { None } else { tidy::list_of(&e) };    track(ix, &item.id, || match list {        Some(list) => {            let of = match list {                List::WhatsappCopies | List::ExactCopies if here => copy_of.clone(),                _ => None,            };            let sub = match (&of, list) {                (Some(o), List::WhatsappCopies) => format!("copy:{o}"),                (None, List::WhatsappCopies) => "other".to_string(),                _ => String::new(),            };            let old: Option<(String, String, i64)> = ix.conn.prepare_cached("SELECT list, sub, seq FROM offer WHERE id = ?1").map_err(db)?.query_row([&item.id], |q| Ok((q.get(0)?, q.get(1)?, q.get(2)?))).optional().map_err(db)?;            let seq = match old {                Some((l, s, seq)) if l == list.key() && s.starts_with("copy:") == sub.starts_with("copy:") => seq,                _ => ix.next_seq()?,            };            let s = size_with_parts(ix, item);            ix.conn                .prepare_cached("INSERT OR REPLACE INTO offer (id, list, bytes, exact, taken, sub, of, seq) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)")                .map_err(db)?                .execute(params![item.id, list.key(), s.bytes as i64, s.exact, item.taken_at_ms, sub, of, seq])                .map(|_| ())                .map_err(db)        }        None => ix.conn.prepare_cached("DELETE FROM offer WHERE id = ?1").map_err(db)?.execute([&item.id]).map(|_| ()).map_err(db),    })}/// Recompute the items whose copy relation may have changed with these:/// their copies, exact copies sharing a hash, and WhatsApp items sharing a/// hash band in the month after (rule E; by index, rule F).fn reoffer_dependents(ix: &Index, ids: &[String]) -> Result<(), MethodError> {    let mut deps: BTreeSet<String> = BTreeSet::new();    for id in ids {        deps.extend(ix.copies_of(id));        let Some((dhash, level, taken)): Option<(i64, i64, i64)> = ix            .conn            .prepare_cached("SELECT look.dhash, look.level, item.taken FROM look JOIN item USING (id) WHERE look.id = ?1")            .map_err(db)?            .query_row([id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))            .optional()            .map_err(db)?        else {            continue;        };        if level == 0 {            continue;        }        deps.extend(ix.conn.prepare_cached("SELECT id FROM look WHERE dhash = ?1").map_err(db)?.query_map([dhash], |r| r.get::<_, String>(0)).map_err(db)?.filter_map(Result::ok));        let mut stmt = ix            .conn            .prepare_cached("SELECT lb.id FROM look_band lb JOIN item ON item.id = lb.id WHERE lb.band = ?1 AND lb.v = ?2 AND item.cat = 'whatsapp' AND item.taken BETWEEN ?3 AND ?4")            .map_err(db)?;        for (b, v) in bands(dhash as u64) {            deps.extend(stmt.query_map(params![b, v, taken, taken + tidy::COPY_WINDOW_MS], |r| r.get::<_, String>(0)).map_err(db)?.filter_map(Result::ok));        }    }    for id in ids {        deps.remove(id);    }    for id in deps {        if !ix.present(&id) {            continue;        }        let Some(item) = ix.item(&id) else { continue };        let look = ix.look_of(&id);        offer_one(ix, &item, look.as_ref(), ix.mark(&id), ix.is_part(&id))?;    }    Ok(())}/// The first of a group of exact copies, whatever his choices.fn exact_original(ix: &Index, item: &Item, look: Option<&Look>) -> Result<Option<String>, MethodError> {    let (Some(l), Some(bytes)) = (look, item.bytes) else { return Ok(None) };    if l.level == Level::None {        return Ok(None);    }    let first: Option<String> = ix        .conn        .prepare_cached(            "SELECT item.id FROM look JOIN item USING (id) WHERE look.dhash = ?1 AND look.level > 0 AND item.w = ?2 AND item.h = ?3 AND item.bytes = ?4 AND item.state = 'present' AND (item.part_of IS NULL OR item.id = ?5) ORDER BY item.taken, item.id LIMIT 1",        )        .map_err(db)?        .query_row(params![l.dhash as i64, item.width, item.height, bytes as i64, item.id], |r| r.get(0))        .optional()        .map_err(db)?;    Ok(first.filter(|f| *f != item.id))}/// The camera original of a WhatsApp copy, whatever his choices: candidates/// by hash band only (rule F), then the core's match.fn whatsapp_original(ix: &Index, item: &Item, look: Option<&Look>) -> Result<Option<String>, MethodError> {    let Some(l) = look.filter(|l| l.level != Level::None) else { return Ok(None) };    let mut ids: BTreeSet<String> = BTreeSet::new();    let mut stmt = ix.conn.prepare_cached("SELECT id FROM look_band WHERE band = ?1 AND v = ?2").map_err(db)?;    for (b, v) in bands(l.dhash) {        ids.extend(stmt.query_map(params![b, v], |r| r.get::<_, String>(0)).map_err(db)?.filter_map(Result::ok));    }    ids.remove(&item.id);    let mut cands: Vec<(Item, Look)> = Vec::new();    let mut row = ix        .conn        .prepare_cached("SELECT item.meta, look.data, look.dhash FROM item JOIN look USING (id) WHERE item.id = ?1 AND item.kind = 'photo' AND item.state = 'present' AND item.part_of IS NULL AND look.level > 0 AND item.taken BETWEEN ?2 AND ?3")        .map_err(db)?;    for id in ids {        let Some((m, d, h)): Option<(String, String, i64)> = row.query_row(params![id, item.taken_at_ms - tidy::COPY_WINDOW_MS, item.taken_at_ms], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).optional().map_err(db)? else { continue };        if look::hamming(h as u64, l.dhash) > tidy::COPY_HAMMING_MAX {            continue;        }        let (Ok(ci), Some(cl)) = (serde_json::from_str::<Item>(&m), decode_look(&d)) else { continue };        if !tidy::whatsapp(&ci) {            cands.push((ci, cl));        }    }    cands.sort_by(|a, b| (a.0.taken_at_ms, &a.0.id).cmp(&(b.0.taken_at_ms, &b.0.id)));    let refs: Vec<(&Item, &Look)> = cands.iter().map(|(i, l)| (i, l)).collect();    Ok(tidy::copy_of((item, l), &refs).map(|k| cands[k].0.id.clone()))}/// After marks change: regroup where a changed photo could be in a set,/// recompute the other changed items' offers alone, then their copies'.fn after_marks(ix: &Index, ids: &[String]) -> Result<(), MethodError> {    let mut dates = Vec::new();    for id in ids {        let Some(item) = ix.item(id) else { continue };        let in_set = ix.conn.prepare_cached("SELECT 1 FROM member WHERE id = ?1").map_err(db)?.query_row([id], |_| Ok(())).optional().map_err(db)?.is_some();        let could_group = item.kind == Kind::Photo && !item.has("screenshot") && !item.has("screen_recording");        if in_set || could_group {            dates.push(item.taken_at_ms);        } else if ix.present(id) {            let look = ix.look_of(id);            offer_one(ix, &item, look.as_ref(), ix.mark(id), ix.is_part(id))?;        }    }    refresh_dates(ix, &dates)?;    reoffer_dependents(ix, ids)}// ── screens ─────────────────────────────────────────────────────────────/// Albums, stage 1: progress lines, then the phone's own albums the shell/// passes (`{system: [{id, title, count, kind: favourites|screenshots|user}]}`), then All photos.fn home(ix: &Index, r: &Value) -> Result<Value, MethodError> {    let system: Vec<Value> = r["system"].as_array().cloned().unwrap_or_default();    let rows: Vec<Value> = system.iter().map(|a| json!({ "id": a["id"], "title": a["title"], "line": words::photos(a["count"].as_u64().unwrap_or(0) as usize) })).collect();    Ok(json!({        "title": "Albums",        "progress": lines_value(ix),        "from_photos": { "heading": "From Photos", "rows": rows },        "all_photos": { "title": "All photos", "count": words::count(tally(ix, "items").0) },    }))}fn tidy_screen(ix: &Index) -> Result<Value, MethodError> {    let (bn, bb, be) = tally(ix, "bin");    let mut lists = Vec::new();    let mut could = 0;    for l in List::ALL {        let (n, bytes, exact) = tally(ix, &format!("list:{}", l.key()));        if n > 0 {            lists.push((l, n, bytes, exact));            could += bytes;        }    }    lists.sort_by(|a, b| b.2.cmp(&a.2).then(a.0.cmp(&b.0)));    let bin = (bn > 0).then(|| json!({ "line": words::in_bin(bn, bb, be), "act": words::delete_all(bn) }));    let handed = tally(ix, "handed").0;    Ok(json!({        "title": "Tidy",        "progress": lines_value(ix),        "bin": bin,        "waiting": (handed > 0).then(|| words::waiting_line(handed)),        "could_free": (could > 0).then(|| words::could_free(could)),        "lists": lists.iter().map(|(l, n, b, e)| json!({ "list": l.key(), "name": words::list_name(*l), "count": words::count(*n), "size": words::size(*b, *e) })).collect::<Vec<_>>(),        "empty": lists.is_empty().then(|| json!({ "title": words::NOTHING_TO_TIDY, "line": words::NOTHING_TO_TIDY_WHY })),    }))}fn token_of(r: &Value, ix: &Index) -> i64 {    r["token"].as_i64().unwrap_or_else(|| ix.seq_now())}/// One list (not Sets): `{list, from?, token?}` → a page of items newest/// first from the snapshot `token` (the first page makes one), WhatsApp copies/// in two groups. Bin all sends back `{list, token, all: true, count}`.fn list_screen(ix: &Index, r: &Value) -> Result<Value, MethodError> {    let key = r["list"].as_str().ok_or_else(|| bad("list"))?;    let list = List::from_key(key).ok_or_else(|| bad(format!("no list {key}")))?;    if list == List::Sets {        return sets_screen(ix, r);    }    let token = token_of(r, ix);    // a keyed page: `from` is the last drawn row's [taken, id] (`next_from`)    let (after_taken, after_id) = (r["from"][0].as_i64(), r["from"][1].as_str().unwrap_or(""));    let rows: Vec<(String, i64, bool, String, String)> = ix        .conn        .prepare_cached(&format!("SELECT offer.id, offer.bytes, offer.exact, offer.sub, item.meta FROM offer JOIN item USING (id) WHERE list = ?1 AND offer.seq <= ?2 AND (?3 IS NULL OR offer.taken < ?3 OR (offer.taken = ?3 AND offer.id > ?4)) ORDER BY offer.taken DESC, offer.id LIMIT {PAGE}"))        .map_err(db)?        .query_map(params![key, token, after_taken, after_id], |q| Ok((q.get(0)?, q.get(1)?, q.get(2)?, q.get(3)?, q.get(4)?)))        .map_err(db)?        .filter_map(Result::ok)        .collect();    let this_year = words::year_of(rows.first().and_then(|r| serde_json::from_str::<Item>(&r.4).ok()).map_or(0, |i| i.taken_at_ms), ix.offset());    let item_json = |(id, bytes, exact, sub, meta): &(String, i64, bool, String, String)| {        let it: Option<Item> = serde_json::from_str(meta).ok();        json!({            "id": id,            "size": words::size(*bytes as u64, *exact),            "when": it.as_ref().map(|i| when_of(ix, i, this_year)),            "video": it.as_ref().is_some_and(|i| i.kind == Kind::Video),            "duration_ms": it.as_ref().map_or(0, |i| i.duration_ms),            "original": sub.strip_prefix("copy:"),        })    };    let (n, bytes, exact) = tally(ix, &format!("list:{key}"));    let groups = if list == List::WhatsappCopies {        let (copies, others): (Vec<_>, Vec<_>) = rows.iter().partition(|r| r.3.starts_with("copy:"));        vec![            json!({ "heading": words::COPIES_OF_YOURS, "items": copies.into_iter().map(item_json).collect::<Vec<_>>() }),            json!({ "heading": words::OTHER_WHATSAPP, "items": others.into_iter().map(item_json).collect::<Vec<_>>() }),        ]    } else {        vec![json!({ "heading": Value::Null, "items": rows.iter().map(item_json).collect::<Vec<_>>() })]    };    // WhatsApp's Bin all takes only the copies of his own photos: the others    // may be his only copy, so they go one at a time    let all_n = if list == List::WhatsappCopies { tally(ix, &format!("list:{key}:copy")).0 } else { n };    let what = words::list_name(list).to_lowercase();    Ok(json!({        "title": words::list_name(list),        "head": format!("{} · {}", words::count(n), words::size(bytes, exact)),        "groups": groups,        "token": token,        "count": n,        "next_from": rows.last().filter(|_| rows.len() == PAGE).and_then(|l| serde_json::from_str::<Item>(&l.4).ok().map(|i| json!([i.taken_at_ms, l.0]))),        "bin_all": (all_n > 0).then(|| json!({ "label": words::bin_all(all_n), "confirm": words::bin_all_confirm(all_n, &what), "count": all_n, "token": token })),    }))}fn sets_screen(ix: &Index, r: &Value) -> Result<Value, MethodError> {    // a keyed page: `from` is the last drawn set's [bytes, first, set] (`next_from`)    let (b, f, sid) = (r["from"][0].as_i64(), r["from"][1].as_i64(), r["from"][2].as_str().unwrap_or(""));    let sets: Vec<(String, i64, i64, i64, bool)> = ix        .conn        .prepare_cached(&format!("SELECT set_id, count, picks, bytes, exact FROM shot_set WHERE ?1 IS NULL OR bytes < ?1 OR (bytes = ?1 AND (first < ?2 OR (first = ?2 AND set_id > ?3))) ORDER BY bytes DESC, first DESC, set_id LIMIT {PAGE}"))        .map_err(db)?        .query_map(params![b, f, sid], |q| Ok((q.get(0)?, q.get(1)?, q.get(2)?, q.get(3)?, q.get(4)?)))        .map_err(db)?        .filter_map(Result::ok)        .collect();    let mut out = Vec::new();    for (sid, count, keep, bytes, exact) in &sets {        let members = member_ids(ix, sid)?;        let first_item = members.first().and_then(|(id, _)| ix.item(id));        let year = first_item.as_ref().map_or(0, |i| words::year_of(i.taken_at_ms, i.offset_s.unwrap_or_else(|| ix.offset())));        let when = first_item.as_ref().map(|i| when_of(ix, i, year)).unwrap_or_default();        out.push(json!({            "set": sid,            "line": words::set_row(*count as usize, &when, *keep as usize),            "keep": format!("Keep {keep}"),            "frees": words::size(*bytes as u64, *exact),            "strip": members.iter().take(6).map(|(id, _)| id.clone()).collect::<Vec<_>>(),            // what the row's Keep button sends back (rule B)            "members": members.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>(),            "keepers": members.iter().filter(|(_, r)| *r >= 0).map(|(id, _)| id.clone()).collect::<Vec<_>>(),        }));    }    let (n, bytes, exact) = tally(ix, "list:sets");    Ok(json!({        "title": "Sets",        "head": format!("{} · {}", words::count(tally(ix, "sets").0), words::size(bytes, exact)),        "offered": words::count(n),        "sets": out,        "next_from": match sets.last().filter(|_| sets.len() == PAGE) {            Some((sid, _, _, bytes, _)) => json!([bytes, ix.conn.query_row("SELECT first FROM shot_set WHERE set_id = ?1", [sid], |q| q.get::<_, i64>(0)).map_err(db)?, sid]),            None => Value::Null,        },    }))}/// A set's members in time order, with each one's pick rank (−1: not picked).fn member_ids(ix: &Index, sid: &str) -> Result<Vec<(String, i64)>, MethodError> {    let v = ix.conn.prepare_cached("SELECT member.id, member.rank FROM member JOIN item USING (id) WHERE set_id = ?1 ORDER BY item.taken, item.id").map_err(db)?.query_map([sid], |q| Ok((q.get(0)?, q.get(1)?))).map_err(db)?.filter_map(Result::ok).collect();    Ok(v)}fn set_screen(ix: &Index, r: &Value) -> Result<Value, MethodError> {    let sid = r["set"].as_str().ok_or_else(|| bad("set"))?;    let info: Option<(i64, i64, bool)> = ix.conn.query_row("SELECT count, picks, sure FROM shot_set WHERE set_id = ?1", [sid], |q| Ok((q.get(0)?, q.get(1)?, q.get(2)?))).optional().map_err(db)?;    let Some((count, keep, sure)) = info else {        return Err(MethodError::new("gone", "this set is no longer offered"));    };    let members = member_ids(ix, sid)?;    let first = members.first().and_then(|(id, _)| ix.item(id));    let last = members.last().and_then(|(id, _)| ix.item(id));    let span = match (&first, &last) {        (Some(f), Some(l)) => {            let year = words::year_of(f.taken_at_ms, f.offset_s.unwrap_or_else(|| ix.offset()));            let a = when_of(ix, f, year);            if l.taken_at_ms - f.taken_at_ms >= 60_000 {                let b = when_of(ix, l, year);                format!("{}–{}", a, b.rsplit(", ").next().unwrap_or(""))            } else {                a            }        }        _ => String::new(),    };    Ok(json!({        "title": words::photos(count as usize),        "when": span,        "members": members.iter().map(|(id, rank)| json!({ "id": id, "keep": *rank >= 0 })).collect::<Vec<_>>(),        "line": words::keeps_line(keep as usize, sure),        "button": words::keep_button(keep as usize, (count - keep) as usize),        "keep_all": words::KEEP_ALL,    }))}// ── acts (rule B: what was on screen; one act row each, made in slices) ──struct Change {    id: String,    after: Chosen,    why: String,    /// The choice the item must still have when the change lands; otherwise    /// it is skipped (a later act or a pass changed it).    expect: &'static str,    /// A main item (counted on screen), not a part following it.    main: bool,    /// Why it was held back from a Delete, shown on the screen.    note: Option<String>,}/// A Delete's plan names a photo to hand without changing its mark: only/// [`handing::free_plan`] hands it, checking it again then.struct ToHand {    id: String,    why: String,    main: bool,}/// What an act row remembers of the screen it came from.#[derive(Default)]struct ActSpec {    list: Option<String>,    token: Option<i64>,    shown: Option<usize>,    /// The ids chosen, as JSON text (a long selection is kept as it came).    sel: Option<String>,}fn ids_of(r: &Value, key: &str) -> Result<Vec<String>, MethodError> {    let ids: Vec<String> = serde::Deserialize::deserialize(&r[key]).map_err(|_| bad(format!("{key} is a list of ids")))?;    if ids.is_empty() {        return Err(bad(format!("no {key}")));    }    shown_count(r).and_then(|n| if n == ids.len() { Ok(ids) } else { Err(changed()) })}fn shown_count(r: &Value) -> Result<usize, MethodError> {    r["count"].as_u64().map(|n| n as usize).ok_or_else(|| bad("count: how many the screen showed"))}/// Record one act and its items (the items may also be added while it plans).fn new_act(ix: &Index, kind: &str, state: &str, spec: &ActSpec, changes: &[Change], now: i64) -> Result<String, MethodError> {    let id = ix.next_act_id(now);    ix.conn        .execute(            "INSERT INTO act (id, at, by, kind, state, list, n, token, shown, sel) VALUES (?1, ?2, 'this phone', ?3, ?4, ?5, 0, ?6, ?7, ?8)",            params![id, now, kind, state, spec.list, spec.token, spec.shown.map(|n| n as i64), spec.sel],        )        .map_err(db)?;    add_items(ix, &id, changes)?;    Ok(id)}fn add_items(ix: &Index, act: &str, changes: &[Change]) -> Result<(), MethodError> {    let n: i64 = ix.conn.query_row("SELECT n FROM act WHERE id = ?1", [act], |r| r.get(0)).map_err(db)?;    let mut stmt = ix.conn.prepare_cached("INSERT INTO act_item (act, pos, id, after_mark, after_why, expect, note, main, fp) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)").map_err(db)?;    for (k, c) in changes.iter().enumerate() {        stmt.execute(params![act, n + k as i64, c.id, serde_json::to_string(&Mark::from(c.after)).unwrap(), c.why, c.expect, c.note, c.main, ix.fp(&c.id)]).map_err(db)?;    }    ix.conn.execute("UPDATE act SET n = n + ?2 WHERE id = ?1", params![act, changes.len() as i64]).map_err(db)?;    Ok(())}/// Record photos a Delete may hand (applied at once: their marks do not change/// until [`handing::free_plan`]).fn add_to_hand(ix: &Index, act: &str, these: &[ToHand]) -> Result<(), MethodError> {    let n: i64 = ix.conn.query_row("SELECT n FROM act WHERE id = ?1", [act], |r| r.get(0)).map_err(db)?;    let mut stmt = ix.conn.prepare_cached("INSERT INTO act_item (act, pos, id, after_mark, after_why, expect, main, fp, applied, before_mark, before_why) VALUES (?1, ?2, ?3, 'hand', ?4, 'bin', ?5, ?6, ?7, ?8, ?4)").map_err(db)?;    for (k, t) in these.iter().enumerate() {        stmt.execute(params![act, n + k as i64, t.id, t.why, t.main, ix.fp(&t.id), APPLIED, serde_json::to_string(&ix.mark(&t.id)).unwrap()]).map_err(db)?;    }    ix.conn.execute("UPDATE act SET n = n + ?2 WHERE id = ?1", params![act, these.len() as i64]).map_err(db)?;    Ok(())}fn in_act(ix: &Index, act: &str, id: &str) -> Result<bool, MethodError> {    Ok(ix.conn.prepare_cached("SELECT 1 FROM act_item WHERE act = ?1 AND id = ?2").map_err(db)?.query_row(params![act, id], |_| Ok(())).optional().map_err(db)?.is_some())}/// Apply (or undo) up to `budget` items of an act. Answers (done, of, finished).fn run(ix: &Index, act: &str, budget: usize) -> Result<(usize, usize, bool), MethodError> {    let (state, kind, n): (String, String, i64) = ix.conn.query_row("SELECT state, kind, n FROM act WHERE id = ?1", [act], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).map_err(db)?;    let budget = budget.min(i64::MAX as usize) as i64;    let mut touched = Vec::new();    match state.as_str() {        "applying" | "handing" => {            let rows: Vec<(i64, String, String, String, String, String)> = ix                .conn                .prepare_cached("SELECT pos, id, after_mark, after_why, expect, fp FROM act_item WHERE act = ?1 AND applied = 0 ORDER BY pos LIMIT ?2")                .map_err(db)?                .query_map(params![act, budget], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)))                .map_err(db)?                .filter_map(Result::ok)                .collect();            for (pos, id, after, why, expect, fp) in rows {                let after = serde_json::from_str::<Mark>(&after).ok().and_then(Chosen::from_mark).unwrap_or(Chosen::None);                let (cur, cur_why, cur_act) = ix.mark_row(&id);                // a late slice checks again: his choice, the library, the photo the id                // names (decision H.a), and a copy's pair                let pair = after.in_bin() && pair_of(ix, &id, act).is_some();                if state_of(&cur) != expect || (!ix.present(&id) && kind != "came_back") || (after.in_bin() && content_changed(&fp, &ix.fp(&id))) || pair {                    ix.conn.prepare_cached("UPDATE act_item SET applied = ?3 WHERE act = ?1 AND pos = ?2").map_err(db)?.execute(params![act, pos, SKIPPED]).map_err(db)?;                    continue;                }                ix.conn                    .prepare_cached("UPDATE act_item SET before_mark = ?3, before_why = ?4, before_act = ?5, applied = ?6 WHERE act = ?1 AND pos = ?2")                    .map_err(db)?                    .execute(params![act, pos, serde_json::to_string(&cur).unwrap(), cur_why, cur_act, APPLIED])                    .map_err(db)?;                put_mark(ix, &id, after, act, &why)?;                touched.push(id);            }            after_marks(ix, &touched)?;            let left = ix.conn.prepare_cached("SELECT count(*) FROM act_item WHERE act = ?1 AND applied = 0").map_err(db)?.query_row([act], |r| r.get::<_, i64>(0)).map_err(db)?;            if left == 0 {                let next = if state == "handing" { "listing" } else { "done" };                ix.conn.execute("UPDATE act SET state = ?2 WHERE id = ?1", params![act, next]).map_err(db)?;            }            Ok(((n - left) as usize, n as usize, left == 0))        }        "undoing" => {            let rows: Vec<(i64, String, String, String, String)> = ix                .conn                .prepare_cached("SELECT pos, id, before_mark, before_why, before_act FROM act_item WHERE act = ?1 AND applied = 1 ORDER BY pos DESC LIMIT ?2")                .map_err(db)?                .query_map(params![act, budget], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)))                .map_err(db)?                .filter_map(Result::ok)                .collect();            for (pos, id, before, why, before_act) in rows {                // never over a handed or deleted item (checked at undo; checked again here)                if matches!(ix.mark(&id), Mark::Handed { .. } | Mark::Freed { .. }) {                    continue;                }                let Some(before) = serde_json::from_str::<Mark>(&before).ok().and_then(Chosen::from_mark) else { continue };                put_mark(ix, &id, before, &before_act, &why)?;                ix.conn.prepare_cached("UPDATE act_item SET applied = ?3 WHERE act = ?1 AND pos = ?2").map_err(db)?.execute(params![act, pos, UNDONE]).map_err(db)?;                touched.push(id);            }            after_marks(ix, &touched)?;            let left = ix.conn.prepare_cached("SELECT count(*) FROM act_item act_item JOIN mark ON mark.id = act_item.id WHERE act_item.act = ?1 AND act_item.applied = 1 AND mark.state NOT IN ('handed', 'freed')").map_err(db)?.query_row([act], |r| r.get::<_, i64>(0)).map_err(db)?;            if left == 0 {                ix.conn.execute("UPDATE act SET state = 'undone' WHERE id = ?1", [act]).map_err(db)?;            }            Ok(((n - left) as usize, n as usize, left == 0))        }        _ => Ok((n as usize, n as usize, true)),    }}/// The answer's `platform: {act, parts, act_id}`, made from the core's/// [`core_handing::PlatformList`] alone (nothing else can make one).fn platform_json(l: &core_handing::PlatformList) -> Value {    json!({ "act": l.act(), "parts": l.parts(), "act_id": l.act_id() })}fn job_json(act: &str, done: usize, of: usize, finished: bool) -> Value {    if finished {        Value::Null    } else {        json!({ "act_id": act, "done": done, "of": of })    }}/// `{}`: carry on the oldest act still planning, applying, handing or/// undoing, a slice at a time, off the tap (the shell calls it until/// `finished`, or `idle`). A Delete ends here with its platform list.fn work(ix: &Index, now: i64) -> Result<Value, MethodError> {    let act: Option<(String, String, String)> = ix        .conn        .query_row("SELECT id, kind, state FROM act WHERE state IN ('planning', 'applying', 'handing', 'listing', 'undoing') ORDER BY at, id LIMIT 1", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))        .optional()        .map_err(db)?;    let Some((act, kind, state)) = act else { return Ok(json!({ "idle": true })) };    if state == "planning" {        let done = plan(ix, &act, &kind, ix.work_budget.get(), now)?;        let after: String = ix.conn.query_row("SELECT state FROM act WHERE id = ?1", [&act], |r| r.get(0)).map_err(db)?;        if after == "changed" {            return Ok(json!({ "act_id": act, "finished": true, "changed": words::CHANGED }));        }        return Ok(json!({ "act_id": act, "finished": false, "planned": done }));    }    if state == "listing" {        // a Delete hands its photos a slice at a time; the list comes with the last        return Ok(match handing::free_plan(ix, &act, now, ix.work_budget.get())? {            core_handing::Listed::More(handed) => json!({ "act_id": act, "finished": false, "handed": handed }),            core_handing::Listed::Done(list) => json!({ "act_id": act, "finished": true, "platform": list.as_ref().map_or(Value::Null, platform_json), "held_back": held_json(ix, &act)? }),        });    }    let (done, of, finished) = run(ix, &act, ix.work_budget.get())?;    let mut out = json!({ "act_id": act, "done": done, "of": of, "finished": finished && kind != "free" });    if finished && kind != "free" {        out["after"] = act_after(ix, &act)?;    }    Ok(out)}/// What a finished act says.fn act_after(ix: &Index, act: &str) -> Result<Value, MethodError> {    let (kind, skipped): (String, i64) = ix.conn.query_row("SELECT kind, skipped FROM act WHERE id = ?1", [act], |r| Ok((r.get(0)?, r.get(1)?))).map_err(db)?;    let applied = ix.conn.query_row("SELECT count(*) FROM act_item WHERE act = ?1 AND applied = 1 AND main = 1", [act], |r| r.get::<_, i64>(0)).map_err(db)? as usize;    let line = match kind.as_str() {        "bin" | "bin_all" => Some(words::moved_after(applied)),        "bring_back" => Some(format!("Brought back {}.", words::count(applied))),        _ => None,    };    Ok(json!({ "line": line, "skipped": (skipped > 0).then(|| words::skipped(skipped as usize)), "pairs": pairs_json(ix, act)? }))}/// The other half of a photo-and-copy pair that `id` must not go without:/// its original or a copy that is in the Bin, handed, or in this act (rule E/// both ways).fn pair_of(ix: &Index, id: &str, act: &str) -> Option<String> {    let going = |o: &str| matches!(ix.mark(o), Mark::Bin { .. } | Mark::Handed { .. }) || (!act.is_empty() && in_act(ix, act, o).unwrap_or(false));    if let Some(o) = ix.copy_of(id).filter(|o| ix.present(o) && going(o)) {        return Some(o);    }    ix.copies_of(id).into_iter().find(|c| going(c))}fn pairs_json(ix: &Index, act: &str) -> Result<Value, MethodError> {    let rows: Vec<(String, String)> = ix        .conn        .prepare_cached("SELECT id, note FROM act_item WHERE act = ?1 AND note LIKE 'pair:%' ORDER BY pos")        .map_err(db)?        .query_map([act], |r| Ok((r.get(0)?, r.get(1)?)))        .map_err(db)?        .filter_map(Result::ok)        .collect();    Ok(json!(rows.iter().map(|(a, n)| json!({ "id": a, "other": n.trim_start_matches("pair:"), "line": words::PAIR_LINE })).collect::<Vec<_>>()))}/// `{set, members: [ids shown], count, keep: [ids], request_id}`: keep those,/// bin the rest. Refused `changed` when the set's members are not the ones he saw.fn set_keep(ix: &Index, r: &Value, now: i64) -> Result<Value, MethodError> {    let sid = r["set"].as_str().ok_or_else(|| bad("set"))?;    let shown: BTreeSet<String> = ids_of(r, "members")?.into_iter().collect();    let chosen: BTreeSet<String> = serde_json::from_value::<Vec<String>>(r["keep"].clone()).map_err(|_| bad("keep is a list of ids"))?.into_iter().collect();    if chosen.is_empty() {        return Err(bad("keep at least one"));    }    if shown.iter().any(|id| ix.mark(id).handed()) {        return Err(handed());    }    let now_members: BTreeSet<String> = member_ids(ix, sid)?.into_iter().map(|(id, _)| id).collect();    if now_members != shown {        return Err(changed());    }    if !chosen.is_subset(&now_members) {        return Err(bad("keep names a photo that is not in this set"));    }    let act = new_act(ix, "set_keep", "applying", &ActSpec::default(), &[], now)?;    let mut changes = Vec::new();    let mut binned = 0;    for id in &now_members {        let m = if chosen.contains(id) {            Chosen::Keep { at_ms: now }        } else if let Some(other) = pair_of(ix, id, &act) {            changes.push(Change { id: id.clone(), after: Chosen::None, why: String::new(), expect: "never", main: true, note: Some(format!("pair:{other}")) });            continue;        } else {            binned += 1;            Chosen::Bin { at_ms: now }        };        let mut these = Vec::new();        for p in with_parts(ix, id) {            these.push(Change { expect: state_of(&ix.mark(&p)), main: p == *id, id: p, after: m, why: "set".to_string(), note: None });        }        // a member going to the Bin is in this act as soon as it is decided, so its pair sees it        add_items(ix, &act, &these)?;    }    add_items(ix, &act, &changes)?;    let (done, of, finished) = run(ix, &act, TAP_BUDGET)?;    Ok(json!({ "after": words::kept_after(chosen.len(), binned), "undo": { "label": words::UNDO, "token": act }, "job": job_json(&act, done, of, finished), "pairs": pairs_json(ix, &act)? }))}/// `{ids, count, request_id}`: keep these; Albums stops offering them. One in/// the Bin is brought back and kept in the same act (undo puts it back)./// Refused for an item waiting in a Delete or deleted.fn keep(ix: &Index, r: &Value, now: i64) -> Result<Value, MethodError> {    let ids = ids_of(r, "ids")?;    for id in &ids {        match ix.mark(id) {            Mark::Handed { .. } => return Err(handed()),            Mark::Freed { .. } => return Err(changed()),            _ if !ix.present(id) => return Err(changed()),            _ => {}        }    }    let from_bin = ids.iter().filter(|id| ix.mark(id).in_bin()).count();    let mut changes = Vec::new();    for id in &ids {        for p in with_parts(ix, id) {            changes.push(Change { expect: state_of(&ix.mark(&p)), main: p == *id, id: p, after: Chosen::Keep { at_ms: now }, why: "keep".to_string(), note: None });        }    }    let act = new_act(ix, "keep", "applying", &ActSpec::default(), &changes, now)?;    let (done, of, finished) = run(ix, &act, TAP_BUDGET)?;    Ok(json!({ "undo": { "label": words::UNDO, "token": act }, "job": job_json(&act, done, of, finished), "after": (from_bin > 0).then(|| words::from_bin(from_bin)) }))}/// Into the Bin: marks only, on both phones. `{list, token, all: true, count}`/// writes one act row and is planned in slices by `albums.work`; `{ids, count,/// list?, token?}` of up to 200 is planned in the tap. Grown since he looked:/// `changed`; shrunk: what still qualifies, the rest `skipped`.fn bin_move(ix: &Index, r: &Value, now: i64) -> Result<Value, MethodError> {    let list = match r["list"].as_str() {        Some(key) => Some(List::from_key(key).ok_or_else(|| bad(format!("no list {key}")))?),        None => None,    };    let token = r["token"].as_i64();    if r["all"].as_bool() == Some(true) {        let (Some(l), Some(t)) = (list, token) else { return Err(bad("all needs list and token")) };        let shown = shown_count(r)?;        let key = if l == List::WhatsappCopies { format!("list:{}:copy", l.key()) } else { format!("list:{}", l.key()) };        if tally(ix, &key).0 > shown {            return Err(changed());        }        let spec = ActSpec { list: Some(l.key().to_string()), token: Some(t), shown: Some(shown), sel: None };        let act = new_act(ix, "bin_all", "planning", &spec, &[], now)?;        return Ok(json!({ "after": Value::Null, "undo": { "label": words::UNDO, "token": act }, "job": { "act_id": act, "done": 0, "of": spec.shown } }));    }    let ids = ids_of(r, "ids")?;    if ids.iter().any(|id| ix.mark(id).handed()) {        return Err(handed());    }    if ids.len() > TAP_IDS {        let spec = ActSpec { list: list.map(|l| l.key().to_string()), token, shown: Some(ids.len()), sel: Some(serde_json::to_string(&ids).unwrap()) };        let act = new_act(ix, "bin", "planning", &spec, &[], now)?;        return Ok(json!({ "after": Value::Null, "undo": { "label": words::UNDO, "token": act }, "job": { "act_id": act, "done": 0, "of": ids.len() } }));    }    let spec = ActSpec { list: list.map(|l| l.key().to_string()), token, shown: Some(ids.len()), sel: Some(serde_json::to_string(&ids).unwrap()) };    let act = new_act(ix, "bin", "planning", &spec, &[], now)?;    plan(ix, &act, "bin", usize::MAX, now)?;    let (done, of, finished) = run(ix, &act, TAP_BUDGET)?;    let after = act_after(ix, &act)?;    let moved = ix.conn.query_row("SELECT count(*) FROM act_item WHERE act = ?1 AND main = 1 AND note IS NULL", [&act], |r| r.get::<_, i64>(0)).map_err(db)?;    let pairs_n = ix.conn.query_row("SELECT count(*) FROM act_item WHERE act = ?1 AND note IS NOT NULL", [&act], |r| r.get::<_, i64>(0)).map_err(db)?;    if moved == 0 && pairs_n == 0 {        ix.conn.execute("DELETE FROM act WHERE id = ?1", [&act]).map_err(db)?;    }    Ok(json!({        "after": (moved > 0).then(|| words::moved_after(moved as usize)),        "undo": (moved > 0).then(|| json!({ "label": words::UNDO, "token": act })),        "job": job_json(&act, done, of, finished),        "skipped": after["skipped"],        "pairs": after["pairs"],    }))}/// Plan up to `budget` candidates of an act still planning: a Bin act's/// offers or a Delete's binned items, from the snapshot it remembers. At the/// end, check what he saw: a Delete that grew or shrank, or a Bin act that/// grew, becomes `changed` and touches nothing. Answers how many it planned.fn plan(ix: &Index, act: &str, kind: &str, budget: usize, now: i64) -> Result<usize, MethodError> {    type A = (Option<String>, Option<i64>, Option<i64>, Option<String>, Option<i64>, Option<String>);    let (list, token, shown, sel, cseq, cid): A = ix        .conn        .query_row("SELECT list, token, shown, sel, cursor_seq, cursor_id FROM act WHERE id = ?1", [act], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)))        .map_err(db)?;    let free = kind == "free";    let budget_i = budget.min(i64::MAX as usize) as i64;    // the candidates of this slice, in a stable order    let (cands, finished): (Vec<(i64, String)>, bool) = match &sel {        Some(sel) => {            let ids: Vec<String> = serde_json::from_str(sel).unwrap_or_default();            let from = cseq.unwrap_or(0) as usize;            let slice: Vec<(i64, String)> = ids.iter().enumerate().skip(from).take(budget).map(|(i, id)| (i as i64 + 1, id.clone())).collect();            let finished = from + slice.len() >= ids.len();            (slice, finished)        }        None => {            let t = token.unwrap_or(0);            let (cs, ci) = (cseq.unwrap_or(-1), cid.unwrap_or_default());            let rows: Vec<(i64, String)> = if free {                ix.conn                    .prepare_cached("SELECT mark.seq, mark.id FROM mark JOIN item ON item.id = mark.id WHERE mark.state = 'bin' AND mark.seq <= ?1 AND (mark.seq, mark.id) > (?2, ?3) AND item.state = 'present' AND item.part_of IS NULL ORDER BY mark.seq, mark.id LIMIT ?4")                    .map_err(db)?                    .query_map(params![t, cs, ci, budget_i], |r| Ok((r.get(0)?, r.get(1)?)))                    .map_err(db)?                    .filter_map(Result::ok)                    .collect()            } else {                let l = list.clone().unwrap_or_default();                let copies_only = if l == "whatsapp_copies" { " AND sub LIKE 'copy:%'" } else { "" };                ix.conn                    .prepare(&format!("SELECT seq, id FROM offer WHERE list = ?1 AND seq <= ?2 AND (seq, id) > (?3, ?4){copies_only} ORDER BY seq, id LIMIT ?5"))                    .map_err(db)?                    .query_map(params![l, t, cs, ci, budget_i], |r| Ok((r.get(0)?, r.get(1)?)))                    .map_err(db)?                    .filter_map(Result::ok)                    .collect()            };            let finished = (rows.len() as i64) < budget_i;            (rows, finished)        }    };    let sel_set: BTreeSet<String> = sel.as_deref().map(|s| serde_json::from_str::<Vec<String>>(s).unwrap_or_default().into_iter().collect()).unwrap_or_default();    let mut planned = 0usize;    let mut skipped = 0i64;    let mut changed_now = false;    for (_, id) in &cands {        let mut these = Vec::new();        if free {            // a Delete: the ONE rule of what may be handed (free_plan checks it again)            let (m, why, _) = ix.mark_row(id);            let ok_shown = m.in_bin() && ix.present(id) && !ix.is_part(id) && token.is_none_or_le(ix, id);            if !ok_shown {                if sel.is_some() {                    changed_now = true;                    break;                }                continue;            }            match held_reason(ix, id, &why, act).filter(|r| !stays_in_bin(r)) {                Some(reason) => these.push(Change { id: id.clone(), after: Chosen::Keep { at_ms: now }, why: String::new(), expect: "bin", main: true, note: Some(reason) }),                None => {                    let hand: Vec<ToHand> = with_parts(ix, id).into_iter().map(|p| ToHand { main: p == *id, id: p, why: why.clone() }).collect();                    add_to_hand(ix, act, &hand)?;                }            }        } else {            // a Bin act: still offered (in this list and snapshot, when it names them)            let offer: Option<(String, Option<String>, i64)> = ix.conn.prepare_cached("SELECT list, of, seq FROM offer WHERE id = ?1").map_err(db)?.query_row([id], |q| Ok((q.get(0)?, q.get(1)?, q.get(2)?))).optional().map_err(db)?;            let Some((key, of, seq)) = offer.filter(|(k, _, s)| list.as_deref().map_or(true, |l| l == k) && token.map_or(true, |t| *s <= t)) else {                // binned again after he edited it: he has looked again (decision 1f)                if list.is_none() && sel.is_some() && edited(ix, id) {                    let why = ix.mark_row(id).1;                    these.push(Change { id: id.clone(), after: Chosen::Bin { at_ms: now }, why, expect: "bin", main: true, note: None });                    planned += 1;                    add_items(ix, act, &these)?;                    continue;                }                skipped += 1;                continue;            };            let _ = seq;            let in_sel = |o: &str| sel_set.contains(o);            // a photo and its copy chosen together: neither goes, both shown (rule E)            let together = ix.copy_of(id).filter(|o| ix.present(o) && in_sel(o)).or_else(|| ix.copies_of(id).into_iter().find(|c| in_sel(c)));            if let Some(other) = together.or_else(|| pair_of(ix, id, act)) {                these.push(Change { id: id.clone(), after: Chosen::None, why: String::new(), expect: "never", main: true, note: Some(format!("pair:{other}")) });            } else {                let why = of.map_or(key, |o| format!("copy:{o}"));                for p in with_parts(ix, id) {                    these.push(Change { expect: "none", main: p == *id, id: p, after: Chosen::Bin { at_ms: now }, why: why.clone(), note: None });                }            }        }        planned += 1;        add_items(ix, act, &these)?;    }    if let Some((s, id)) = cands.last() {        ix.conn.execute("UPDATE act SET cursor_seq = ?2, cursor_id = ?3, planned = planned + ?4, skipped = skipped + ?5 WHERE id = ?1", params![act, s, id, planned as i64, skipped]).map_err(db)?;    }    if changed_now {        return give_up(ix, act);    }    if finished {        let (total, skipped_all): (i64, i64) = ix.conn.query_row("SELECT planned, skipped FROM act WHERE id = ?1", [act], |r| Ok((r.get(0)?, r.get(1)?))).map_err(db)?;        let shown = shown.unwrap_or(total) ;        let grew = total > shown;        let shrank = total + skipped_all < shown || (sel.is_none() && total < shown);        if (free && (grew || shrank)) || (!free && grew) {            return give_up(ix, act);        }        if !free && sel.is_none() {            ix.conn.execute("UPDATE act SET skipped = ?2 WHERE id = ?1", params![act, shown - total]).map_err(db)?;        }        let next = if free { "handing" } else { "applying" };        ix.conn.execute("UPDATE act SET state = ?2 WHERE id = ?1", params![act, next]).map_err(db)?;    }    Ok(planned)}/// A plan that no longer matches the screen: nothing is touched.fn give_up(ix: &Index, act: &str) -> Result<usize, MethodError> {    ix.conn.execute("UPDATE act SET state = 'changed' WHERE id = ?1", [act]).map_err(db)?;    ix.conn.execute("DELETE FROM act_item WHERE act = ?1", [act]).map_err(db)?;    Ok(0)}trait Snapshot {    fn is_none_or_le(&self, ix: &Index, id: &str) -> bool;}impl Snapshot for Option<i64> {    /// Whether a binned item was in the Bin snapshot `self` (none: any).    fn is_none_or_le(&self, ix: &Index, id: &str) -> bool {        let Some(t) = *self else { return true };        ix.conn.prepare_cached("SELECT seq FROM mark WHERE id = ?1").ok().and_then(|mut s| s.query_row([id], |r| r.get::<_, i64>(0)).optional().ok().flatten()).is_some_and(|s| s <= t)    }}/// Why a binned item may not be handed to the phone now, if it may not (rule 2/// and rule E both ways):/// - a copy (its mark says `copy:<X>`, or the copy relation says so) whose///   original is gone, in the phone's trash, binned, handed, deleted, or in///   this same Delete: the copy is kept back, so the original may go;/// - an original with a copy that is binned or handed and NOT in this Delete///   (so that copy is not being kept back here).////// The same answer whichever of the two is planned first.fn held_reason(ix: &Index, id: &str, why: &str, act: &str) -> Option<String> {    let original = why.strip_prefix("copy:").map(String::from).or_else(|| ix.copy_of(id));    if let Some(o) = original {        let lib = ix.lib(&o);        if lib == "absent" || lib.is_empty() {            return Some("original_gone".to_string());        }        // the id may now name another photo: not read again since the library changed        if !ix.verified(&o) {            return Some("original_not_checked".to_string());        }        if lib == "trashed" {            return Some("original_trashed".to_string());        }        if !matches!(ix.mark(&o), Mark::None | Mark::Keep { .. }) || in_plan(ix, act, &o) {            return Some("original_binned".to_string());        }    }    if copies_going(ix, id).iter().any(|c| !in_plan(ix, act, c)) {        return Some("copy_binned".to_string());    }    None}/// Reasons a photo stays in the Bin, not handed and not kept: it waits for/// something (a read, his look) rather than being protected for ever.fn stays_in_bin(reason: &str) -> bool {    matches!(reason, "not_checked" | "edited_since_binned" | "original_not_checked" | "not_on_this_phone")}/// The copies of `id` that are binned or handed: by the copy relation, or by/// a mark that says `copy:<id>`.fn copies_going(ix: &Index, id: &str) -> Vec<String> {    let mut out: BTreeSet<String> = ix.copies_of(id).into_iter().filter(|c| matches!(ix.mark(c), Mark::Bin { .. } | Mark::Handed { .. })).collect();    if let Ok(mut stmt) = ix.conn.prepare_cached("SELECT id FROM mark WHERE why = ?1 AND state IN ('bin', 'handed')") {        out.extend(stmt.query_map([format!("copy:{id}")], |r| r.get::<_, String>(0)).map(|m| m.filter_map(Result::ok).collect::<Vec<_>>()).unwrap_or_default());    }    out.into_iter().collect()}/// Whether this Delete takes `id` (it is in what he saw: his selection, or/// the Bin's snapshot), planned yet or not.fn in_plan(ix: &Index, act: &str, id: &str) -> bool {    if act.is_empty() {        return false;    }    if in_act(ix, act, id).unwrap_or(false) {        return true;    }    let Ok((token, has_sel)) = ix.conn.query_row("SELECT token, sel IS NOT NULL FROM act WHERE id = ?1 AND state = 'planning'", [act], |r| Ok((r.get::<_, Option<i64>>(0)?, r.get::<_, bool>(1)?))) else { return false };    if !ix.mark(id).in_bin() || !ix.present(id) || ix.is_part(id) {        return false;    }    if has_sel {        ix.selection(act).contains(id)    } else {        token.is_none_or_le(ix, id)    }}fn held_json(ix: &Index, act: &str) -> Result<Value, MethodError> {    let rows: Vec<(String, String)> = ix        .conn        .prepare_cached("SELECT id, note FROM act_item WHERE act = ?1 AND note IS NOT NULL AND note NOT LIKE 'pair:%' ORDER BY pos")        .map_err(db)?        .query_map([act], |r| Ok((r.get(0)?, r.get(1)?)))        .map_err(db)?        .filter_map(Result::ok)        .collect();    if rows.is_empty() {        return Ok(Value::Null);    }    Ok(json!({        "line": words::held_back(rows.len()),        "items": rows.iter().map(|(id, reason)| json!({ "id": id, "reason": reason, "line": words::held_reason(reason) })).collect::<Vec<_>>(),    }))}/// `{token, request_id}`: undo one act whole. Only the newest act on its/// photos, never over one waiting in a Delete or deleted.fn undo(ix: &Index, r: &Value) -> Result<Value, MethodError> {    let token = r["token"].as_str().ok_or_else(|| bad("token"))?;    let row: Option<(String, String)> = ix.conn.query_row("SELECT kind, state FROM act WHERE id = ?1", [token], |q| Ok((q.get(0)?, q.get(1)?))).optional().map_err(db)?;    let Some((kind, state)) = row else { return Err(MethodError::new("gone", "nothing to undo")) };    match state.as_str() {        "planning" | "applying" | "undoing" => return Err(MethodError::new("busy", "still working on it")),        "done" if !matches!(kind.as_str(), "free" | "came_back") => {}        _ => return Err(MethodError::new("gone", "nothing to undo")),    }    let (freed, handed_n, later): (i64, i64, i64) = ix        .conn        .query_row(            "SELECT coalesce(sum(mark.state = 'freed'), 0), coalesce(sum(mark.state = 'handed'), 0), coalesce(sum(mark.act IS NULL OR mark.act <> ?1), 0) FROM act_item LEFT JOIN mark ON mark.id = act_item.id WHERE act_item.act = ?1 AND act_item.applied = 1",            [token],            |q| Ok((q.get(0)?, q.get(1)?, q.get(2)?)),        )        .map_err(db)?;    if freed > 0 {        return Err(MethodError::new("deleted", words::UNDO_DELETED));    }    if handed_n > 0 {        return Err(handed());    }    if later > 0 {        return Err(MethodError::new("later", words::UNDO_LATER));    }    ix.conn.execute("UPDATE act SET state = 'undoing' WHERE id = ?1", [token]).map_err(db)?;    let (done, of, finished) = run(ix, token, TAP_BUDGET)?;    Ok(json!({ "done": finished, "job": job_json(token, done, of, finished) }))}/// The Bin, built from marks: `{from?, token?}` → a page of what waits there/// (binned and present), grouped by day and why, from the snapshot `token`;/// and on the first page what he chose that the library no longer shows as/// present (absent or in the phone's trash), never counted or deleted.fn bin_screen(ix: &Index, r: &Value, now: i64) -> Result<Value, MethodError> {    let platform = ix.platform();    let (n, bytes, exact) = tally(ix, "bin");    let token = token_of(r, ix);    // a keyed page: `from` is the last drawn row's [at, taken, id] (`next_from`)    let first_page = r["from"].is_null();    let (fa, ft, fid) = (r["from"][0].as_i64(), r["from"][1].as_i64(), r["from"][2].as_str().unwrap_or(""));    let page: Vec<(String, i64, String)> = ix        .conn        .prepare_cached(&format!("SELECT mark.id, mark.at, mark.why FROM mark JOIN item ON item.id = mark.id WHERE mark.state = 'bin' AND mark.seq <= ?1 AND item.state = 'present' AND item.part_of IS NULL AND (?2 IS NULL OR mark.at < ?2 OR (mark.at = ?2 AND (item.taken < ?3 OR (item.taken = ?3 AND mark.id > ?4)))) ORDER BY mark.at DESC, item.taken DESC, mark.id LIMIT {PAGE}"))        .map_err(db)?        .query_map(params![token, fa, ft, fid], |q| Ok((q.get(0)?, q.get(1)?, q.get(2)?)))        .map_err(db)?        .filter_map(Result::ok)        .collect();    // all of them, on the first page: what he chose that the library no longer shows    let gone: Vec<(String, String)> = if first_page {        ix.conn            .prepare_cached("SELECT mark.id, mark.state FROM mark JOIN item ON item.id = mark.id WHERE mark.state IN ('bin', 'keep') AND mark.suspended = 0 AND item.state <> 'present' AND mark.id NOT LIKE '%#retired-%' ORDER BY mark.at DESC, mark.id")            .map_err(db)?            .query_map([], |q| Ok((q.get(0)?, q.get(1)?)))            .map_err(db)?            .filter_map(Result::ok)            .collect()    } else {        Vec::new()    };    let handed_n = tally(ix, "handed").0;    let other = tally(ix, "suspended").0;    let full = ix.get("permission").as_deref() == Some("full");    if page.is_empty() && gone.is_empty() && first_page && handed_n == 0 && other == 0 {        return Ok(json!({ "title": "Bin", "empty": { "title": words::BIN_EMPTY, "line": words::BIN_EMPTY_WHY } }));    }    let offset = ix.offset();    let mut groups: Vec<((i64, String), Vec<String>)> = Vec::new();    for (id, at, why) in &page {        let day = (at / 1000 + offset).div_euclid(86_400);        let why = if edited(ix, id) {            "edited".to_string()        } else if why.starts_with("copy:") {            "whatsapp_copies".to_string()        } else {            why.clone()        };        match groups.last_mut() {            Some((k, ids)) if *k == (day, why.clone()) => ids.push(id.clone()),            _ => groups.push(((day, why), vec![id.clone()])),        }    }    let today = (now / 1000 + offset).div_euclid(86_400);    let mut out: Vec<Value> = groups        .into_iter()        .map(|((day, why), ids)| {            let when = match today - day {                0 => "Today".to_string(),                1 => "Yesterday".to_string(),                _ => words::when(day * 86_400_000 - offset * 1000, offset, words::year_of(now, offset)).split(',').next().unwrap_or("").to_string(),            };            let what = match why.as_str() {                "set" => "from a set".to_string(),                "chosen" | "" | "bin" | "keep" => "chosen".to_string(),                key => List::from_key(key).map_or("chosen".to_string(), |l| words::list_name(l).to_lowercase()),            };            if why == "edited" {                // he edited these after binning them: no Delete takes them until he bins them again                return json!({ "heading": words::EDITED_HEADING, "line": words::EDITED_LINE, "bin_again": words::BIN_AGAIN, "bring_back": format!("{} {}", words::BRING_BACK, words::count(ids.len())), "count": ids.len(), "ids": ids });            }            json!({ "heading": format!("{when} · {what}"), "bring_back": format!("{} {}", words::BRING_BACK, words::count(ids.len())), "count": ids.len(), "ids": ids })        })        .collect();    if !gone.is_empty() {        out.push(json!({            "heading": words::GONE_HEADING,            "bring_back": Value::Null,            "count": gone.len(),            "ids": gone.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>(),            "chosen": gone.iter().map(|(_, s)| s.clone()).collect::<Vec<_>>(),        }));    }    let kept_parts = page.iter().flat_map(|(id, _, _)| ix.parts_of(id)).filter(|p| matches!(ix.mark(p), Mark::Keep { .. })).count();    let batch = match platform {        Platform::Ios => bin::IOS_BATCH,        Platform::Android => bin::ANDROID_BATCH,    };    let batches = n.div_ceil(batch).max(1);    let note = match (batches, platform) {        (1, Platform::Ios) => words::DELETE_NOTE_IOS.to_string(),        (1, Platform::Android) => words::DELETE_NOTE_ANDROID.to_string(),        (b, p) => words::delete_note_many(b, p),    };    Ok(json!({        "title": "Bin",        "head": words::bin_head(n, bytes, exact),        "note": words::BIN_NOTE,        "groups": out,        "kept_parts": (kept_parts > 0).then(|| words::kept_parts(kept_parts)),        "waiting": (handed_n > 0).then(|| words::waiting_line(handed_n)),        "other_library": (other > 0 && !rechecking(ix)).then(|| json!({ "line": words::other_library(other), "act": words::CLEAR_OTHER, "count": other })),        "rechecking": rechecking(ix).then_some(words::RECHECKING),        // Delete is never offered without full access: a read could not tell        // whether a photo went (finding 5)        "needs_full_access": (n > 0 && !full && platform == Platform::Ios).then(|| json!({ "line": words::DELETE_NEEDS_FULL, "act": words::OPEN_SETTINGS })),        "delete_later": (n > 0 && platform == Platform::Android).then_some(words::DELETE_ANDROID_LATER),        "token": token,        "count": n,        "next_from": page.last().filter(|_| page.len() == PAGE).map(|(id, at, _)| json!([at, ix.item(id).map_or(0, |i| i.taken_at_ms), id])),        "act": (n > 0 && deletes_here(ix)).then(|| json!({ "label": words::delete_all(n), "question": words::delete_question(n, platform), "note": note, "no_way_back": words::DELETE_NO_WAY_BACK })),    }))}/// Out of the Bin: marks only, on both phones; one act, undoable./// `{ids, count, request_id}`: each still binned and present (a handed one is/// refused), the rest skipped.fn bring_back(ix: &Index, r: &Value, now: i64) -> Result<Value, MethodError> {    let asked = ids_of(r, "ids")?;    if asked.iter().any(|id| matches!(ix.mark(id), Mark::Handed { .. })) {        return Err(handed());    }    let ids: Vec<String> = asked.iter().filter(|id| ix.present(id) && bin::can_bring_back(&ix.mark(id))).cloned().collect();    let skipped = asked.len() - ids.len();    let skipped_line = (skipped > 0).then(|| words::skipped(skipped));    if ids.is_empty() {        return Ok(json!({ "after": Value::Null, "undo": Value::Null, "skipped": skipped_line }));    }    let mut changes = Vec::new();    for id in &ids {        for p in with_parts(ix, id) {            changes.push(Change { expect: "bin", main: p == *id, id: p, after: Chosen::None, why: String::new(), note: None });        }    }    let act = new_act(ix, "bring_back", "applying", &ActSpec::default(), &changes, now)?;    let (done, of, finished) = run(ix, &act, TAP_BUDGET)?;    Ok(json!({ "after": format!("Brought back {}.", words::count(ids.len())), "undo": { "label": words::UNDO, "token": act }, "job": job_json(&act, done, of, finished), "skipped": skipped_line }))}/// Delete from the Bin screen: `{token, all: true, count, request_id}` or/// `{token, ids, count, request_id}`. The tap writes one act row; `albums.work`/// plans it (what he saw must be the Bin's snapshot exactly, else `changed`),/// hands the items (they leave the Bin and wait), and answers the platform/// list from [`free_plan`].fn bin_delete(ix: &Index, r: &Value, now: i64) -> Result<Value, MethodError> {    if ix.platform() == Platform::Android {        return Err(MethodError::new("not_on_this_phone", words::DELETE_ANDROID_LATER));    }    if !deletes_here(ix) {        return Err(MethodError::new("needs_full_access", words::DELETE_NEEDS_FULL));    }    let token = r["token"].as_i64().ok_or_else(|| bad("token: the Bin snapshot he saw"))?;    let shown = shown_count(r)?;    let sel = if r["all"].as_bool() == Some(true) {        if tally(ix, "bin").0 != shown {            return Err(changed());        }        None    } else {        // a long selection is kept as it came and checked while planning (a        // handed or unknown id makes the Delete `changed`); a short one here        let arr = r["ids"].as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad("ids is a list of ids"))?;        if arr.len() != shown {            return Err(changed());        }        if !arr.iter().all(Value::is_string) {            return Err(bad("ids is a list of ids"));        }        if arr.len() <= TAP_IDS && arr.iter().filter_map(Value::as_str).any(|id| ix.mark(id).handed()) {            return Err(handed());        }        Some(r["ids"].to_string())    };    let spec = ActSpec { list: None, token: Some(token), shown: Some(shown), sel };    let act = new_act(ix, "free", "planning", &spec, &[], now)?;    Ok(json!({ "job": { "act_id": act, "done": 0, "of": shown } }))}/// `{count, request_id}`: he clears the choices from another phone or/// library that no read re-matched (decision H.b). One act row; not undone.fn clear_other(ix: &Index, r: &Value, now: i64) -> Result<Value, MethodError> {    let ids: Vec<String> = ix.conn.prepare("SELECT id FROM mark WHERE suspended = 1 ORDER BY id").map_err(db)?.query_map([], |q| q.get(0)).map_err(db)?.filter_map(Result::ok).collect();    if shown_count(r)? != ids.len() {        return Err(changed());    }    let act = new_act(ix, "clear_other", "done", &ActSpec::default(), &[], now)?;    for id in &ids {        track(ix, id, || ix.conn.prepare_cached("DELETE FROM mark WHERE id = ?1").map_err(db)?.execute([id]).map(|_| ()).map_err(db))?;    }    ix.conn.execute("UPDATE act SET n = ?2 WHERE id = ?1", params![act, ids.len() as i64]).map_err(db)?;    Ok(json!({ "cleared": ids.len() }))}/// `{count, request_id}` from You: he clears the choices that belong to photos/// no longer on this phone (an id that came to name another photo). One act/// row; not undone.fn clear_gone(ix: &Index, r: &Value, now: i64) -> Result<Value, MethodError> {    let ids: Vec<String> = ix.conn.prepare("SELECT id FROM mark WHERE id LIKE '%#retired-%' AND suspended = 0 AND state IN ('bin', 'keep') ORDER BY id").map_err(db)?.query_map([], |q| q.get(0)).map_err(db)?.filter_map(Result::ok).collect();    if shown_count(r)? != ids.len() {        return Err(changed());    }    let act = new_act(ix, "clear_gone", "done", &ActSpec::default(), &[], now)?;    for id in &ids {        track(ix, id, || ix.conn.prepare_cached("DELETE FROM mark WHERE id = ?1").map_err(db)?.execute([id]).map(|_| ()).map_err(db))?;    }    ix.conn.execute("UPDATE act SET n = ?2 WHERE id = ?1", params![act, ids.len() as i64]).map_err(db)?;    Ok(json!({ "cleared": ids.len() }))}/// A read says an item the index holds as not present is in the library/// again: present, with a new number (rule B).fn set_present(ix: &Index, id: &str) -> Result<(), MethodError> {    track(ix, id, || ix.conn.prepare_cached("UPDATE item SET state = 'present' WHERE id = ?1").map_err(db)?.execute([id]).map(|_| ()).map_err(db))?;    ix.conn.prepare_cached("DELETE FROM absent WHERE id = ?1").map_err(db)?.execute([id]).map_err(db)?;    renumber_mark(ix, id)}/// `{act_id, request_id}` after the phone asked the system: which ids to read/// now. The shell never says what happened; it reads those ids and sends/// `albums.library.take {act_id, states}`, which settles them.fn platform_done(ix: &Index, r: &Value) -> Result<Value, MethodError> {    let act = r["act_id"].as_str().ok_or_else(|| bad("act_id: the Delete this follows"))?;    let state: Option<String> = ix.conn.query_row("SELECT state FROM act WHERE id = ?1 AND kind = 'free'", [act], |r| r.get(0)).optional().map_err(db)?;    if state.as_deref() != Some("asking") {        return Err(MethodError::new("gone", "no Delete is waiting for this"));    }    Ok(json!({ "read": handed_ids(ix, act)?, "act_id": act }))}fn handed_ids(ix: &Index, act: &str) -> Result<Vec<String>, MethodError> {    let v = ix.conn.prepare_cached("SELECT id FROM mark WHERE state = 'handed' AND act = ?1 ORDER BY id").map_err(db)?.query_map([act], |r| r.get(0)).map_err(db)?.filter_map(Result::ok).collect();    Ok(v)}/// `{}`: the Deletes still waiting for the library to say what happened/// (after a kill, or a dialog never answered): `count` handed photos, and for/// each Delete the ids to read (`acts: [{act_id, read}]`). Both come from the/// handed marks, so they always agree.fn waiting(ix: &Index) -> Result<Value, MethodError> {    let acts: Vec<String> = ix.conn.prepare("SELECT DISTINCT mark.act FROM mark JOIN act ON act.id = mark.act WHERE mark.state = 'handed' ORDER BY act.at, act.id").map_err(db)?.query_map([], |r| r.get(0)).map_err(db)?.filter_map(Result::ok).collect();    let mut out = Vec::new();    for a in acts {        out.push(json!({ "act_id": a, "read": handed_ids(ix, &a)? }));    }    Ok(json!({ "count": tally(ix, "handed").0, "acts": out }))}/// The face crop for the phone's face model, the same on both phones:/// `{rgba|rgb: {width, height, pixels (base64)}, points: [x0, y0, … x4, y4]/// (shares of width and height, origin top left), side?: 112}` →/// `{rgb: base64, side}`, or `null` for points that cannot be a face.fn face_align(r: &Value) -> Result<Value, MethodError> {    let (key, channels) = if r["rgba"].is_object() { ("rgba", 4) } else { ("rgb", 3) };    let g = &r[key];    let (w, h) = (g["width"].as_u64().unwrap_or(0) as u32, g["height"].as_u64().unwrap_or(0) as u32);    let px = base64::engine::general_purpose::STANDARD.decode(g["pixels"].as_str().unwrap_or("")).map_err(|e| bad(format!("{key} pixels: {e}")))?;    if px.len() != w as usize * h as usize * channels {        return Err(bad(format!("{key} pixels do not fill width x height")));    }    let points: Vec<f32> = serde_json::from_value(r["points"].clone()).map_err(|_| bad("points: ten numbers"))?;    let points: [f32; 10] = points.try_into().map_err(|_| bad("points: ten numbers"))?;    let side = r["side"].as_u64().unwrap_or(face::SIDE as u64).clamp(16, 512) as u32;    Ok(match face::align(&px, w, h, channels, &points, side) {        Some(rgb) => json!({ "rgb": base64::engine::general_purpose::STANDARD.encode(rgb), "side": side }),        None => Value::Null,    })}fn you(ix: &Index) -> Result<Value, MethodError> {    let (n, bytes, exact) = tally(ix, "bin");    let gone = tally(ix, "retired").0;    Ok(json!({        "title": "You",        "gone": (gone > 0).then(|| json!({ "line": words::retired(gone), "act": words::CLEAR_GONE, "count": gone })),        "rows": [            { "row": "look", "label": "Look" },            { "row": "faces", "label": "Faces", "value": "On" },            { "row": "bin", "label": "Bin", "value": if n == 0 { "Empty".to_string() } else { words::bin_head(n, bytes, exact) } },            { "row": "sync", "label": "Sync" },            { "row": "claude", "label": "Your Claude" },            { "row": "privacy", "label": "Privacy", "value": "Every photo is looked at on this phone." },            { "row": "storage", "label": "Storage" },            { "row": "help", "label": "Help and feedback" },            { "row": "about", "label": "About" }        ]    }))}/// **The one way a photo is handed to the phone (rule 2, decision M-b).**/// The core's [`core_handing::free_plan`] alone makes a `Mark::Handed` (it/// carries a seal no other code can make) and a/// [`core_handing::PlatformList`]; this module is the store it reads and/// writes, and the only place marks are written. Everything else writes/// marks through [`put_choice`], which cannot express Handed.mod handing {    use super::*;    use core_handing::{Store, Verdict, Waiting};    pub(super) fn put_choice(ix: &Index, id: &str, mark: Chosen, act: &str, why: &str) -> Result<(), MethodError> {        write(ix, id, Mark::from(mark), act, why)    }    fn write(ix: &Index, id: &str, mark: Mark, act: &str, why: &str) -> Result<(), MethodError> {        let at = match mark {            Mark::Keep { at_ms } | Mark::Bin { at_ms } | Mark::Handed { at_ms, .. } | Mark::Freed { at_ms } => at_ms,            Mark::None => 0,        };        let seq = ix.next_seq()?;        let fp = ix.fp(id);        track(ix, id, || {            ix.conn                .prepare_cached("INSERT INTO mark (id, mark, state, at, act, why, seq, fp, suspended) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 0) ON CONFLICT (id) DO UPDATE SET mark = excluded.mark, state = excluded.state, at = excluded.at, act = excluded.act, why = excluded.why, seq = excluded.seq, fp = excluded.fp, suspended = 0")                .map_err(db)?                .execute(params![id, serde_json::to_string(&mark).unwrap(), state_of(&mark), at, act, why, seq, fp])                .map(|_| ())                .map_err(db)        })    }    /// The index as the core's handing sees it, for one Delete.    struct HandStore<'a> {        ix: &'a Index,        act: &'a str,        now: i64,    }    impl Store for HandStore<'_> {        type Error = MethodError;        fn waiting(&mut self, budget: usize) -> Result<Vec<Waiting>, MethodError> {            let rows = self                .ix                .conn                .prepare_cached("SELECT pos, id, after_why, main FROM act_item WHERE act = ?1 AND after_mark = 'hand' AND applied = ?2 ORDER BY pos LIMIT ?3")                .map_err(db)?                .query_map(params![self.act, APPLIED, budget.min(i64::MAX as usize) as i64], |r| Ok(Waiting { pos: r.get(0)?, id: r.get(1)?, why: r.get(2)?, main: r.get(3)? }))                .map_err(db)?                .filter_map(Result::ok)                .collect();            Ok(rows)        }        /// At this moment: still binned and present; the id read again since        /// the library changed (tier one); not edited since he binned it (tier        /// two); for a main item no copy rule against it ([`held_reason`]); a        /// part only with its main.        fn verdict(&mut self, w: &Waiting) -> Result<Verdict, MethodError> {            let (ix, id) = (self.ix, w.id.as_str());            // nothing is ever handed to an Android phone (look-only for now)            if ix.platform() == Platform::Android {                return Ok(Verdict::Hold("not_on_this_phone".to_string()));            }            if !ix.mark(id).in_bin() || !ix.present(id) {                return Ok(Verdict::Skip);            }            if !ix.verified(id) {                return Ok(Verdict::Hold("not_checked".to_string()));            }            if content_changed(&ix.mark_fp(id), &ix.fp(id)) {                return Ok(Verdict::Hold("edited_since_binned".to_string()));            }            if w.main {                if let Some(reason) = held_reason(ix, id, &w.why, self.act) {                    return Ok(if stays_in_bin(&reason) { Verdict::Hold(reason) } else { Verdict::KeepBack(reason) });                }                return Ok(Verdict::Go);            }            let main_handed = ix                .conn                .prepare_cached("SELECT 1 FROM item JOIN act_item ON act_item.id = item.part_of WHERE item.id = ?1 AND act_item.act = ?2 AND act_item.applied = ?3")                .map_err(db)?                .exists(params![id, self.act, HANDED])                .map_err(db)?;            Ok(if main_handed { Verdict::Go } else { Verdict::Skip })        }        fn hand(&mut self, w: &Waiting, mark: Mark) -> Result<(), MethodError> {            write(self.ix, &w.id, mark, self.act, &w.why)?;            self.ix.conn.prepare_cached("UPDATE act_item SET applied = ?3 WHERE act = ?1 AND pos = ?2").map_err(db)?.execute(params![self.act, w.pos, HANDED]).map(|_| ()).map_err(db)        }        fn decided(&mut self, w: &Waiting, verdict: &Verdict) -> Result<(), MethodError> {            let note = match verdict {                Verdict::Go | Verdict::Skip => None,                Verdict::Hold(reason) => Some(reason.as_str()),                Verdict::KeepBack(reason) => {                    put_choice(self.ix, &w.id, Chosen::Keep { at_ms: self.now }, self.act, "")?;                    Some(reason.as_str())                }            };            self.ix.conn.prepare_cached("UPDATE act_item SET note = coalesce(?3, note), applied = ?4 WHERE act = ?1 AND pos = ?2").map_err(db)?.execute(params![self.act, w.pos, note, SKIPPED]).map(|_| ()).map_err(db)        }        fn slice_done(&mut self, handed: &[String]) -> Result<(), MethodError> {            after_marks(self.ix, handed)        }        fn progress(&mut self) -> Result<(usize, Vec<String>), MethodError> {            let left: i64 = self.ix.conn.query_row("SELECT count(*) FROM act_item WHERE act = ?1 AND after_mark = 'hand' AND applied = ?2", params![self.act, APPLIED], |r| r.get(0)).map_err(db)?;            let handed = self.ix.conn.prepare_cached("SELECT id FROM act_item WHERE act = ?1 AND applied = ?2 ORDER BY pos").map_err(db)?.query_map(params![self.act, HANDED], |r| r.get(0)).map_err(db)?.filter_map(Result::ok).collect();            Ok((left as usize, handed))        }        fn finish(&mut self, asking: bool) -> Result<(), MethodError> {            self.ix.conn.execute("UPDATE act SET state = ?2 WHERE id = ?1", params![self.act, if asking { "asking" } else { "final" }]).map(|_| ()).map_err(db)        }    }    /// A slice of a Delete's handing, decided by the core.    pub(super) fn free_plan(ix: &Index, act: &str, now: i64, budget: usize) -> Result<core_handing::Listed, MethodError> {        core_handing::free_plan(&mut HandStore { ix, act, now }, act, ix.platform(), now, budget)    }    /// Settle one handed photo from a read of the library (rule 3): present →    /// back in the Bin with the why it had; trashed or absent → freed. Answers    /// whether it was freed.    pub(super) fn settle_one(ix: &Index, act: &str, id: &str, state: &str, now: i64) -> Result<bool, MethodError> {        let before_why: String = ix            .conn            .query_row("SELECT coalesce(before_why, '') FROM act_item WHERE act = ?1 AND id = ?2 ORDER BY pos DESC LIMIT 1", params![act, id], |r| r.get(0))            .optional()            .map_err(db)?            .unwrap_or_default();        let lib = bin::LibraryState::from_key(state).unwrap_or(bin::LibraryState::Absent);        let after = Chosen::from_mark(bin::settled(lib, now)).unwrap_or(Chosen::Freed { at_ms: now });        let freed = !after.in_bin();        put_choice(ix, id, after, act, if freed { "" } else { &before_why })?;        ix.conn.execute("UPDATE act_item SET applied = ?3 WHERE act = ?1 AND id = ?2 AND applied = ?4", params![act, id, if freed { FREED } else { BACK }, HANDED]).map_err(db)?;        let left = ix.conn.query_row("SELECT count(*) FROM mark WHERE state = 'handed' AND act = ?1", [act], |r| r.get::<_, i64>(0)).map_err(db)?;        if left == 0 {            ix.conn.execute("UPDATE act SET state = 'final' WHERE id = ?1 AND state = 'asking'", [act]).map_err(db)?;        }        Ok(freed)    }    /// A Delete's own read of the ids it handed (`albums.library.take {act_id,    /// states, complete}`): each is settled from what the library says. Absent    /// is believed only with the trust of a sweep (full access and the read    /// complete); otherwise the photo stays handed and `albums.waiting` still    /// lists it. Trashed and present are things the library shows, and settle    /// at once.    pub(super) fn settle(ix: &Index, act: &str, states: &[(String, String)], trusted: bool, now: i64, dates: &mut Vec<i64>) -> Result<Value, MethodError> {        let kind: Option<String> = ix.conn.query_row("SELECT kind FROM act WHERE id = ?1", [act], |r| r.get(0)).optional().map_err(db)?;        if kind.as_deref() != Some("free") {            return Err(MethodError::new("gone", "no Delete is waiting for this"));        }        let platform = ix.platform();        let (mut freed, mut back, mut unsure, mut bytes, mut exact) = (0usize, 0usize, 0usize, 0u64, true);        for (id, st) in states {            let (m, _, by) = ix.mark_row(id);            if !m.handed() || by != act {                continue;            }            let main = !ix.is_part(id);            if st == "present" {                if !ix.present(id) {                    set_present(ix, id)?;                }                settle_one(ix, act, id, "present", now)?;                back += usize::from(main);            } else if st == "absent" && !trusted {                unsure += usize::from(main);            } else {                if let Some(it) = ix.item(id) {                    let s = size::of(&it);                    bytes += s.bytes;                    exact &= s.exact;                }                if ix.present(id) {                    leave_library(ix, id, st, now, dates)?;                } else {                    settle_one(ix, act, id, st, now)?;                }                freed += usize::from(main);            }        }        let left = ix.conn.query_row("SELECT count(*) FROM mark WHERE state = 'handed' AND act = ?1", [act], |r| r.get::<_, i64>(0)).map_err(db)?;        let ids: Vec<String> = states.iter().map(|s| s.0.clone()).collect();        after_marks(ix, &ids)?;        Ok(json!({            "freed": freed,            "back": back,            "line": (freed > 0).then(|| words::deleted_after(freed, bytes, exact, platform)),            "not_done": (back > 0).then(|| words::not_freed(back)),            "waiting": left,            "unsure": (unsure > 0).then(|| json!({ "count": unsure, "why": if ix.get("permission").as_deref() == Some("full") { "not_complete" } else { "needs_full_access" } })),        }))    }}#[cfg(test)]#[path = "albums_app_tests.rs"]mod tests;#[cfg(test)]#[path = "albums_app_real_photos.rs"]mod real_photos;