Cotton code
636 lines · 29.4 KB · RustRaw
//! The repeat editor's four verbs — `make_todo_recurring`,//! `update_todo_recurrence`, `stop_todo_recurrence`,//! `materialize_todo_recurrences`.//!//! `packages/core/src/services/todoRecurrences.service.ts`, ported clause for//! clause. The DECISION about which occurrences exist stays where it already is//! — `cotton_core::rules::todo_recurrence::plan_materialization`, reached//! through `records_1::engine_shim::materialize_template` — and nothing here//! expands a rule a second way. What is here is the three writes the app's//! repeat sheet makes, and the pass the app runs when it comes to the//! foreground.//!//! WHY THESE ARE OWNER-SCOPE. The verb grid refuses all five `todo_recurrence`//! verbs, and the refusal on `update` names the reason: *"editing one occurrence//! is update_todo; reshaping the rule is its own record page in the app."* That//! sentence is true and it is product surface — an assistant reshaping the//! series behind a person's repeating obligations is not something this surface//! allows. So the app's editor gets the verbs it always had, on//! [`crate::mcp::protocol::McpScope::Owner`], and the grid's refusals for an//! assistant are unchanged.//!//! THE TEMPLATE + INSTANCES SHAPE, in one paragraph, because every rule below//! depends on it. A repeating todo is a `cotton_todo_recurrences` row (the//! template: title, notes, priority, rrule, dtstart, paused,//! `materialized_until`) plus `cotton_todos` rows carrying `recurrence_id` and//! `occurrence_at`. `materialized_until` is a MARK — everything up to it has//! been projected — and it must never go backwards, because a regressing mark//! makes the next pass re-project occurrences that already exist. There is//! exactly one sanctioned regression and it is written out at its call site.use crate::mcp::writer::Retract;use cotton_core::transforms::rrule::{next_after_parsed, parse_todo_rule};use cotton_store::protocol::derived_id::recurrence_occurrence_id;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use crate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult};use crate::mcp::handlers::common::{    flag, insert_row, int, iso_of_ms, maybe_row, now_iso, now_ms, optional_boolean, parse_ms,    optional_zone, require_string, require_uuid, row_by_id, rows, text, update_row,    workspace_timezone_or_null, Valid,};use crate::mcp::handlers::records_1::engine_shim::{    materialize_template, RecurrenceTemplate, RECURRENCE_TEMPLATE_COLUMNS,};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Order, Query};pub fn handlers() -> HandlerGroup {    &[        ("make_todo_recurring", make_todo_recurring),        ("update_todo_recurrence", update_todo_recurrence),        ("stop_todo_recurrence", stop_todo_recurrence),        ("materialize_todo_recurrences", materialize_todo_recurrences),    ]}const TABLE: &str = "cotton_todo_recurrences";const TODOS: &str = "cotton_todos";/// The zone a rule is expanded in — `services/workspaceZone.ts::expansionZone`,/// exactly: the WORKSPACE's own zone, else the device's, and never a UTC floor.////// The order is the whole point and it is the duplication guard, not a/// preference. The row id of a materialised occurrence is DERIVED from its/// instant, so two producers reading the rule in two zones compute two instants,/// two ids, no unique-constraint conflict — and the person sees every repeating/// todo twice. The workspace's recorded zone is the one value every producer can/// agree on, so it wins wherever it exists; the device's is the momentary/// fallback for a workspace that has never recorded one.////// A caller with NEITHER is refused rather than floored to UTC. The reader's/// floor (`workspace_timezone`) is honest for a read — "we were not told" draws/// something — and dishonest for a WRITER, which would mint rows at instants no/// other producer computes. `create_todo`'s repeating path already refuses for/// the same reason.fn expansion_zone(ctx: &Ctx<'_>, args: &Map<String, Value>) -> Valid<String> {    if let Some(recorded) = workspace_timezone_or_null(ctx)? {        return Ok(recorded);    }    optional_zone(args)?.ok_or_else(|| {        ToolFailure::new(            "this database has not recorded a timezone yet — pass `timezone`, the zone this              device is standing in, so every producer of this series computes the same instants",        )    })}/// At the foreground pass: if nothing has recorded the workspace's zone, record/// THIS DEVICE's — `services/workspaceZone.ts::claimWorkspaceZone`, ported.////// ONE PRODUCER PER STATE is the property being bought. Before this existed, a/// zone-less workspace had the phone falling back to the device zone while the/// server rested rather than guess: two halves with different answers about/// when a repeating todo happens, which is exactly the duplication the derived/// occurrence id was supposed to end. The phone is the half that can actually/// know — it has a person and a clock — so it writes the zone down on the same/// synced row the server reads, and both halves converge.////// It writes ONLY when there is no settings row at all. A row implies a/// recorded zone: `timezone` is `NOT NULL` with `CHECK (length(trim(...)) > 0)`./// And it deliberately does NOT key off [`workspace_timezone_or_null`], which/// answers `None` both for "unset" and for "set to a zone this runtime cannot/// read" — opposite situations. A device with a smaller zone table than the one/// that chose it would otherwise overwrite somebody else's decision on every/// launch, for ever.////// A caller that passed no `timezone` claims nothing and changes nothing: this/// core has no clock of its own to ask, and inventing UTC here is the very/// floor the module header refuses.////// An app whose kit does not carry `news_settings` (Books, Music, Cinemas,/// Story) claims nothing either: no copy of such an app ever takes that/// table's definition or rows, so the row could never be sent, and it stood/// in the outbox for ever ("Waiting to send 1 row", 21 Nov 2026). A kit whose/// tables read the database's zone carries the table.fn claim_workspace_zone(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> Result<(), ToolFailure> {    if ctx.services.this_file.as_ref().is_some_and(|file| !file.carries("news_settings")) {        return Ok(());    }    let settled = maybe_row(        ctx,        &Query::on("cotton_news_settings").columns(&["workspace_id"]),    )?;    if settled.is_some() {        return Ok(());    }    let Some(zone) = optional_zone(args)? else {        return Ok(());    };    let workspace = ctx.workspace_id.to_string();    let mut patch = Map::new();    patch.insert("workspace_id".to_string(), Value::from(workspace.clone()));    patch.insert("timezone".to_string(), Value::from(zone));    insert_row(ctx, "cotton_news_settings", &workspace, patch)?;    Ok(())}// ── the template, as it goes back out ───────────────────────────────────────/// One template in the tool's camel case — `toITodoRecurrence`.fn template_out(row: &Map<String, Value>) -> Value {    let mut out = Map::new();    out.insert("id".to_string(), Value::from(text(row, "id")));    out.insert(        "title".to_string(),        Value::from(text(row, "title").unwrap_or_default()),    );    out.insert(        "notes".to_string(),        text(row, "notes").map_or(Value::Null, Value::from),    );    out.insert("priority".to_string(), Value::from(int(row, "priority")));    out.insert(        "rrule".to_string(),        Value::from(text(row, "rrule").unwrap_or_default()),    );    out.insert(        "dtstart".to_string(),        Value::from(text(row, "dtstart").unwrap_or_default()),    );    out.insert("paused".to_string(), Value::Bool(flag(row, "paused")));    out.insert(        "materializedUntil".to_string(),        text(row, "materialized_until").map_or(Value::Null, Value::from),    );    Value::Object(out)}fn template_by_id(ctx: &Ctx<'_>, id: &str) -> Valid<Map<String, Value>> {    maybe_row(        ctx,        &Query::on(TABLE)            .columns(RECURRENCE_TEMPLATE_COLUMNS)            .eq("id", id.to_string()),    )?    .ok_or_else(|| ToolFailure::new(format!("no repeating todo with id {id}")))}/// The template's OPEN instances still in the future, earliest first.////// Overdue open instances are deliberately not here: they are independent/// obligations the person still owes, and an edit to the rule does not erase/// something that was already due./// Is an open, unbinned occurrence of this series already due (the live copy/// a person has not yet done)?fn open_overdue_instance(ctx: &Ctx<'_>, recurrence_id: &str, now_iso: &str) -> Valid<bool> {    let found = rows(        ctx,        &Query::on(TODOS)            .columns(&["id"])            .eq("recurrence_id", recurrence_id.to_string())            .eq("status", "open".to_string())            .filter(Filter::IsNull("trashed_at".to_string()))            .filter(Filter::Lte(                "occurrence_at".to_string(),                SqlValue::Text(now_iso.to_string()),            ))            .limit(1),    )?;    Ok(!found.is_empty())}fn open_future_instances(ctx: &Ctx<'_>, recurrence_id: &str, now_iso: &str) -> Valid<Vec<String>> {    let found = rows(        ctx,        &Query::on(TODOS)            .columns(&["id", "occurrence_at"])            .eq("recurrence_id", recurrence_id.to_string())            .eq("status", "open".to_string())            .filter(Filter::Gt(                "occurrence_at".to_string(),                SqlValue::Text(now_iso.to_string()),            ))            .order_by("occurrence_at", Order::Asc),    )?;    Ok(found.iter().filter_map(|row| text(row, "id")).collect())}/// Is some OTHER instance already sitting in this occurrence slot?////// The case it exists for: a future occurrence the person completed early. Its/// row is not open, so `open_future_instances` never saw it, and moving the/// kept projection onto that instant would put two todos on one occurrence.fn slot_taken(    ctx: &Ctx<'_>,    recurrence_id: &str,    occurrence_iso: &str,    except_id: Option<&str>,) -> Valid<bool> {    let found = rows(        ctx,        &Query::on(TODOS)            .columns(&["id"])            .eq("recurrence_id", recurrence_id.to_string())            .eq("occurrence_at", occurrence_iso.to_string()),    )?;    Ok(found        .iter()        .filter_map(|row| text(row, "id"))        .any(|id| except_id != Some(id.as_str())))}// ── make_todo_recurring ─────────────────────────────────────────────────────/// Make an existing todo repeat.////// The todo BECOMES the template's first instance — `recurrence_id` plus/// `occurrence_at = dtstart` — and the mark starts AT the anchor, which is what/// stops the materializer creating the occurrence this todo already is. Then/// one pass runs so the series is visible immediately rather than at the next/// foreground.pub fn make_todo_recurring(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let todo_id = require_uuid(args, "todoId")?;    let Some(rrule) = require_string(args, "rrule") else {        return Err(ToolFailure::new("rrule is required"));    };    let Some(dtstart) = require_string(args, "dtstart") else {        return Err(ToolFailure::new(            "dtstart is the first occurrence's due instant, in ISO-8601",        ));    };    if parse_ms(&dtstart).is_none() {        return Err(ToolFailure::new("dtstart must be an ISO-8601 instant"));    }    // Surface an unsupported rule BEFORE writing it — the service's own first    // line, and the reason is that a rule nothing can expand is a series that    // silently mints nothing.    parse_todo_rule(&rrule).map_err(ToolFailure::new)?;    // And resolve the ZONE before writing too, for the same reason one level    // up. `expansion_zone` REFUSES a workspace that has recorded none and was    // passed none, and it used to be asked for after the template and the    // todo's anchor had already been committed — so that refusal left a    // half-made series behind: a template nothing projects and a todo now    // pointing at it. `update_todo_recurrence` already asks in this order.    let zone = expansion_zone(ctx, args)?;    let todo = row_by_id(ctx, TODOS, &todo_id)?        .ok_or_else(|| ToolFailure::new(format!("no todo with id {todo_id}")))?;    if text(&todo, "recurrence_id").is_some() {        return Err(ToolFailure::new("That todo already repeats"));    }    let id = ctx.new_uuid();    let mut template = Map::new();    template.insert(        "title".to_string(),        Value::from(text(&todo, "title").unwrap_or_default()),    );    template.insert(        "notes".to_string(),        text(&todo, "notes").map_or(Value::Null, Value::from),    );    template.insert("priority".to_string(), Value::from(int(&todo, "priority")));    template.insert("rrule".to_string(), Value::from(rrule.clone()));    template.insert("dtstart".to_string(), Value::from(dtstart.clone()));    template.insert("paused".to_string(), Value::Bool(false));    template.insert(        "materialized_until".to_string(),        Value::from(dtstart.clone()),    );    template.insert(        "source_inbox_id".to_string(),        text(&todo, "source_inbox_id").map_or(Value::Null, Value::from),    );    insert_row(ctx, TABLE, &id, template)?;    // The todo's due date SNAPS to the anchor: picking "Monthly" from the sheet    // anchors the series on the due instant the sheet was showing.    let mut moved = Map::new();    moved.insert("recurrence_id".to_string(), Value::from(id.clone()));    moved.insert("occurrence_at".to_string(), Value::from(dtstart.clone()));    moved.insert("due_at".to_string(), Value::from(dtstart));    update_row(ctx, TODOS, &todo_id, moved)?;    ctx.commit()?;    // The lookahead occurrence, so the series reads as a series at once. A    // FUTURE anchor plans nothing more, and that is the planner's own rule    // rather than a gap: the desired end state is "everything due, plus one    // upcoming", and the anchor IS the one upcoming.    let row = template_by_id(ctx, &id)?;    materialize_template(ctx, &RecurrenceTemplate::of(&row), &zone)?;    Ok(template_out(&template_by_id(ctx, &id)?))}// ── update_todo_recurrence ──────────────────────────────────────────────────/// Replace a template's state and re-project its future.////// The editor always holds the whole template it is editing, so this is a/// REPLACEMENT rather than a patch — every field is required, and the/// `previous` block is the state before the edit, which the caller has because/// it is the thing it is editing.////// Open FUTURE instances are projections of the template, so the edit rewrites/// them: the earliest one is moved in place to the next occurrence (keeping its/// id, so a detail screen the person is standing on survives the edit), any/// others go, and the mark lands on that instant. Overdue open instances are/// never touched.pub fn update_todo_recurrence(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let recurrence_id = require_uuid(args, "recurrenceId")?;    let Some(title) = require_string(args, "title") else {        return Err(ToolFailure::new("title is required"));    };    let notes = match args.get("notes") {        None => return Err(ToolFailure::new("notes is required (null for none)")),        Some(Value::Null) => None,        Some(Value::String(text)) => Some(text.clone()),        Some(_) => return Err(ToolFailure::new("notes is text or null")),    };    let priority = args        .get("priority")        .and_then(Value::as_i64)        .ok_or_else(|| ToolFailure::new("priority is required (a whole number)"))?;    let Some(rrule) = require_string(args, "rrule") else {        return Err(ToolFailure::new("rrule is required"));    };    let Some(dtstart) = require_string(args, "dtstart") else {        return Err(ToolFailure::new("dtstart is required"));    };    let paused = optional_boolean(args, "paused")?        .ok_or_else(|| ToolFailure::new("paused is required (true or false)"))?;    let previous = args        .get("previous")        .and_then(Value::as_object)        .ok_or_else(|| {            ToolFailure::new(                "previous is the template's state before this edit — {rrule, dtstart, \                 materializedUntil}",            )        })?;    let previous_rrule = text(previous, "rrule").unwrap_or_default();    let previous_dtstart = text(previous, "dtstart").unwrap_or_default();    let previous_mark = text(previous, "materializedUntil");    let rule = parse_todo_rule(&rrule).map_err(ToolFailure::new)?;    let Some(dtstart_ms) = parse_ms(&dtstart) else {        return Err(ToolFailure::new("dtstart must be an ISO-8601 instant"));    };    let existing = template_by_id(ctx, &recurrence_id)?;    let workspace_id = text(&existing, "workspace_id").unwrap_or_default();    let now = now_ms(ctx);    let now_stamp = now_iso(ctx);    let rule_changed = rrule != previous_rrule || dtstart != previous_dtstart;    // An UNCHANGED rule keeps a forward mark, so a skipped or early-completed    // occurrence stays skipped and the re-projection continues after it. A rule    // CHANGE starts a fresh projection from now.    let previous_mark_ms = previous_mark.as_deref().and_then(parse_ms);    let after = match previous_mark_ms {        Some(mark) if !rule_changed && mark > now => mark,        _ => now,    };    let zone = expansion_zone(ctx, args)?;    let next = if paused {        None    } else {        next_after_parsed(&rule, dtstart_ms, after, &zone)            .map_err(|error| ToolFailure::new(error.to_string()))?    };    // One live copy per repeat (Cotton Days, 20 Nov 2026): an open copy    // already due is the series' live one, however the rule changed. Nothing    // is projected beside it; when it is done or skipped the materializer    // makes the next after now.    let overdue_live = open_overdue_instance(ctx, &recurrence_id, &now_stamp)?;    let next_iso = if overdue_live { None } else { next.map(iso_of_ms) };    let mut patch = Map::new();    patch.insert("title".to_string(), Value::from(title.clone()));    patch.insert(        "notes".to_string(),        notes.clone().map_or(Value::Null, Value::from),    );    patch.insert("priority".to_string(), Value::from(priority));    patch.insert("rrule".to_string(), Value::from(rrule));    patch.insert("dtstart".to_string(), Value::from(dtstart));    patch.insert("paused".to_string(), Value::Bool(paused));    update_row(ctx, TABLE, &recurrence_id, patch)?;    let future = open_future_instances(ctx, &recurrence_id, &now_stamp)?;    let keep = if next_iso.is_some() {        future.first().cloned()    } else {        None    };    for instance in &future {        if keep.as_deref() == Some(instance.as_str()) {            continue;        }        ctx.writer()?.retract(TODOS, instance, Retract::Relation);    }    match (keep.as_deref(), next_iso.as_deref()) {        (Some(keep), Some(next_iso)) => {            if slot_taken(ctx, &recurrence_id, next_iso, Some(keep))? {                // The new slot is already occupied — a future occurrence was                // completed early — so the kept projection is redundant rather                // than movable.                ctx.writer()?.retract(TODOS, keep, Retract::Relation);            } else {                let mut moved = Map::new();                moved.insert("title".to_string(), Value::from(title.clone()));                moved.insert(                    "notes".to_string(),                    notes.clone().map_or(Value::Null, Value::from),                );                moved.insert("priority".to_string(), Value::from(priority));                moved.insert("occurrence_at".to_string(), Value::from(next_iso));                moved.insert("due_at".to_string(), Value::from(next_iso));                moved.insert("snoozed_until".to_string(), Value::Null);                update_row(ctx, TODOS, keep, moved)?;            }        }        (None, Some(next_iso)) if !slot_taken(ctx, &recurrence_id, next_iso, None)? => {            // No open future instance to move (it was skipped or completed            // early) and the new slot is empty: insert the projection, so the            // mark below stays honest — it must never point past an occurrence            // that does not exist.            //            // DERIVED, for the same reason the materializer's ids are: this row            // is an occurrence, and the server's own sweep may compute it too.            let id = recurrence_occurrence_id(&recurrence_id, next_iso);            let mut projection = Map::new();            projection.insert("workspace_id".to_string(), Value::from(workspace_id.clone()));            projection.insert("title".to_string(), Value::from(title));            projection.insert("notes".to_string(), notes.map_or(Value::Null, Value::from));            projection.insert("priority".to_string(), Value::from(priority));            projection.insert("status".to_string(), Value::from("open"));            projection.insert(                "recurrence_id".to_string(),                Value::from(recurrence_id.clone()),            );            projection.insert("occurrence_at".to_string(), Value::from(next_iso));            projection.insert("due_at".to_string(), Value::from(next_iso));            projection.insert("snoozed_until".to_string(), Value::Null);            projection.insert("completed_at".to_string(), Value::Null);            projection.insert("source_inbox_id".to_string(), Value::Null);            insert_row(ctx, TODOS, &id, projection)?;        }        _ => {}    }    // THE ONE SANCTIONED MARK REGRESSION: pausing (no next) parks the mark at    // NOW, so resuming re-projects from the present rather than back-filling    // the paused window.    let mut mark = Map::new();    mark.insert(        "materialized_until".to_string(),        Value::from(next_iso.unwrap_or(now_stamp)),    );    update_row(ctx, TABLE, &recurrence_id, mark)?;    ctx.commit()?;    Ok(template_out(&template_by_id(ctx, &recurrence_id)?))}// ── stop_todo_recurrence ────────────────────────────────────────────────────/// Stop repeating.////// Open future instances go — except `keepTodoId`, the instance the person is/// standing on — and surviving instances read as plain todos: their soft/// `recurrence_id` names no present template. Overdue and/// completed instances stay: they are what actually happened.pub fn stop_todo_recurrence(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let recurrence_id = require_uuid(args, "recurrenceId")?;    let keep = match args.get("keepTodoId") {        None | Some(Value::Null) => None,        Some(_) => Some(require_uuid(args, "keepTodoId")?),    };    template_by_id(ctx, &recurrence_id)?;    let now_stamp = now_iso(ctx);    let future = open_future_instances(ctx, &recurrence_id, &now_stamp)?;    let mut dropped = 0i64;    for instance in &future {        if keep.as_deref() == Some(instance.as_str()) {            continue;        }        ctx.writer()?.retract(TODOS, instance, Retract::Relation);        dropped += 1;    }    ctx.writer()?.retract(TABLE, &recurrence_id, Retract::Verb("stop_todo_recurrence"));    ctx.commit()?;    let mut out = Map::new();    out.insert("stopped".to_string(), Value::Bool(true));    out.insert("id".to_string(), Value::from(recurrence_id));    out.insert("droppedOccurrences".to_string(), Value::from(dropped));    Ok(Value::Object(out))}// ── materialize_todo_recurrences ────────────────────────────────────────────/// WHO MINTS A RECURRING TODO'S OCCURRENCES AS TIME PASSES: the file's writer/// of record, and only it (coordinator's decision (b), 17 Oct 2026; 295 C,/// walker294). That is the device that serves the file (`Held::Served`: the/// active Mac's hourly tick, `cotton_server::recurrence_worker`, and any call/// over the served file), or a device holding a copy no machine serves yet/// (`ThisFile::unserved`: a phone started on its own, or a database made here/// and not yet taken). A copy a server takes waits for that server's tick and/// the sync: a phone that minted them too queued four changes per occurrence/// at every day's first launch, and Me read "N changes waiting to send" on a/// phone whose person wrote nothing. ONE rule for both producers — the tick/// and the phone's launch pass ask this function, never a test of their own.////// A person's own act — making a todo repeat, reshaping or resuming the/// series — still materialises what it owes at once: that is their write.pub fn mints_occurrences(ctx: &Ctx<'_>) -> bool {    match ctx.writer_held() {        Some(cotton_store::mint::Held::Served) => true,        Some(cotton_store::mint::Held::Replica) => {            ctx.services.this_file.as_ref().is_some_and(|file| file.unserved)        }        // The carry's offline import writes as an import, never a pass; a        // read-only context writes nothing.        Some(cotton_store::mint::Held::Offline) | None => false,    }}/// Give every active template what it is owed — the pass as time passes.////// WHERE THIS RUNS, AND WHY IT IS A TOOL. The phone mounts/// `RecurrenceMaterializer`/// (`apps/cotton/Sources/CottonUI/Boot/RecurrenceMaterializer.swift`) in its/// ROOT view (`apps/cotton/Sources/CottonUI/Boot/RootView.swift`) and runs/// this pass at foreground, on every launch. It mints only where this device/// is the writer of record ([`mints_occurrences`]); everywhere else it claims/// the zone if none is recorded and answers `mints: false`, `created: 0`, and/// the occurrence arrives with the sync after the serving Mac's hourly tick.////// One writer either way, because the DECISION is the engine's: two passes that/// overlap plan the same occurrences and write the same derived ids, and the/// mark never regresses.////// A workspace with no recorded zone plans NOTHING and says so, rather than/// guessing UTC — the same refusal `create_todo`'s repeating path makes, and/// for the same reason.////// EVERY ACTIVE TEMPLATE, WITH NO CEILING, because `materializeForWorkspace`/// has none. There was a `MATERIALIZE_CAP` of 200 here with `more: true` in the/// answer and a comment promising *"the next pass picks the rest up"* — and/// nothing picked anything up: the read is ordered `created_at ASC` with no/// cursor and no stored state, so every pass re-walked the same first two/// hundred and the two hundred and first template never materialised at all./// A cap that silently loses a person's repeating todos for ever is strictly/// worse than a pass that is occasionally longer, and the invented ceiling had/// no source to be faithful to. If a file ever really does hold a pathological/// number of series, the answer is a resume cursor with somewhere to keep it —/// not a limit that reads like one.pub fn materialize_todo_recurrences(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    // The zone is claimed BEFORE anything is expanded, so the instants this    // pass computes are the ones every later producer will compute too.    claim_workspace_zone(ctx, args)?;    if !mints_occurrences(ctx) {        ctx.commit()?;        let mut out = Map::new();        out.insert("mints".to_string(), Value::Bool(false));        out.insert("created".to_string(), Value::from(0));        return Ok(Value::Object(out));    }    let zone = expansion_zone(ctx, args)?;    let found = rows(        ctx,        &Query::on(TABLE)            .columns(RECURRENCE_TEMPLATE_COLUMNS)            .eq("paused", false)            .order_by("created_at", Order::Asc),    )?;    let mut created = 0usize;    let mut planned = 0i64;    for row in &found {        created += materialize_template(ctx, &RecurrenceTemplate::of(row), &zone)?;        planned += 1;    }    // The same pass makes a settled monthly expectation's next month once money rows are sealed (R3).    let money = crate::mcp::handlers::records_2::money::materialize_settled_expectations(ctx)?;    // And links a sealed event's attendees to People (R3), which the object cannot read.    let attendees = crate::mcp::handlers::attendees::link_event_attendees(ctx)?;    let mut out = Map::new();    out.insert("mints".to_string(), Value::Bool(true));    // What was WRITTEN, not what was planned — `materialize_template` answers    // the rows it inserted after the skip, so a pass over templates that are    // already up to date honestly answers zero.    out.insert("created".to_string(), Value::from(created as i64));    out.insert("templates".to_string(), Value::from(planned));    out.insert("expected".to_string(), Value::from(money as i64));    out.insert("attendees_linked".to_string(), Value::from(attendees as i64));    // The zone the pass ran in, so the caller can see that its `timezone` was    // taken up rather than merely offered.    out.insert("timezone".to_string(), Value::from(zone));    ctx.commit()?;    Ok(Value::Object(out))}