Cotton code
1409 lines · 63.2 KB · RustRaw
//! Groups: a named list of one table's records that a person picked by hand//! ("Family" in People, "Weekend" in Todos), drawn as a row of stacks above//! the table's list. Four tools — `list_groups`, `create_group`,//! `update_group`, `delete_group` — plus `list_records` with `where: { group }`,//! which answers a group's members on the table's own list, and `undo`.//!//! Every table that keeps records takes groups; a table whose records are//! worked out (`derived`) is refused. A definition's `groups` says how its//! stacks are drawn above its list.//!//! ## Picked by hand, or a filter//!//! A group either holds members a person picked, or keeps a `where` — the//! grammar list_records' `where` reads (`records::parse_where`) — and its//! records are whatever that finds when it is read: "the open todos", "the//! goals still going". Never both: add, remove and order are refused on a//! filter, and a filter is never put on a hand-picked group. The filter is//! one key of `data`, so a change to it is one last write, like a rename.//!//! ## Where a group is kept//!//! Its own core table, [`GROUPS`] (`cotton_groups`): one row with its//! `name`, `table_id` (whose records it gathers) and, for a filter group, its//! `filter`. A hand-picked group's members are rows of [`MEMBERS`]//! (`cotton_group_members`), one per member, its id derived from the group//! and the record (`derived_id::group_member_id`) and its `place` the//! member's place in the group's own order. No definition names either table,//! so the generic verbs never reach them.//!//! A member is a ROW, not an entry of a list, because two devices that each//! add someone each write their own row: both stand, the same record added on//! both is the one derived row, and a removal retracts that row alone (a//! relation retract). A list under one key would be one value, and one of two//! adds made apart would vanish.//!//! Inside this module a group is still read as one map — `name`, `table`,//! `where`, and `m:<record id>` per member at its place — the shape its//! changes' before and after have always carried, so a receipt, an undo and a//! change written before 137 read alike.//!//! A member whose record is deleted or archived is left out of every read//! and comes back with its record; the key stays.//!//! A table whose definition says `groups.kept_in` keeps no rows here: its//! groups are that table's records — the photo list's are its albums — and//! every verb below hands them to [`album_groups`], which writes each as the//! album write it is.//!//! A deleted group waits in the bin under its name like any deleted record://! its receipt's Undo or `restore_from_bin` brings it back with its members,//! and emptying the bin erases it.//!//! ## Groups of tools//!//! The Tools screen's groups (Spec 9.2) are kept the same way under the table//! [`TOOLS`], but a tool is no record: its members are tool KEYS — this//! database's tools, each a row of its own — and a group answers//! them as `members` beside its `top`. "All tools" is every tool and never a//! stored group, so no group of tools takes that name.use cotton_core::records::receipt::{binned_said, Receipt, ReceiptKind, WordsChange};use super::*;use super::album_groups;/// The kind word a group answers as — a bin entry's `table`, a change's/// `table` — and the `table_id` its changes carried before 137, when a group/// was a row of the generic store.pub const TABLE: &str = "_group";/// Where a group lives (137).pub const GROUPS: &str = "cotton_groups";/// Where a hand-picked group's members live, one row each (137).pub const MEMBERS: &str = "cotton_group_members";/// The `table_id` a group's change rows carry: its storage table, as `mint`'s/// history names a core table.const CHANGE_TABLE: &str = GROUPS;/// What a member's key starts with; the rest is the record's id.const MEMBER: &str = "m:";/// The longest name a group takes.const NAME_MAX: usize = 60;/// The `where` key that narrows a table's list to one group's records.pub const WHERE_KEY: &str = "group";/// The key of a group's map that keeps its filter.const FILTER: &str = "where";/// The key of a group's map, and the column of its row, that keeps the/// list's own picture: a media key (a photo's, or a picture a document/// keeps), drawn pinned on the list's tile in place of its members' covers.pub const PICTURE: &str = "picture";/// The key of a group's map, and the column of its row, that keeps the/// list's place among its table's lists (`record_group.position`): lower/// first; a list with none stands where it was made ([`ordered`]).pub const POSITION: &str = "position";/// `update_group { id, move, record? }`: the list (or, with `record`, that/// member) one place earlier or later.pub const MOVE: &str = "move";pub const EARLIER: &str = "earlier";pub const LATER: &str = "later";/// How many of a group's first members a stack is drawn from.pub(super) const TOP: usize = 3;/// The table the Tools screen lists; its groups gather tool keys.pub const TOOLS: &str = "tool_order";/// The ready-made list of every tool, which no stored group may be called.pub const ALL_TOOLS: &str = "All tools";/// One group, read from its row and its members' rows as the one map this/// module reads (see the module header).struct Group {    id: String,    data: Data,    deleted_at: Option<String>,}impl Group {    fn from_row(db: &cotton_store::driver::Driver, row: &cotton_store::Row) -> Result<Group, String> {        let id = row.text("id").unwrap_or_default().to_string();        let data = assembled(db, row)?;        Ok(Group { id, data, deleted_at: row.text("deleted_at").map(str::to_string) })    }    fn name(&self) -> &str {        name_of(&self.data)    }    fn table(&self) -> &str {        self.data.get("table").and_then(Value::as_str).unwrap_or_default()    }    /// The members' record ids in the group's own order.    fn members(&self) -> Vec<String> {        members_of(&self.data)    }    fn holds(&self, record: &str) -> bool {        self.data.contains_key(&member_key(record))    }    /// The filter a group keeps instead of members, when it is one.    fn filter(&self) -> Option<&Value> {        filter_of(&self.data)    }    /// Where the next member added goes: after the last.    fn next_place(&self) -> f64 {        self.data            .iter()            .filter(|(key, _)| key.starts_with(MEMBER))            .filter_map(|(_, place)| place.as_f64())            .fold(0.0, f64::max)            + 1.0    }}/// A group's name, read from its map.pub fn name_of(data: &Data) -> &str {    data.get("name").and_then(Value::as_str).unwrap_or_default()}fn member_key(record: &str) -> String {    format!("{MEMBER}{record}")}/// A group's members' record ids in the group's own order, read from its map.pub fn members_of(data: &Data) -> Vec<String> {    let mut placed: Vec<(f64, &str)> = data        .iter()        .filter_map(|(key, place)| Some((place.as_f64()?, key.strip_prefix(MEMBER)?)))        .collect();    placed.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(b.1)));    placed.into_iter().map(|(_, id)| id.to_string()).collect()}/// The columns of a group's row every reader asks for.const GROUP_COLUMNS: &str = "id, table_id, name, filter, picture, position, deleted_at";/// A group's map from its row (read with [`GROUP_COLUMNS`]) and its members'/// rows: `name`, `table`, `where` for a filter, `picture` when the person/// gave the list one, `position` once it has a place among its table's/// lists, `m:<record>` per member.fn assembled(db: &cotton_store::driver::Driver, row: &cotton_store::Row) -> Result<Data, String> {    let mut data = Data::new();    data.insert("name".into(), Value::from(row.text("name").unwrap_or_default()));    data.insert("table".into(), Value::from(row.text("table_id").unwrap_or_default()));    if let Some(filter) = row.text("filter").and_then(|text| serde_json::from_str::<Value>(text).ok()) {        if filter.is_object() {            data.insert(FILTER.into(), filter);        }    }    if let Some(picture) = row.text("picture").map(str::trim).filter(|picture| !picture.is_empty()) {        data.insert(PICTURE.into(), Value::from(picture));    }    if let Some(position) = row.real(POSITION) {        data.insert(POSITION.into(), Value::from(position));    }    let members = db        .all(            &format!("SELECT record_id, place FROM {MEMBERS} WHERE group_id = ?"),            &[SqlValue::Text(row.text("id").unwrap_or_default().to_string())],        )        .map_err(|error| error.to_string())?;    for member in &members {        let (Some(record), Some(place)) = (member.text("record_id"), member.real("place")) else { continue };        data.insert(member_key(record), Value::from(place));    }    Ok(data)}/// Every live group of the file (of `workspace`, when given), each its id and/// its map, in the order they were made — what Home's catalogue and the/// phone's snapshot read.pub fn live_groups(    db: &cotton_store::driver::Driver,    workspace: Option<&str>,) -> Result<Vec<(String, Data)>, String> {    let (scope, params) = match workspace {        Some(workspace) => ("workspace_id = ? AND", vec![SqlValue::Text(workspace.to_string())]),        None => ("", Vec::new()),    };    let rows = db        .all(            &format!(                "SELECT {GROUP_COLUMNS} FROM {GROUPS} WHERE {scope} deleted_at IS NULL ORDER BY created_at, id"            ),            &params,        )        .map_err(|error| error.to_string())?;    rows.iter()        .map(|row| Ok((row.text("id").unwrap_or_default().to_string(), assembled(db, row)?)))        .collect()}/// One group's map and when it was deleted, live or binned: `None` when the/// file holds no such group.pub fn group_of(    db: &cotton_store::driver::Driver,    id: &str,) -> Result<Option<(Data, Option<String>)>, String> {    let Some(row) = db        .get(&format!("SELECT {GROUP_COLUMNS} FROM {GROUPS} WHERE id = ?"), &[SqlValue::Text(id.to_string())])        .map_err(|error| error.to_string())?    else {        return Ok(None);    };    Ok(Some((assembled(db, &row)?, row.text("deleted_at").map(str::to_string))))}fn groups_where(ctx: &Ctx<'_>, clause: &str, params: Vec<SqlValue>) -> Valid<Vec<Group>> {    let db = ctx.read.driver();    let mut all = vec![SqlValue::Text(ctx.workspace_id.to_string())];    all.extend(params);    let rows = db        .all(            &format!("SELECT {GROUP_COLUMNS} FROM {GROUPS} WHERE workspace_id = ? {clause} ORDER BY created_at, id"),            &all,        )        .map_err(sql_err)?;    rows.iter().map(|row| Group::from_row(db, row).map_err(sql_err)).collect()}fn find(ctx: &Ctx<'_>, id: &str) -> Valid<Option<Group>> {    Ok(groups_where(ctx, "AND id = ?", vec![SqlValue::Text(id.to_string())])?.into_iter().next())}fn no_group() -> ToolFailure {    ToolFailure::new("There is no such group. It may have been deleted.")}fn live(ctx: &Ctx<'_>, id: &str) -> Valid<Group> {    find(ctx, id)?.filter(|group| group.deleted_at.is_none()).ok_or_else(no_group)}/// The grouping table and where its groups are kept, when `id` names no/// group row here but a record of a table groups are kept in (an album).fn kept_group(ctx: &Ctx<'_>, id: &str) -> Valid<Option<(TableDefinition, cotton_core::definitions::GroupsKeptIn)>> {    if find(ctx, id)?.is_some() {        return Ok(None);    }    album_groups::grouping_of(ctx, id)}/// Every live group of `table`, in its lists' order ([`ordered`]).fn groups_of(ctx: &Ctx<'_>, table: &str) -> Valid<Vec<Group>> {    Ok(ordered(groups_where(ctx, "AND table_id = ? AND deleted_at IS NULL", vec![SqlValue::Text(table.to_string())])?))}/// The ids of `table`'s live lists in their order ([`ordered`]): where a/// list stands among them, which a held list's Move earlier and Move later/// are read from.pub fn list_order(ctx: &Ctx<'_>, table: &str) -> Valid<Vec<String>> {    Ok(groups_of(ctx, table)?.into_iter().map(|group| group.id).collect())}/// The record ids of a hand-picked list's live members in its order — the/// order its deck deals them in; none for a filter list or no list here.pub fn member_order(ctx: &Ctx<'_>, id: &str) -> Valid<Vec<String>> {    let Some(group) = find(ctx, id)?.filter(|group| group.deleted_at.is_none() && group.filter().is_none()) else {        return Ok(Vec::new());    };    match gathers(ctx, group.table())? {        Gathers::Table(definition) => Ok(live_members(ctx, &definition, &group)?.into_iter().map(|stored| stored.id).collect()),        Gathers::Tools(_) => Ok(group.members()),    }}/// RULE: a table's lists stand in the order of their `position`, lower/// first; a list with none (made before lists had places, or by a write/// that gave none) stands at the place it was made — its turn among the/// table's lists in the order they were made, counted from 1 — so lists/// that never moved keep the order they always had (list-acts, 7 Nov 2026)./// Ties fall to the order they were made.fn ordered(made: Vec<Group>) -> Vec<Group> {    let mut placed: Vec<(f64, usize, Group)> =        made.into_iter().enumerate().map(|(turn, group)| (place_of(&group, turn), turn, group)).collect();    placed.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));    placed.into_iter().map(|(_, _, group)| group).collect()}/// A list's place among its table's lists: its own `position`, else its/// turn in the order the lists were made (`turn`, from 0).fn place_of(group: &Group, turn: usize) -> f64 {    group.data.get(POSITION).and_then(Value::as_f64).unwrap_or((turn + 1) as f64)}/// Every list of `table` given a place of its own where it has none, or/// shares one: each numbered 1, 2, 3… in the order they stand now, which/// that order is unchanged by — written as the rows they are and recorded as/// no change, since nothing a person sees moved. Answers the lists in order.fn placed_lists(ctx: &mut Ctx<'_>, table: &str) -> Valid<Vec<Group>> {    let lists = groups_of(ctx, table)?;    let positions: Vec<Option<f64>> = lists.iter().map(|group| group.data.get(POSITION).and_then(Value::as_f64)).collect();    let distinct = positions.windows(2).all(|pair| matches!(pair, [Some(a), Some(b)] if a < b));    if positions.iter().all(Option::is_some) && distinct {        return Ok(lists);    }    let now = now_iso(ctx);    for (turn, group) in lists.iter().enumerate() {        let mut patch = Map::new();        patch.insert(POSITION.into(), Value::from((turn + 1) as f64));        patch.insert("updated_at".into(), Value::from(now.clone()));        update_row(ctx, GROUPS, &group.id, patch)?;    }    ctx.commit()?;    groups_of(ctx, table)}/// A table's lists put in the order `order` names, the ones it leaves out after them as they stood (Cinemas' home/// rows, 26 Nov 2026: he orders his groups by dragging, and that order is the rows' order). Each is numbered 1, 2, 3…/// as the rows they are. An id that is no live list of `table` is refused before anything is written. Answers the/// lists' ids in their new order.pub fn order_lists(ctx: &mut Ctx<'_>, table: &str, order: &[String]) -> Valid<Vec<String>> {    let lists = groups_of(ctx, table)?;    if let Some(stray) = order.iter().find(|id| !lists.iter().any(|group| &group.id == *id)) {        return Err(ToolFailure::new(format!("{stray} is not one of this table's lists.")));    }    let mut ids: Vec<String> = Vec::new();    for id in order.iter().chain(lists.iter().map(|group| &group.id)) {        if !ids.contains(id) {            ids.push(id.clone());        }    }    let now = now_iso(ctx);    for (turn, id) in ids.iter().enumerate() {        let mut patch = Map::new();        patch.insert(POSITION.into(), Value::from((turn + 1) as f64));        patch.insert("updated_at".into(), Value::from(now.clone()));        update_row(ctx, GROUPS, id, patch)?;    }    ctx.commit()?;    Ok(ids)}/// The place between the two neighbours a moving item lands between, one/// of them absent at an end of its list; None where no place lies strictly/// between them (two that share a place).fn between(before: Option<f64>, after: Option<f64>) -> Option<f64> {    let place = match (before, after) {        (Some(before), Some(after)) => (before + after) / 2.0,        (Some(before), None) => before + 1.0,        (None, Some(after)) => after - 1.0,        (None, None) => return None,    };    (before.is_none_or(|before| before < place) && after.is_none_or(|after| place < after)).then_some(place)}/// The direction a `move` asks: earlier (-1) or later (+1).fn move_arg(args: &Map<String, Value>) -> Valid<isize> {    match args.get(MOVE).and_then(Value::as_str) {        Some(EARLIER) => Ok(-1),        Some(LATER) => Ok(1),        _ => Err(ToolFailure::new("move is earlier or later.")),    }}/// Where `item` lands one step `by` along `order` (the places in order, with/// the ids they belong to): the place between its new neighbours. None at/// an end, where it cannot move that way.fn stepped(order: &[(String, f64)], item: &str, by: isize) -> Option<Option<f64>> {    let at = order.iter().position(|(id, _)| id == item)?;    let to = at.checked_add_signed(by).filter(|to| *to < order.len())?;    let others: Vec<f64> = order.iter().filter(|(id, _)| id != item).map(|(_, place)| *place).collect();    // Among the others, it lands before the one now at `to`'s turn.    Some(between(to.checked_sub(1).and_then(|turn| others.get(turn)).copied(), others.get(to).copied()))}/// What a table's groups gather: its own records, or — for [`TOOLS`] — the/// tools of this database, each key with the name it is shown by.enum Gathers {    Table(TableDefinition),    Tools(Vec<(String, String)>),}impl Gathers {    fn id(&self) -> &str {        match self {            Gathers::Table(definition) => &definition.id,            Gathers::Tools(_) => TOOLS,        }    }    fn tool(&self, key: &str) -> Option<&str> {        match self {            Gathers::Table(_) => None,            Gathers::Tools(tools) => tools.iter().find(|(id, _)| id == key).map(|(_, name)| name.as_str()),        }    }    /// Refused unless `record` can be a member: a live record of the table,    /// or a tool of this database.    fn check_member(&self, ctx: &Ctx<'_>, record: &str) -> Valid<()> {        match self {            // An archived record is put away, not gone: it stays a member            // and joins a group like any other (notes-empty, 21 Nov 2026: an            // archived note's hashtag filed into its tag was refused "That            // note is no longer here", and every Notes list with it). Only a            // binned record, or none, is refused.            Gathers::Table(definition) => match load(ctx, definition, record)? {                Some(stored) if stored.deleted_at.is_none() || only_archived(definition, &stored) => Ok(()),                _ => Err(not_found(definition, record)),            },            Gathers::Tools(_) => match self.tool(record) {                Some(_) => Ok(()),                None => Err(ToolFailure::new("There is no tool of that name in this database.")),            },        }    }}/// Whether what puts `stored` away is its table's archive column alone (a/// read answers an archived record as gone, as it does a binned one).fn only_archived(definition: &TableDefinition, stored: &Stored) -> bool {    let set = |column: &str| stored.data.get(column).and_then(Value::as_str).filter(|value| !value.is_empty());    let Some(archived) = definition.archived.as_deref().and_then(set) else { return false };    set("trashed_at").is_none() && stored.deleted_at.as_deref() == Some(archived)}/// What `table`'s groups gather, whether or not its definition names groups —/// what a receipt names a group's members by.fn gathers(ctx: &Ctx<'_>, table: &str) -> Valid<Gathers> {    if table.trim() == TOOLS {        return Ok(Gathers::Tools(tools(ctx)?));    }    Ok(Gathers::Table(definition(ctx, table)?))}/// Every tool of this database, key and name: the tools installed here — the/// set the Tools screen lists. No tool is built in (72nd amendment).fn tools(ctx: &Ctx<'_>) -> Valid<Vec<(String, String)>> {    let mut tools: Vec<(String, String)> = Vec::new();    let installed = ctx        .read        .driver()        .all(            "SELECT id, json_extract(definition, '$.name') AS name FROM cotton_tool_definitions \             WHERE workspace_id = ? ORDER BY id",            &[SqlValue::Text(ctx.workspace_id.to_string())],        )        .map_err(sql_err)?;    for row in &installed {        let Some(id) = row.text("id").filter(|id| !tools.iter().any(|(key, _)| key == id)) else {            continue;        };        tools.push((id.to_string(), row.text("name").unwrap_or(id).to_string()));    }    Ok(tools)}/// What a table that takes groups gathers, or the refusal.fn grouped(ctx: &Ctx<'_>, table: &str) -> Valid<Gathers> {    let gathers = gathers(ctx, table)?;    if let Gathers::Table(definition) = &gathers {        if !takes_groups(definition) {            return Err(ToolFailure::new(format!("{} are not gathered into groups.", definition.plural)));        }    }    Ok(gathers)}/// Does `definition`'s table take groups: every table that keeps records,/// but one whose records are worked out, and one with a column called/// `group` (which `where: { group }` would then mean).fn takes_groups(definition: &TableDefinition) -> bool {    definition.derived != Some(true) && definition.column(WHERE_KEY).is_none()}/// The group's members that are live records, in the group's order.fn live_members(ctx: &Ctx<'_>, definition: &TableDefinition, group: &Group) -> Valid<Vec<Stored>> {    let mut records = Vec::new();    for id in group.members() {        if let Some(stored) = load(ctx, definition, &id)?.filter(|stored| stored.deleted_at.is_none()) {            records.push(stored);        }    }    Ok(records)}/// A group as every read and write answers it: its name, how many live/// records it holds, and its first few as the table's own records — what a/// stack is drawn from. A group of tools also answers every member's key, in/// its order, which its page lists; a tool no longer here is left out.fn group_json(ctx: &mut Ctx<'_>, gathers: &Gathers, group: &Group) -> Valid<Value> {    let definition = match gathers {        Gathers::Table(definition) => definition,        Gathers::Tools(_) => {            let members: Vec<String> =                group.members().into_iter().filter(|key| gathers.tool(key).is_some()).collect();            let top: Vec<Value> = members                .iter()                .take(TOP)                .map(|key| json!({ "id": key, "table": TOOLS, "data": { "name": gathers.tool(key), "object": key } }))                .collect();            return Ok(json!({                "id": group.id,                "name": group.name(),                "table": TOOLS,                "count": members.len(),                "top": top,                "members": members,            }));        }    };    if let Some(filter) = group.filter() {        let found = super::list_records(            ctx,            &json!({ "table": definition.id, "where": filter, "limit": TOP }).as_object().cloned().unwrap_or_default(),        )?;        return Ok(json!({            "id": group.id,            "name": group.name(),            "table": definition.id,            "count": found["total"],            "top": found["records"],            "where": filter,            "picture": group.data.get(PICTURE),        }));    }    let mut members = live_members(ctx, definition, group)?;    let count = members.len();    members.truncate(TOP);    derive_records(ctx, definition, &mut members, &Map::new(), false)?;    Ok(json!({        "id": group.id,        "name": group.name(),        "table": definition.id,        "count": count,        "top": members.iter().map(|stored| stored.to_json(&definition)).collect::<Vec<_>>(),        "picture": group.data.get(PICTURE),    }))}/// `list_groups { table, record? }` → `{ table, groups: [group] }`, in the/// order the groups were made. With `record`, each group also says `holds`:/// whether that record is in it. Without `table`, every group of the/// database ([`every_group`]).pub fn list_groups(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    if optional_string(args, "table").is_none() {        return every_group(ctx, args);    }    let gathers = grouped(ctx, &id_arg(args, "table")?)?;    let record = optional_string(args, "record");    if let Gathers::Table(definition) = &gathers {        if let Some(kept) = album_groups::kept_in(definition) {            return album_groups::list(ctx, definition, kept, record);        }    }    let mut groups = Vec::new();    for group in groups_of(ctx, gathers.id())? {        let mut answer = group_json(ctx, &gathers, &group)?;        if let Some(record) = &record {            answer["holds"] = Value::from(holds(ctx, &gathers, &group, record)?);        }        groups.push(answer);    }    Ok(json!({ "table": gathers.id(), "groups": groups }))}/// Each of `table`'s groups as a list of them shows it: id, name and how many live records it holds, in their/// order. No member is read for its derived columns (CONTACTS AT SIZE: 200 groups of people took 201M steps that/// way, each group's top members' figures worked out for a list that shows only names and counts).pub fn group_summaries(ctx: &mut Ctx<'_>, table: &str) -> Valid<Vec<Value>> {    let gathers = grouped(ctx, table)?;    let Gathers::Table(definition) = &gathers else { return Ok(Vec::new()) };    let definition = definition.clone();    let mut out = Vec::new();    for group in groups_of(ctx, &definition.id)? {        let count = match group.filter() {            Some(filter) => {                let found = super::list_records(ctx, &json!({ "table": definition.id, "where": filter, "limit": 1 }).as_object().cloned().unwrap_or_default())?;                found["total"].as_u64().unwrap_or(0) as usize            }            // Counted where the members are kept, never by loading each one (a person's load works out its figures).            None => {                let db = ctx.read.driver();                let store = cotton_core::definitions::builtin_store_table(&definition.id).map_or_else(|| format!("cotton_{}", definition.id), str::to_string);                let has = |table: &str, column: &str| {                    db.get(&format!("SELECT 1 AS one FROM pragma_table_info('{table}') WHERE name = ?"), &[SqlValue::Text(column.to_string())]).map(|r| r.is_some()).unwrap_or(false)                };                let mut live = String::new();                for column in ["trashed_at", "deleted_at"] {                    if has(&store, column) {                        live.push_str(&format!(" AND r.{column} IS NULL"));                    }                    if has(MEMBERS, column) {                        live.push_str(&format!(" AND m.{column} IS NULL"));                    }                }                let row = db                    .get(&format!("SELECT COUNT(DISTINCT r.id) AS n FROM {MEMBERS} m JOIN {store} r ON r.id = m.record_id WHERE m.group_id = ?{live}"), &[SqlValue::Text(group.id.clone())])                    .map_err(sql_err)?;                row.and_then(|r| r.int("n")).unwrap_or(0) as usize            }        };        out.push(json!({ "id": group.id, "name": group.name(), "count": count }));    }    Ok(out)}/// `list_groups {}` → `{ groups: [group] }`: every group of this database,/// whatever table it gathers, in the order they were made — the database's/// views read in one call. Each says its `table`./// A group whose table is no longer here (its tool was removed) is left out:/// nothing can read its records. `record` belongs to one table's read.fn every_group(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    if optional_string(args, "record").is_some() {        return Err(ToolFailure::new("record is a record of one table: say which table."));    }    let every = groups_where(ctx, "AND deleted_at IS NULL", Vec::new())?;    let mut gathered: Vec<(String, Option<Gathers>)> = Vec::new();    let mut groups = Vec::new();    for group in &every {        let table = group.table().to_string();        if !gathered.iter().any(|(known, _)| *known == table) {            let found = grouped(ctx, &table).ok();            gathered.push((table.clone(), found));        }        let Some((_, Some(gathers))) = gathered.iter().find(|(known, _)| *known == table) else { continue };        groups.push(group_json(ctx, gathers, group)?);    }    Ok(json!({ "groups": groups }))}/// Whether `record` is in the group: one of its members, or a live record/// its filter finds.fn holds(ctx: &Ctx<'_>, gathers: &Gathers, group: &Group, record: &str) -> Valid<bool> {    let zone = crate::mcp::handlers::common::where_zone(ctx)?;    let (Some(filter), Gathers::Table(definition)) = (group.filter(), gathers) else {        return Ok(group.holds(record));    };    let Some(stored) = load(ctx, definition, record)?.filter(|stored| stored.deleted_at.is_none()) else {        return Ok(false);    };    let clauses = records::parse_where(definition, Some(filter)).map_err(refuse)?;    Ok(clauses.iter().all(|clause| records::holds(&stored.data, clause, &zone)))}/// The group a `list_records` narrows to: `where: { group: <id> }` on a table/// that takes groups. `group` is not a column of any such table/// ([`takes_groups`]), so the key can only mean this.pub(super) fn named_in_where(definition: &TableDefinition, args: &Map<String, Value>) -> Option<String> {    if !takes_groups(definition) {        return None;    }    args.get("where")?.get(WHERE_KEY)?.as_str().map(str::trim).filter(|id| !id.is_empty()).map(str::to_string)}/// A filter group's read: the same ask with the group's filter as its/// `where`, which list_records then answers as any filtered read of the/// table — by the day plan, when the table is read as one. `None` for a/// hand-picked group.pub(super) fn filtered(    ctx: &Ctx<'_>,    definition: &TableDefinition,    group: &str,    args: &Map<String, Value>,) -> Valid<Option<Map<String, Value>>> {    if album_groups::kept_in(definition).is_some() {        return Ok(None);    }    let group = checked(ctx, definition, group, args)?;    Ok(group.filter().map(|filter| {        let mut asked = args.clone();        asked.insert("where".into(), filter.clone());        asked    }))}/// The live group a `where: { group }` names, refused beside anything else/// that names records and when it gathers another table.fn checked(ctx: &Ctx<'_>, definition: &TableDefinition, group: &str, args: &Map<String, Value>) -> Valid<Group> {    refuse_beside_group(args)?;    let group = live(ctx, group)?;    if group.table() != definition.id {        return Err(ToolFailure::new(format!("{} is not a group of {}.", group.name(), definition.plural)));    }    Ok(group)}/// Refused: a `where: { group }` beside anything else that names records.fn refuse_beside_group(args: &Map<String, Value>) -> Valid<()> {    let narrowed_more = args.get("where").and_then(Value::as_object).is_some_and(|clauses| clauses.len() > 1);    if let Some(other) = ["ids", "project"]        .into_iter()        .find(|key| args.get(*key).is_some_and(|value| !value.is_null()))        .or(narrowed_more.then_some("another where"))    {        return Err(ToolFailure::new(format!("group names the records itself; ask without {other}")));    }    Ok(())}/// Whether a group of `definition` is read as its table's day plan: a list/// of work still to do (`upcoming`: Todos) or a list split into days (the/// Calendar). Its page is then the table's own list narrowed to the members —/// every member, in the plan's order, with `sections` counted over the whole/// group — never the group's hand order paged fifty at a time, whose first/// page held the oldest members and left this week's todos unread.pub(super) fn planned(definition: &TableDefinition) -> bool {    definition.upcoming.is_some() || (definition.day_grouping.is_some() && definition.date.is_some())}/// The ids of a planned group's members, after the same checks/// [`list_in_group`] makes; the table's list narrows to them.pub(super) fn planned_members(    ctx: &Ctx<'_>,    definition: &TableDefinition,    group: &str,    args: &Map<String, Value>,) -> Valid<Vec<String>> {    Ok(checked(ctx, definition, group, args)?.members())}/// `list_records { table, where: { group }, query?, page?, limit? }`: the/// group's live members on the table's own list, in the group's order./// `total` is how many the group holds that `query` matches.pub(super) fn list_in_group(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    group: &str,    args: &Map<String, Value>,) -> ToolResult {    let offset = match args.get("page") {        None | Some(Value::Null) => 0,        Some(value) => value            .as_u64()            .ok_or_else(|| ToolFailure::new("page is the number of records to skip, 0 or more"))? as usize,    };    let limit = bounded_limit(args, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE).max(1) as usize;    let mut members = match album_groups::kept_in(definition) {        Some(kept) => {            refuse_beside_group(args)?;            album_groups::members(ctx, definition, kept, group)?        }        None => {            let group = checked(ctx, definition, group, args)?;            live_members(ctx, definition, &group)?        }    };    if let Some(query) = optional_string(args, "query") {        members.retain(|stored| records::matches_query(definition, &stored.data, &query));    }    let total = members.len();    let mut page: Vec<Stored> = members.into_iter().skip(offset).take(limit).collect();    derive_records(ctx, definition, &mut page, args, false)?;    let next = (offset + page.len() < total).then_some(offset + page.len());    Ok(json!({        "table": definition.id,        "records": page.iter().map(|stored| stored.to_json(&definition)).collect::<Vec<_>>(),        "next_page": next,        "total": total,    }))}/// The filter a group's row keeps, when it is a filter group.pub fn filter_of(data: &Data) -> Option<&Value> {    data.get(FILTER).filter(|filter| filter.is_object())}// ── arguments ───────────────────────────────────────────────────────────────fn name_arg(ctx: &Ctx<'_>, table: &str, args: &Map<String, Value>, except: Option<&str>) -> Valid<String> {    let name = optional_string(args, "name")        .filter(|name| name.chars().count() <= NAME_MAX)        .ok_or_else(|| ToolFailure::new(format!("Give the group a name of up to {NAME_MAX} characters.")))?;    if table == TOOLS && name.to_lowercase() == ALL_TOOLS.to_lowercase() {        return Err(ToolFailure::new(format!("{ALL_TOOLS} is ready-made: it is every tool. Give the group another name.")));    }    // One "Family" per table: a second would be two stacks nobody can tell apart.    if groups_of(ctx, table)?        .iter()        .any(|other| Some(other.id.as_str()) != except && other.name().to_lowercase() == name.to_lowercase())    {        return Err(ToolFailure::new(format!("There is already a group called {name}.")));    }    Ok(name)}/// The record ids `key` lists, each once, in the order given; `None` when the/// argument is absent.pub(super) fn records_arg(args: &Map<String, Value>, key: &str) -> Valid<Option<Vec<String>>> {    let items = match args.get(key) {        None | Some(Value::Null) => return Ok(None),        Some(Value::Array(items)) if !items.is_empty() => items,        Some(_) => return Err(ToolFailure::new(format!("{key} is a list of one or more record ids"))),    };    let mut ids: Vec<String> = Vec::new();    for item in items {        let id = item            .as_str()            .map(str::trim)            .filter(|id| !id.is_empty())            .ok_or_else(|| ToolFailure::new(format!("each of {key} is one record id")))?;        if !ids.iter().any(|seen| seen == id) {            ids.push(id.to_string());        }    }    Ok(Some(ids))}/// The filter `args` gives under `where`, checked as list_records' `where`/// is and then read once, so a filter the table's reader cannot answer is/// refused now and never kept to answer nothing later. `None` when absent.fn filter_arg(ctx: &mut Ctx<'_>, gathers: &Gathers, args: &Map<String, Value>) -> Valid<Option<Value>> {    let filter = match args.get(FILTER) {        None | Some(Value::Null) => return Ok(None),        Some(Value::Object(filter)) if !filter.is_empty() => filter,        Some(_) => {            return Err(ToolFailure::new(                "where is an object of column keys and the values they hold, like list_records' where",            ))        }    };    let Gathers::Table(definition) = gathers else {        return Err(ToolFailure::new("A group of tools holds tools picked by hand; it takes no where."));    };    if filter.contains_key(WHERE_KEY) {        return Err(ToolFailure::new("A group's where names columns of its table, never another group."));    }    let filter = Value::Object(filter.clone());    records::parse_where(definition, Some(&filter)).map_err(refuse)?;    // Asked only to see the filter refused or answered, never counted.    super::list_answer(        ctx,        &json!({ "table": definition.id, "where": filter, "limit": 1 }).as_object().cloned().unwrap_or_default(),        super::Total::Skipped,    )?;    Ok(Some(filter))}/// The list's own picture `args` gives: a media key of this database (a/// photo's, or one `put_document` kept), or null to take it off.fn picture_arg(ctx: &Ctx<'_>, args: &Map<String, Value>) -> Valid<Value> {    match args.get(PICTURE) {        None | Some(Value::Null) => Ok(Value::Null),        Some(Value::String(key)) if cotton_core::media::keys::is_key_in_workspace(Some(key), ctx.file.id()) => {            Ok(Value::from(key.trim()))        }        Some(_) => Err(ToolFailure::new(            "picture is the media key of a picture in this database (a photo's, or the storage_path put_document answers), or null to take it off",        )),    }}// ── receipts ────────────────────────────────────────────────────────────────/// Who a receipt names: one record (or tool) by its own name, several by how many.fn who(ctx: &Ctx<'_>, gathers: &Gathers, ids: &[&str]) -> String {    let definition = match gathers {        Gathers::Table(definition) => definition,        Gathers::Tools(_) => {            return match ids {                [key] => gathers.tool(key).map(str::to_string).unwrap_or_else(|| "1 tool".into()),                _ => format!("{} tools", ids.len()),            };        }    };    if let [id] = ids {        if let Ok(Some(stored)) = load(ctx, definition, id) {            return cotton_core::records::receipt::record_name_in(definition, &Value::Object(stored.data), &super::date_words(ctx));        }    }    let noun = if ids.len() == 1 { &definition.name } else { &definition.plural };    format!("{} {}", ids.len(), noun.to_lowercase())}/// What a change to a group says: a verb and the names — "Made Family with/// Asha", "Added Asha to Family", "Removed 3 people from Family", "Moved/// Family to the bin" (a deleted group is in the bin, never gone). A rename/// says both names and carries the words before and after.fn receipt(ctx: &Ctx<'_>, change: &Change, name: &str) -> Receipt {    let plain = |kind, said: String| Receipt { kind, said, words: Vec::new(), values: Vec::new() };    let (before, after) = (change.before.as_object(), change.after.as_object());    match change.verb {        Verb::Create => {            // The records it was made holding, named, so "Made Book club"            // never leaves out who was put in it.            let held: Vec<&str> = after                .into_iter()                .flatten()                .filter(|(_, place)| !place.is_null())                .filter_map(|(key, _)| key.strip_prefix(MEMBER))                .collect();            let gathered = gathers(ctx, &change_table(ctx, change)).ok();            match (&gathered, held.is_empty()) {                (Some(gathered), false) => {                    plain(ReceiptKind::Added, format!("Made {name} with {}", who(ctx, gathered, &held)))                }                _ => plain(ReceiptKind::Added, format!("Made {name}")),            }        }        Verb::Delete => plain(ReceiptKind::Deleted, binned_said(name, true)),        Verb::Restore => plain(ReceiptKind::PutBack, format!("Put back {name}")),        Verb::Move => plain(ReceiptKind::Moved, "Moved".to_string()),        Verb::MoveIn => plain(ReceiptKind::MovedIn, "Moved here".to_string()),        Verb::Update | Verb::Link | Verb::Reorder => {            let empty = Data::new();            let (before, after) = (before.unwrap_or(&empty), after.unwrap_or(&empty));            if after.contains_key(FILTER) {                return plain(ReceiptKind::Edited, format!("Changed what {name} shows"));            }            if after.contains_key(POSITION) {                return plain(ReceiptKind::Reordered, format!("Moved {name}"));            }            if after.contains_key(PICTURE) {                return match after.get(PICTURE).filter(|picture| !picture.is_null()) {                    Some(_) => plain(ReceiptKind::Edited, format!("Gave {name} a picture")),                    None => plain(ReceiptKind::Edited, format!("Took {name}'s picture off")),                };            }            if let Some(new) = after.get("name").and_then(Value::as_str) {                let old = before.get("name").and_then(Value::as_str);                return Receipt {                    kind: ReceiptKind::Edited,                    said: match old {                        Some(old) if old != new => format!("Renamed {old} to {new}"),                        _ => format!("Renamed {new}"),                    },                    words: vec![WordsChange {                        name: "Name".into(),                        before: before.get("name").and_then(Value::as_str).map(str::to_string),                        after: Some(new.to_string()),                    }],                    values: Vec::new(),                };            }            let was_in = |key: &String| before.get(key).is_some_and(|place| !place.is_null());            let moved: Vec<(&String, &Value)> = after.iter().filter(|(key, _)| key.starts_with(MEMBER)).collect();            let ids = |keep: &dyn Fn(&(&String, &Value)) -> bool| -> Vec<&str> {                moved.iter().filter(|entry| keep(entry)).filter_map(|(key, _)| key.strip_prefix(MEMBER)).collect()            };            let added = ids(&|(key, place)| !place.is_null() && !was_in(key));            let removed = ids(&|(_, place)| place.is_null());            let gathered = gathers(ctx, &change_table(ctx, change)).ok();            let named = |ids: &[&str]| match &gathered {                Some(gathered) => who(ctx, gathered, ids),                None => ids.len().to_string(),            };            if !added.is_empty() && added.len() == moved.len() {                plain(ReceiptKind::Added, format!("Added {} to {name}", named(&added)))            } else if !removed.is_empty() && removed.len() == moved.len() {                plain(ReceiptKind::Changed, format!("Removed {} from {name}", named(&removed)))            } else {                plain(ReceiptKind::Reordered, format!("Reordered {name}"))            }        }    }}/// The table whose records the changed group gathers.fn change_table(ctx: &Ctx<'_>, change: &Change) -> String {    change        .record_id        .as_deref()        .and_then(|id| find(ctx, id).ok().flatten())        .map(|group| group.table().to_string())        .unwrap_or_default()}/// A group's change as every write answers it — the generic change's shape,/// with the group's own receipt. Every change to a group can be undone.fn change_json(ctx: &Ctx<'_>, change: &Change, name: &str) -> Value {    let refusal = change.undone_by.is_some().then(|| RecordError::AlreadyUndone.to_string());    json!({        "id": change.id,        // A group answers as its kind word, whichever table its change row names.        "table": TABLE,        "record_id": change.record_id,        "verb": change.verb.as_str(),        "byline": change.byline,        "before": change.before,        "after": change.after,        "created_at": change.created_at,        "undone_by": change.undone_by,        "undoable": refusal.is_none(),        "reason": refusal,        "receipt": receipt(ctx, change, name),    })}// ── writes ──────────────────────────────────────────────────────────────────/// Write `keys` of the group's map — only these keys, a null taking one away:/// `name` and `where` on the group's own row, each `m:<record>` as that/// member's own row (a null retracts it). Every write stamps the group's row/// with who wrote it last. Two devices' writes to different members are two/// rows, so both stand.fn write_keys(ctx: &mut Ctx<'_>, id: &str, keys: Data) -> Valid<()> {    let now = now_iso(ctx);    let mut row = Map::new();    for (key, value) in keys {        if let Some(record) = key.strip_prefix(MEMBER) {            write_member(ctx, id, record, &value, &now)?;        } else if key == "name" {            row.insert("name".into(), value);        } else if key == FILTER {            row.insert("filter".into(), value);        } else if key == PICTURE {            row.insert(PICTURE.into(), value);        } else if key == POSITION {            row.insert(POSITION.into(), value);        }    }    row.insert("record_byline".into(), Value::from(byline(ctx)));    row.insert("updated_at".into(), Value::from(now));    update_row(ctx, GROUPS, id, row)?;    ctx.commit()}/// One member's row: placed at `place` (made when the group does not hold/// the record yet), or retracted for a null — a membership is a relation,/// and the record added again later is an ordinary create of the same row.fn write_member(ctx: &mut Ctx<'_>, group: &str, record: &str, place: &Value, now: &str) -> Valid<()> {    let id = cotton_store::protocol::derived_id::group_member_id(group, record);    let held = ctx        .read        .driver()        .get(&format!("SELECT 1 AS held FROM {MEMBERS} WHERE id = ?"), &[SqlValue::Text(id.clone())])        .map_err(sql_err)?        .is_some();    match (place.as_f64(), held) {        (None, true) => ctx.writer()?.retract(MEMBERS, &id, crate::mcp::writer::Retract::Relation),        (None, false) => {}        (Some(place), true) => {            let mut patch = Map::new();            patch.insert("place".into(), Value::from(place));            patch.insert("updated_at".into(), Value::from(now));            update_row(ctx, MEMBERS, &id, patch)?;        }        (Some(place), false) => {            let mut patch = Map::new();            patch.insert("id".into(), Value::from(id.clone()));            patch.insert("group_id".into(), Value::from(group));            patch.insert("record_id".into(), Value::from(record));            patch.insert("place".into(), Value::from(place));            insert_row(ctx, MEMBERS, &id, patch)?;        }    }    Ok(())}fn set_deleted(ctx: &mut Ctx<'_>, id: &str, deleted: bool) -> Valid<()> {    let now = now_iso(ctx);    let mut patch = Map::new();    patch.insert("deleted_at".into(), if deleted { Value::from(now.clone()) } else { Value::Null });    patch.insert("updated_at".into(), Value::from(now));    patch.insert("record_byline".into(), Value::from(byline(ctx)));    update_row(ctx, GROUPS, id, patch)?;    ctx.commit()}/// A write's answer: its change, and the group as it now stands (null once/// deleted).fn answer(ctx: &mut Ctx<'_>, change: &Change, name: &str) -> ToolResult {    let group = match change.record_id.as_deref().map(|id| live(ctx, id)) {        Some(Ok(group)) => {            let gathers = gathers(ctx, group.table())?;            group_json(ctx, &gathers, &group)?        }        _ => Value::Null,    };    Ok(json!({ "change": change_json(ctx, change, name), "group": group }))}/// `create_group { table, name, records? }` → `{ change, group }`.pub fn create_group(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    atomically_noted(ctx, |ctx| {        let gathers = grouped(ctx, &id_arg(args, "table")?)?;        if let Gathers::Table(definition) = &gathers {            if let Some(kept) = album_groups::kept_in(definition) {                return album_groups::create(ctx, definition, kept, args);            }        }        let name = name_arg(ctx, gathers.id(), args, None)?;        let records = records_arg(args, "records")?;        let filter = filter_arg(ctx, &gathers, args)?;        if records.is_some() && filter.is_some() {            return Err(ToolFailure::new(                "A group holds records picked by hand or keeps a where, not both: give records or where.",            ));        }        // A new list lands last among its table's lists.        let last = placed_lists(ctx, gathers.id())?.last().and_then(|group| group.data.get(POSITION).and_then(Value::as_f64));        let position = last.map_or(1.0, |last| last + 1.0);        let mut data = Data::new();        data.insert("name".into(), Value::from(name.clone()));        data.insert("table".into(), Value::from(gathers.id()));        data.insert(POSITION.into(), Value::from(position));        let mut row = Map::new();        row.insert(POSITION.into(), Value::from(position));        if let Some(filter) = filter {            data.insert(FILTER.into(), filter.clone());            row.insert("filter".into(), filter);        }        let mut members = Vec::new();        for (place, record) in records.unwrap_or_default().iter().enumerate() {            gathers.check_member(ctx, record)?;            let place = (place + 1) as f64;            data.insert(member_key(record), Value::from(place));            members.push((record.clone(), place));        }        let id = ctx.new_uuid();        row.insert("id".into(), Value::from(id.clone()));        row.insert("table_id".into(), Value::from(gathers.id()));        row.insert("name".into(), Value::from(name.clone()));        row.insert("record_byline".into(), Value::from(byline(ctx)));        insert_row(ctx, GROUPS, &id, row)?;        let now = now_iso(ctx);        for (record, place) in members {            write_member(ctx, &id, &record, &Value::from(place), &now)?;        }        ctx.commit()?;        let change = record_change(ctx, CHANGE_TABLE, Some(&id), Verb::Create, Value::Null, Value::Object(data))?;        ctx.commit()?;        answer(ctx, &change, &name)    })}/// `update_group { id, name | add | remove | order | where | picture | move }`/// → `{ change, group }`. One thing per call, so its receipt says one thing:/// a new `name`; `add` records, after the last member; `remove` records;/// `order`, members in their new order (the rest follow, as they stood); a/// filter group's new `where`; the list's own `picture`, a media key of/// this database, `null` taking it off; or `move` (`earlier` | `later`):/// the list one place along its table's lists, or with `record` that member/// one place along the list — refused at the end it cannot pass.pub fn update_group(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    atomically_noted(ctx, |ctx| {        let id = id_arg(args, "id")?;        if let Some((grouping, kept)) = kept_group(ctx, &id)? {            return album_groups::update(ctx, &grouping, &kept, &id, args);        }        let group = live(ctx, &id)?;        let gathers = grouped(ctx, group.table())?;        // A picture named null is asked too: it takes the list's picture off.        let asked: Vec<&str> = ["name", "add", "remove", "order", FILTER, PICTURE, MOVE]            .into_iter()            .filter(|key| args.get(*key).is_some_and(|value| !value.is_null()) || (*key == PICTURE && args.contains_key(PICTURE)))            .collect();        let [asked] = asked[..] else {            return Err(ToolFailure::new("Say one change: name, add, remove, order, where, picture or move."));        };        let name = group.name().to_string();        let member = optional_string(args, "record");        if member.is_some() && asked != MOVE {            return Err(ToolFailure::new("record names the member a move moves; say move."));        }        let moves_member = asked == MOVE && member.is_some();        match (group.filter().is_some(), asked) {            (true, "add" | "remove" | "order") => {                return Err(ToolFailure::new(format!(                    "{name} shows what its filter finds, not records picked by hand; change the filter with where."                )))            }            (true, MOVE) if moves_member => {                return Err(ToolFailure::new(format!(                    "{name} shows what its filter finds, not records picked by hand; change the filter with where."                )))            }            (false, FILTER) => {                return Err(ToolFailure::new(format!(                    "{name} holds records picked by hand; make a new group to keep a filter."                )))            }            _ => {}        }        let mut keys = Data::new();        // A list may first be given its place, and its neighbours theirs:        // nothing moves by it, so it is no change of its own.        let group = if asked == MOVE && !moves_member {            placed_lists(ctx, gathers.id())?;            live(ctx, &id)?        } else {            group        };        match asked {            MOVE => {                let by = move_arg(args)?;                let (key, order) = match &member {                    Some(record) => {                        if !group.holds(record) {                            return Err(ToolFailure::new(format!("{record:?} is not in {name}.")));                        }                        // Its live members as they stand, by their places.                        let placed: Vec<(String, f64)> = match &gathers {                            Gathers::Table(definition) => live_members(ctx, definition, &group)?.into_iter().map(|stored| stored.id).collect(),                            Gathers::Tools(_) => group.members(),                        }                        .into_iter()                        .filter_map(|id| group.data.get(&member_key(&id)).and_then(Value::as_f64).map(|place| (id, place)))                        .collect();                        (member_key(record), placed)                    }                    None => {                        let lists = groups_of(ctx, gathers.id())?;                        let placed = lists.iter().filter_map(|list| list.data.get(POSITION).and_then(Value::as_f64).map(|place| (list.id.clone(), place))).collect();                        (POSITION.to_string(), placed)                    }                };                let item = member.clone().unwrap_or_else(|| group.id.clone());                let Some(landing) = stepped(&order, &item, by) else {                    let end = if by < 0 { "first" } else { "last" };                    return Err(ToolFailure::new(match &member {                        Some(_) => format!("That is already {end} in {name}."),                        None => format!("{name} is already {end}."),                    }));                };                match landing {                    Some(place) => {                        keys.insert(key, Value::from(place));                    }                    // Two members that share a place: every member placed                    // again, in the order they stand with this one moved.                    // (A list's neighbours never share one: they were placed.)                    None => {                        let mut ids: Vec<String> = order.into_iter().map(|(id, _)| id).collect();                        let at = ids.iter().position(|id| *id == item).unwrap_or_default();                        let moving = ids.remove(at);                        ids.insert(at.saturating_add_signed(by).min(ids.len()), moving);                        for (place, id) in ids.iter().enumerate() {                            keys.insert(member_key(id), Value::from((place + 1) as f64));                        }                    }                }            }            PICTURE => {                keys.insert(PICTURE.into(), picture_arg(ctx, args)?);            }            "name" => {                let new = name_arg(ctx, gathers.id(), args, Some(&group.id))?;                if new != name {                    keys.insert("name".into(), Value::from(new));                }            }            FILTER => {                if let Some(filter) = filter_arg(ctx, &gathers, args)? {                    keys.insert(FILTER.into(), filter);                }            }            "add" => {                let mut place = group.next_place();                for record in records_arg(args, "add")?.unwrap_or_default() {                    gathers.check_member(ctx, &record)?;                    if !group.holds(&record) {                        keys.insert(member_key(&record), Value::from(place));                        place += 1.0;                    }                }                if keys.is_empty() {                    return Err(ToolFailure::new(format!("Already in {name}.")));                }            }            "remove" => {                for record in records_arg(args, "remove")?.unwrap_or_default() {                    if group.holds(&record) {                        keys.insert(member_key(&record), Value::Null);                    }                }                if keys.is_empty() {                    return Err(ToolFailure::new(format!("Not in {name}.")));                }            }            _ => {                let order = records_arg(args, "order")?.unwrap_or_default();                if let Some(stranger) = order.iter().find(|record| !group.holds(record)) {                    return Err(ToolFailure::new(format!("{stranger:?} is not in {name}.")));                }                // Every member is placed again — those named first, the rest                // after them as they stood — so no two ever share a place.                let rest: Vec<String> = group.members().into_iter().filter(|member| !order.contains(member)).collect();                for (place, record) in order.iter().chain(&rest).enumerate() {                    keys.insert(member_key(record), Value::from((place + 1) as f64));                }            }        }        let (was, now) = records::diff(&group.data, &records::apply_patch(&group.data, &keys));        if now.is_empty() {            return Err(refuse(RecordError::NothingToChange));        }        write_keys(ctx, &group.id, now.clone())?;        let change = record_change(ctx, CHANGE_TABLE, Some(&group.id), Verb::Update, Value::Object(was), Value::Object(now))?;        ctx.commit()?;        let name = live(ctx, &group.id)?.name().to_string();        answer(ctx, &change, &name)    })}/// `delete_group { id }` → `{ change, group: null }`. The records it held/// are untouched; undo brings the group back with its members.pub fn delete_group(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    atomically_noted(ctx, |ctx| {        let id = id_arg(args, "id")?;        if let Some((_, kept)) = kept_group(ctx, &id)? {            return album_groups::delete(ctx, &kept, &id);        }        let group = live(ctx, &id)?;        set_deleted(ctx, &group.id, true)?;        let change =            record_change(ctx, CHANGE_TABLE, Some(&group.id), Verb::Delete, Value::Object(group.data.clone()), Value::Null)?;        ctx.commit()?;        let mut answered = change_json(ctx, &change, group.name());        if !crate::mcp::handlers::bin::bin_shown(ctx)? {            answered["receipt"]["said"] = Value::from(binned_said(group.name(), false));        }        Ok(json!({ "change": answered, "group": Value::Null }))    })}/// Whether a change row is a group's: its storage table, or the kind word a/// change written before 137 carries.pub(super) fn is_group_change(table_id: &str) -> bool {    table_id == CHANGE_TABLE || table_id == TABLE}/// `undo` of a change to a group: the same plan every undo follows/// (`records::plan_undo` — refused once undone, or once a later change moved/// the same name or member), written the way a group is written.pub(super) fn undo(ctx: &mut Ctx<'_>, original: Change, born: &str) -> ToolResult {    let id = original.record_id.clone().unwrap_or_default();    let group = find(ctx, &id)?.ok_or_else(no_group)?;    // A change written before 137 names the generic store's kind word.    let mut later = later_changes(ctx, TABLE, born)?;    later.extend(later_changes(ctx, CHANGE_TABLE, born)?);    let current = Current::Record(group.deleted_at.is_none().then(|| group.data.clone()));    let (verb, before, after) = match records::plan_undo(&original, &later, &current, None).map_err(refuse)? {        Inverse::Delete { .. } => {            set_deleted(ctx, &id, true)?;            (Verb::Delete, Value::Object(group.data.clone()), Value::Null)        }        Inverse::Restore { .. } => {            set_deleted(ctx, &id, false)?;            (Verb::Restore, Value::Null, Value::Object(group.data.clone()))        }        Inverse::Patch { patch, .. } => {            let (was, now) = records::diff(&group.data, &records::apply_patch(&group.data, &patch));            write_keys(ctx, &id, now.clone())?;            (Verb::Update, Value::Object(was), Value::Object(now))        }        Inverse::Reorder { .. } => return Err(ToolFailure::new("this change cannot be undone")),    };    let undo_change_id = ctx.new_uuid();    write_undo_mark(ctx, &original.id, &undo_change_id)?;    let change = record_change_as(ctx, undo_change_id, CHANGE_TABLE, Some(&id), verb, before, after)?;    ctx.commit()?;    let name = find(ctx, &id)?.map(|group| group.name().to_string()).unwrap_or_default();    let undone = Change { undone_by: Some(change.id.clone()), ..original };    let mut answer = answer(ctx, &change, &name)?;    answer["undone"] = change_json(ctx, &undone, &name);    answer["record"] = Value::Null;    Ok(answer)}/// Put a restored group back in the bin — the Undo of its restore through/// the bin table — recording the `delete` any delete of a group does.pub(super) fn bin_again(ctx: &mut Ctx<'_>, id: &str) -> Valid<()> {    let group = live(ctx, id)?;    set_deleted(ctx, id, true)?;    record_change(ctx, CHANGE_TABLE, Some(id), Verb::Delete, Value::Object(group.data), Value::Null)?;    ctx.commit()}/// Bring a deleted group back out of the bin with every member it held,/// recording the `restore` change any restore does: `false` when the group/// was not in the bin.pub(super) fn restore_binned(ctx: &mut Ctx<'_>, id: &str) -> Valid<bool> {    let Some(group) = find(ctx, id)?.filter(|group| group.deleted_at.is_some()) else {        return Ok(false);    };    set_deleted(ctx, id, false)?;    record_change(ctx, CHANGE_TABLE, Some(id), Verb::Restore, Value::Null, Value::Object(group.data))?;    ctx.commit()?;    Ok(true)}