//! The unlock card (sealing plan §3.2 step 3-4, §3.3)://! what the phone shows when an assistant asks to read sealed tables for a//! while, decided here from the object's `unlock_request` rows, and what an//! answer to it may say.//!//! The face draws [`UnlockCard`] and nothing else (its definition is//! `kits/keys/faces/unlock.json`, [`FACE`]): the client and token asking, the//! reason, one toggle per table (on for every table asked), one choice of how//! long ([`DURATIONS`]: 15 minutes, an hour, a day, or until the person turns//! it off; the request's suggestion on, ruling R4), and *Allow* / *Not now*. A request is shown while it is `waiting` and before//! its `expires_at`; the oldest waiting request is the card, so two//! assistants asking at once are answered in turn.//!//! While any request waits the phone polls fast ([`POLL_SECONDS`]); with//! none, the sync loop's own pace stands.//!//! After a window ends the phone moves every table it handed keys for to its//! next seal version ([`to_advance`]): rows written after the window are//! sealed under keys the window never saw (§3.2 step 8).use chrono::{DateTime, Utc};use serde::Serialize;use serde_json::{json, Map, Value};usesuper::shell_lines::LineSet;pubusecrate::seal::grant::{DURATIONS, STANDING};/// The face definition the card is drawn by.pubconst FACE: &str = include_str!("../../kits/keys/faces/unlock.json");/// The face's id.pubconst FACE_ID: &str = "unlock.card";/// The shell line set the card is worded by (`kits/shell/lines/unlock.json`).pubconst LINES: &str = "unlock";/// How often the phone syncs while a request waits, in seconds.pubconst POLL_SECONDS: u64 = 5;/// The object's tables the window is answered through.pubconst REQUEST_TABLE: &str = "unlock_request";pubconst GRANT_TABLE: &str = "unlock_grant";/// The clear log of what assistants read through a window (ruling R4).pubconst READ_TABLE: &str = "assistant_read";/// The tables every Cotton app pulls, whatever its kit, so the card, the open/// windows and the read log stand from the shell in each one./// What an assistant asks the owner to allow (ROUTES-AUDIT finding 8): its card stands wherever the unlock card does.pubconst ASK_TABLE: &str = "assistant_ask";pubconst SHELL_TABLES: [&str; 4] = [REQUEST_TABLE, GRANT_TABLE, READ_TABLE, ASK_TABLE];/// What the object stamps as a standing grant's `ends_at`.pubconst STANDING_ENDS_AT: &str = "9999-12-31T23:59:59.999Z";/// The request's suggestion: one of [`DURATIONS`], anything else 15.pubfn suggested(minutes: Option<f64>) -> u32 { minutes.filter(|m| m.fract() == 0.0 && *m >= 0.0 && *m <= f64::from(u32::MAX)).map(|m| m as u32).filter(|m| DURATIONS.contains(m)).unwrap_or(DURATIONS[0])}/// The `unlock` line naming a duration (`duration.<key>`).fn duration_line(minutes: u32) -> &'static str {match minutes {15 => "duration.quarter",60 => "duration.hour",1440 => "duration.day", _ => "duration.standing", }}/// What the card calls a duration: `15 minutes`, `1 hour`, `1 day`, `Until I turn it off`.pubfn duration_said(minutes: u32, lines: &LineSet) -> String { lines.say(duration_line(minutes), &[]).unwrap_or_default()}/// One `unlock_request` row, as the card reads it.#[derive(Debug, Clone, PartialEq, Eq)]pubstructUnlockRequest {pub id: String,pub token_id: String,pub token_name: Option<String>,pub client: String,pub tables: Vec<String>,pub reason: Option<String>,pub minutes: u32,/// The object's one-use X25519 public half, base64url.pub worker_pub: String,pub requested_at: String,pub expires_at: String,pub state: String,/// The one card for the person's own Claude: standing,/// no duration, the keys wrapped to `member_pub` (= `worker_pub`).pub account: bool,pub member_id: Option<String>,/// When the asking connection was made (the object stamps it on the/// request; absent on rows from before, when the account card's/// `requested_at` stands in: it is asked at the first connection).pub connected_at: Option<String>,/// What asks (owner, 23 Nov 2026): `code`, a token minted by hand or for a lane, Claude Code on a machine;/// `app`, an assistant connected by sign-in. Absent on rows from before: a token named `Lane …` is code.pub asker: Option<String>,/// The machine a code token was minted for (its short host name, `mac-c`), when its mint said it.pub machine: Option<String>,}/// One of the card's durations: the choice row, the suggestion on.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pubstructDurationChoice {pub minutes: u32,pub label: String,pub on: bool,}/// A table's toggle on the card.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pubstructTableToggle {pub table: String,/// What the card calls it: the table's plural (`Messages`), never its id/// unless no definition names it.pub label: String,pub on: bool,}/// The card the face draws.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pubstructUnlockCard {pub face: &'static str, #[serde(rename = "requestId")]pub request_id: String,/// Who asks: the client (`Claude (claude.ai)`), else the token's name.pub client: String, #[serde(rename = "tokenName")]pub token_name: Option<String>,/// `Allow Claude (claude.ai) to read Messages and Notes?`pub title: String,pub reason: Option<String>,pub tables: Vec<TableToggle>,/// The request's suggestion, one of [`DURATIONS`] (0 is standing): what/// *Allow* grants when no other duration is chosen.pub minutes: u32,/// The four durations as one choice row, the suggestion `on`.pub durations: Vec<DurationChoice>, #[serde(rename = "expiresAt")]pub expires_at: String,/// More requests wait behind this one.pub behind: usize,/// The places the face draws, by its definition's slots, every word/// said: `title`, `asker`, `reason`, `toggles` (`[{table, label, on}]`),/// `minutes` (the suggestion's words), `durations` (`[{minutes, label,/// on}]`), `expires`, `queue`. A place with nothing to say is absent.pub fields: Map<String, Value>,/// *Allow* and *Not now*, as the face definition names them; none while/// an Allow already given is held ([`Held::Pending`]).pub acts: Vec<FaceAct>,/// Where an Allow already given on this request stands, in words: the/// setting-up line while it is held, or why it could not be completed./// Absent when no Allow is held or failed. #[serde(skip_serializing_if = "Option::is_none")]pub status: Option<String>,/// The one card for the person's own Claude: no durations; Allow is the/// standing grant (`unlock.allow` answers it with `assistant_allow`). #[serde(skip_serializing_if = "std::ops::Not::not")]pub account: bool,/// The card in plain words (owner, 23 Nov 2026: forty raw tables): who/// asks, what it will read as groups a person knows, for how long.pub ask: Ask,/// Several of the person's own Claude Code machines wait together (owner, 23 Nov 2026: three cards came one/// after another): Allow all of them at once, each with what it asked and its own suggested time. #[serde(rename = "allowAll", skip_serializing_if = "Option::is_none")]pub allow_all: Option<AllowAll>,}/// *Allow all*: the label ("Allow all 3"), who else asks ("Also waiting: Claude Code on mac-d and Claude Code on/// mac-a"), and the requests it answers, this card's first. `unlock.allowAll {requestIds, privateKey}`.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pubstructAllowAll {pub label: String,pub line: String, #[serde(rename = "requestIds")]pub request_ids: Vec<String>,}/// Whether `request` was asked by a token the person minted for one of their own machines (or by hand): Claude/// Code. A row from before `asker` was stamped tells by the lane token's own name.pubfn is_code(request: &UnlockRequest) -> bool {match request.asker.as_deref() {Some(kind) => kind == "code",None => request.token_name.as_deref().is_some_and(|n| n.starts_with("Lane ")), }}/// What asks, in plain words (owner, 23 Nov 2026: the card said "Lane …" and a session's name, which tells a person/// nothing): "Claude Code on mac-c", "Claude Code", or a connected assistant by its own name, a Claude Code/// sign-in read as "Claude Code". Never a token's own name.pubfn asker_said(request: &UnlockRequest, lines: &LineSet) -> String {if is_code(request) {returnmatch request.machine.as_deref().filter(|m| !m.is_empty()) {Some(machine) => lines.say("names.code_on", &[("machine", machine)]).unwrap_or_default(),None => lines.say("names.code", &[]).unwrap_or_default(), }; } plain_client(&request.client, lines)}/// A connected assistant's own name, as a person reads it: a lane token's name or a Claude Code client id reads/// as Claude Code.pubfn plain_client(client: &str, lines: &LineSet) -> String {let squashed: String = client.to_lowercase().chars().filter(|c| c.is_alphanumeric()).collect();if client.starts_with("Lane ") || squashed == "claudecode" {return lines.say("names.code", &[]).unwrap_or_default(); } client.trim().to_string()}/// The card in plain words, drawn whole by every app: who asks (`who`),/// what it can read (`everything` by default, or `choose` and the `groups`/// a person picks), for how long (`how_long` with `durations`, or the/// standing line), and where to change it later (`settings`).#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pubstructAsk {/// `Claude · connected 3 days ago`: the connection's name as the person/// named it, and when it was connected.pub who: String,/// `What it can read`.pub what: String,/// The default choice: every table asked (`Everything in your Cotton` on/// the account card, `Everything it asked for` on a timed one).pub everything: Choice,/// `Choose what`, offered when what was asked spans more than one group. #[serde(skip_serializing_if = "Option::is_none")]pub choose: Option<Choice>,/// The groups the asked tables fall in, in the core's order, `other`/// last; each on. A hidden table is in none: it goes with Everything.pub groups: Vec<GroupChoice>,/// `For how long`. #[serde(rename = "howLong")]pub how_long: String,/// The account card's standing line (it has no durations), or what/// happens after a timed window. #[serde(rename = "howLongLine")]pub how_long_line: String,/// `You can see and change this any time in Settings, under Your Claude.`pub settings: String,}/// One of the card's two ways to answer what it reads.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pubstructChoice {pub label: String, #[serde(skip_serializing_if = "Option::is_none")]pub line: Option<String>,}/// A group a person knows, as the card offers it under Choose what.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pubstructGroupChoice {pub id: String,pub label: String,pub line: String,/// The asked tables it holds: what choosing it grants.pub tables: Vec<String>,pub on: bool,}/// The groups a person reads their data by (`kits/keys/reads.json`).pubconst READS: &str = include_str!("../../kits/keys/reads.json");/// The group every table no group names falls into.pubconst OTHER: &str = "other";structReads { groups: Vec<(String, Vec<String>)>, hidden: Vec<String>,}fn reads_map() -> &'staticReads {static MAP: std::sync::OnceLock<Reads> = std::sync::OnceLock::new(); MAP.get_or_init(|| {let file: Value = serde_json::from_str(READS).expect("kits/keys/reads.json reads");let names = |v: &Value| v.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect::<Vec<_>>();let groups = file["groups"].as_array().into_iter().flatten().filter_map(|g| Some((g["id"].as_str()?.to_string(), names(&g["tables"])))).collect();Reads { groups, hidden: names(&file["hidden"]) } })}/// The groups' ids in the order the card offers them, [`OTHER`] last.pubfn group_ids() -> Vec<&'static str> { reads_map().groups.iter().map(|(id, _)| id.as_str()).collect()}/// The tables the core names under each group and as hidden, for whoever/// checks the map covers every table.pubfn named_tables() -> Vec<(&'static str, &'static str)> {let map = reads_map(); map.groups.iter().flat_map(|(id, tables)| tables.iter().map(move |t| (id.as_str(), t.as_str()))).chain(map.hidden.iter().map(|t| ("hidden", t.as_str()))).collect()}/// The group a table falls into: its group by the core's map, [`OTHER`] for/// a table no group names, `None` for a hidden (system) table, which is/// never shown and is read only with Everything.pubfn group_of(table: &str) -> Option<&'static str> {let map = reads_map();if map.hidden.iter().any(|t| t == table) {returnNone; }Some(map.groups.iter().find(|(_, tables)| tables.iter().any(|t| t == table)).map_or(OTHER, |(id, _)| id.as_str()))}/// `tables` by the group each falls into, in the core's order, hidden ones left out: what Settings › Your Claude/// chooses between in an app whose kit names no groups of its own (Words, Days, Story).pubfn groups_of(tables: &[String]) -> Vec<(String, Vec<String>)> { grouped(tables).into_iter().map(|(id, tables)| (id.to_string(), tables)).collect()}/// The asked tables by group, in the core's order; hidden ones left out.fn grouped(tables: &[String]) -> Vec<(&'static str, Vec<String>)> { group_ids() .into_iter() .filter_map(|id| {let held: Vec<String> = tables.iter().filter(|t| group_of(t) == Some(id)).cloned().collect(); (!held.is_empty()).then_some((id, held)) }) .collect()}/// What Allow grants for the person's choice: `None` (Everything) is every/// table asked, hidden ones too; `Some(groups)` is the asked tables of those/// groups and nothing hidden. Refused by name for no group, or a group the/// card did not offer.pubfn chosen_tables(request: &UnlockRequest, groups: Option<&[String]>) -> Result<Vec<String>, AnswerRefusal> {letSome(groups) = groups else {letmut all: Vec<String> = request.tables.iter().filter(|t| !crate::seal::agent::closed(t)).cloned().collect(); all.sort(); all.dedup();returnOk(all); };if groups.is_empty() {returnErr(AnswerRefusal::BadTables(refused("no_groups", &[]))); }let offered = grouped(&request.tables);letmut out = Vec::new();for id in groups {let (_, tables) = offered.iter().find(|(g, _)| g == id).ok_or_else(|| AnswerRefusal::BadTables(refused("not_a_group", &[("group", id.as_str())])))?; out.extend(tables.iter().filter(|t| !crate::seal::agent::closed(t)).cloned()); } out.sort(); out.dedup();Ok(out)}/// The card's plain words for `request`.fn ask_of(request: &UnlockRequest, durations: bool, now: DateTime<Utc>, lines: &LineSet) -> Ask {let said = |line: &str, fills: &[(&str, &str)]| lines.say(line, fills).unwrap_or_default();// Claude Code on a machine by its plain name; an assistant connected by sign-in as the person named it.let name = if is_code(request) { asker_said(request, lines) } else { plain_client(&request.token_name.clone().filter(|n| !n.is_empty()).unwrap_or_else(|| request.client.clone()), lines) };let connected = request.connected_at.clone().or_else(|| request.account.then(|| request.requested_at.clone()));let who = match connected {Some(at) => said("card.who", &[("client", &name), ("when", &ago_said(&at, now, lines))]),None => name, };let groups: Vec<GroupChoice> = grouped(&request.tables) .into_iter() .map(|(id, tables)| GroupChoice { id: id.to_string(), label: said(&format!("card.groups.{id}.label"), &[]), line: said(&format!("card.groups.{id}.line"), &[]), tables, on: true }) .collect();let everything = if request.account {Choice { label: said("card.everything", &[]), line: Some(said("card.everything_line", &[])) } } else {let labels: Vec<&str> = groups.iter().map(|g| g.label.as_str()).collect();Choice { label: said("card.asked", &[]), line: Some(labels.join(&said("card.comma", &[]))).filter(|l| !l.is_empty()) } };let choose = (groups.len() > 1).then(|| Choice { label: said("card.choose", &[]), line: Some(said("card.choose_line", &[])) });Ask { who, what: said("card.what", &[]), everything, choose, groups, how_long: said("card.how_long", &[]), how_long_line: if durations { said("card.timed", &[]) } else { said("card.standing", &[]) }, settings: said("card.settings", &[]), }}/// An Allow this phone took but could not post yet (lane/// unlock-card-leftovers, 12 Nov 2026). A device whose vault is not founded/// yet founds it on the first Allow, and the founding rule opens nothing until/// the object has taken the wrap; the Allow is held for its request and/// completed by the phone itself when the founding pass lands, so the person/// taps once. While held, the card shows the setting-up line and no acts; a/// held Allow that could not be completed hands the acts back with why.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumHeld<'a> {/// Held for this request, waiting on the founding pass.Pending(&'a str),/// Completing it was refused: the sentence says why.Failed { request_id: &'a str, sentence: &'a str },}implHeld<'_> {fn request_id(&self) -> &str {matchself {Held::Pending(id) | Held::Failed { request_id: id, .. } => id, } }}/// Whether an Allow held for `request_id` is still kept: only within its/// request's life (waiting, before `expires_at`). Past it the held key is/// dropped and nothing is posted.pubfn keep_held(rows: &[Value], now: DateTime<Utc>, request_id: &str) -> bool { rows.iter().filter_map(request_of).any(|r| r.id == request_id && is_waiting(&r, now))}/// One of the face's acts as its definition names it: the button's words,/// the receipt's, and whether it reads the vault key behind presence.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pubstructFaceAct {pub id: String,pub label: String,pub method: String,pub receipt: String,pub presence: bool,}fn acts_at(pointer: &str) -> Vec<FaceAct> {let face: Value = serde_json::from_str(FACE).expect("the unlock face definition reads"); face.pointer(pointer) .and_then(Value::as_array) .into_iter() .flatten() .map(|act| FaceAct { id: text(act, "id").unwrap_or_default(), label: text(act, "label").unwrap_or_default(), method: text(act, "method").unwrap_or_default(), receipt: text(act, "receipt").unwrap_or_default(), presence: act.get("presence").and_then(Value::as_bool).unwrap_or(false), }) .collect()}/// The card's acts: *Allow*, *Not now*.pubfn card_acts() -> Vec<FaceAct> { acts_at("/acts")}/// The act on an open window's row: *End*.pubfn window_acts() -> Vec<FaceAct> { acts_at("/window/acts")}fn text(row: &Value, key: &str) -> Option<String> { row.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string)}/// A list column as the object serves it (an array) or a copy keeps it (its/// JSON text).fn list(row: &Value, key: &str) -> Vec<String> {let value = match row.get(key) {Some(Value::String(text)) => serde_json::from_str(text).unwrap_or(Value::Null),Some(other) => other.clone(),None => Value::Null, }; value.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()}/// A bool column as the object serves it or a copy keeps it (0/1, "true").pub(crate) fn flag(row: &Value, key: &str) -> bool {match row.get(key) {Some(Value::Bool(b)) => *b,Some(Value::Number(n)) => n.as_f64().is_some_and(|n| n != 0.0),Some(Value::String(t)) => t == "true" || t == "1", _ => false, }}fn at(text: &str) -> Option<DateTime<Utc>> {DateTime::parse_from_rfc3339(text).ok().map(|at| at.with_timezone(&Utc))}/// Read one `unlock_request` row (its `id` beside its columns). `None` for a/// row that lacks what a card needs.pubfn request_of(row: &Value) -> Option<UnlockRequest> {let minutes = suggested(row.get("minutes").and_then(Value::as_f64));let tables = list(row, "tables");if tables.is_empty() {returnNone; }Some(UnlockRequest { id: text(row, "id")?, token_id: text(row, "token_id")?, token_name: text(row, "token_name"), client: text(row, "client").or_else(|| text(row, "token_name"))?, tables, reason: text(row, "reason"), minutes, worker_pub: text(row, "worker_pub")?, requested_at: text(row, "requested_at")?, expires_at: text(row, "expires_at")?, state: text(row, "state")?, account: flag(row, "account"), member_id: text(row, "member_id"), connected_at: text(row, "connected_at"), asker: text(row, "asker"), machine: text(row, "machine"), })}/// Whether `request` can still be answered at `now`.pubfn is_waiting(request: &UnlockRequest, now: DateTime<Utc>) -> bool { request.state == "waiting" && at(&request.expires_at).is_some_and(|expires| now < expires)}/// The requests that wait at `now`, oldest first.pubfn waiting(rows: &[Value], now: DateTime<Utc>) -> Vec<UnlockRequest> {letmut out: Vec<UnlockRequest> = rows.iter().filter_map(request_of).filter(|r| is_waiting(r, now)).collect(); out.sort_by(|a, b| (at(&a.requested_at), &a.id).cmp(&(at(&b.requested_at), &b.id))); out}/// How often the phone should sync now: [`POLL_SECONDS`] while a timed/// request waits, else `None` (the loop's own pace). The account card stands/// until answered, so it alone keeps no fast pace.pubfn poll_seconds(rows: &[Value], now: DateTime<Utc>) -> Option<u64> { waiting(rows, now).iter().any(|r| !r.account).then_some(POLL_SECONDS)}/// `a`, `a and b`, `a, b and c`.fn joined(labels: &[&str], lines: &LineSet) -> String {match labels { [] => String::new(), [one] => (*one).to_string(), [rest @ .., last] => {let comma = lines.say("comma", &[]).unwrap_or_default(); lines.say("joined", &[("rest", &rest.join(&comma)), ("last", last)]).unwrap_or_default() } }}/// Whole minutes from `now` until `then`, rounded up; 1 at the least.fn minutes_left(now: DateTime<Utc>, then: &str) -> i64 { at(then).map_or(1, |then| ((then - now).num_seconds() + 59).div_euclid(60).max(1))}/// The tables by their labels, joined (`Notes and Messages`).fn tables_said(tables: &[String], label: implFn(&str) -> Option<String>, lines: &LineSet) -> String {let labels: Vec<String> = tables.iter().map(|t| label(t).unwrap_or_else(|| t.clone())).collect();let labels: Vec<&str> = labels.iter().map(String::as_str).collect(); joined(&labels, lines)}/// Whether an `unlock_grant` row is a standing grant: its `standing` column,/// or the object's sentinel `ends_at`.pubfn grant_standing(row: &Value) -> bool {let column = match row.get("standing") {Some(Value::Bool(b)) => *b,Some(Value::Number(n)) => n.as_f64().is_some_and(|n| n != 0.0),Some(Value::String(t)) => t == "true" || t == "1", _ => false, }; column || text(row, "ends_at").is_some_and(|ends| ends.starts_with("9999-"))}/// The words on an open window's row: its tables and what it has left/// (`Notes and Messages · 12 minutes left`; over two hours, in hours rounded/// up: `Notes · 23 hours left`); a standing window, `Notes · until you turn/// it off`.pubfn window_said(tables: &[String], ends_at: &str, now: DateTime<Utc>, label: implFn(&str) -> Option<String>, lines: &LineSet) -> String {let tables = tables_said(tables, label, lines);if ends_at.starts_with("9999-") {return lines.say("window_standing", &[("tables", &tables)]).unwrap_or_default(); }let left = minutes_left(now, ends_at);if left > 120 {let hours = ((left + 59) / 60).to_string();return lines.say("window_hours", &[("tables", &tables), ("n", &hours)]).unwrap_or_default(); } lines.say("window", &[("tables", &tables), ("n", &left.to_string())]).unwrap_or_default()}/// [`window_said`] for a grant row: a standing one by its column too.pubfn grant_said(row: &Value, now: DateTime<Utc>, label: implFn(&str) -> Option<String>, lines: &LineSet) -> String {let tables = list(row, "tables");let ends_at = if grant_standing(row) { STANDING_ENDS_AT.to_string() } else { text(row, "ends_at").unwrap_or_default() }; window_said(&tables, &ends_at, now, label, lines)}/// Whether a grant row is open at `now`: not ended, and standing or before its `ends_at`.pubfn grant_open(row: &Value, now: DateTime<Utc>) -> bool { !grant_ended(row) && (grant_standing(row) || text(row, "ends_at").and_then(|ends| at(&ends)).is_some_and(|ends| now < ends))}/// How long ago `then` was, in the `unlock` lines' words (`just now`,/// `5 minutes ago`, `3 hours ago`, `2 days ago`).pubfn ago_said(then: &str, now: DateTime<Utc>, lines: &LineSet) -> String {letSome(then) = at(then) else { returnString::new() };let minutes = (now - then).num_minutes().max(0);let (line, n) = match minutes {0 => return lines.say("ago.now", &[]).unwrap_or_default(),1..=59 => ("ago.minutes", minutes),60..=1439 => ("ago.hours", minutes / 60), _ => ("ago.days", minutes / 1440), }; lines.say(line, &[("n", &n.to_string())]).unwrap_or_default()}/// One read through a window, from the clear `assistant_read` log.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pubstructRead {pub id: String, #[serde(rename = "grantId")]pub grant_id: Option<String>,pub client: String,pub tables: Vec<String>,pub tool: Option<String>,pub rows: u64, #[serde(rename = "readAt")]pub read_at: String,/// `Claude read 12 rows of Notes and Messages · 5 minutes ago`.pub said: String,}/// How many reads the log shows.pubconst READS_SHOWN: usize = 50;/// The latest reads, newest first, at most [`READS_SHOWN`], each worded. A/// row without its client or time is left out.pubfn reads(rows: &[Value], now: DateTime<Utc>, label: implFn(&str) -> Option<String>, lines: &LineSet) -> Vec<Read> {letmut out: Vec<(DateTime<Utc>, Read)> = rows .iter() .filter_map(|row| {let read_at = text(row, "read_at")?;let when = at(&read_at)?;let client = text(row, "client")?;let tables = list(row, "tables");let count = row.get("rows").and_then(Value::as_f64).filter(|n| *n >= 0.0).map_or(0, |n| n as u64);let said = lines .say("read", &[("client", &client), ("n", &count.to_string()), ("tables", &tables_said(&tables, &label, lines)), ("when", &ago_said(&read_at, now, lines))]) .unwrap_or_default();Some((when, Read { id: text(row, "id").unwrap_or_default(), grant_id: text(row, "grant_id"), client, tables, tool: text(row, "tool"), rows: count, read_at, said })) }) .collect(); out.sort_by(|a, b| (b.0, &b.1.id).cmp(&(a.0, &a.1.id))); out.into_iter().take(READS_SHOWN).map(|(_, read)| read).collect()}/// The card for the oldest waiting request, or `None`. `label` names a/// table (its definition's plural); a table no definition names shows its id.pubfn card(rows: &[Value], now: DateTime<Utc>, label: implFn(&str) -> Option<String>, lines: &LineSet) -> Option<UnlockCard> { card_held(rows, now, label, lines, None)}/// [`card`], with where an Allow already given stands ([`Held`]): held on/// the card's request, the card says the setting-up line and offers no act;/// failed, it says why and offers the acts again.pubfn card_held(rows: &[Value], now: DateTime<Utc>, label: implFn(&str) -> Option<String>, lines: &LineSet, held: Option<Held<'_>>) -> Option<UnlockCard> {let waiting = waiting(rows, now);let request = waiting.first()?;let tables: Vec<TableToggle> = request.tables.iter().map(|t| TableToggle { table: t.clone(), label: label(t).unwrap_or_else(|| t.clone()), on: true }).collect();let labels: Vec<&str> = tables.iter().map(|t| t.label.as_str()).collect();let minutes = request.minutes;let said = |line: &str, fills: &[(&str, &str)]| lines.say(line, fills).unwrap_or_default();let minutes_said = duration_said(minutes, lines);// The one card for your Claude asks no duration: Allow is the standing grant.let durations: Vec<DurationChoice> = if request.account { Vec::new() } else { DURATIONS.iter().map(|&m| DurationChoice { minutes: m, label: duration_said(m, lines), on: m == minutes }).collect() };let ask = ask_of(request, !request.account, now, lines);// A timed card names what it asks as the groups a person knows, never the tables' own names.let group_labels: Vec<&str> = ask.groups.iter().map(|g| g.label.as_str()).collect();let asker_name = asker_said(request, lines);let title = if request.account { said("account.title", &[("client", &asker_name)]) } elseif group_labels.is_empty() { said("title", &[("client", &asker_name), ("tables", &joined(&labels, lines))]) } elseif group_labels.len() <= 2 && !ask.groups.iter().any(|g| g.id == OTHER) { said("card.title_asked", &[("client", &asker_name), ("groups", &joined(&group_labels, lines))]) } else {// Three groups and more (or Everything else) read as a list, not a title: the card lists them under Everything it asked for. said("card.title_some", &[("client", &asker_name)]) };// Its reason is the promise, said by the kit, never the asker's own sentence.let reason = if request.account { Some(said("account.promise", &[])) } else { request.reason.clone() };let behind = waiting.len() - 1;letmut fields = Map::new(); fields.insert("title".into(), json!(title));// Who asks, plain: a lane's or pasted token's own name ("Lane …") is never said; an assistant// connected by sign-in keeps its client and the name the person gave it.let asker = match &request.token_name { _ if is_code(request) => asker_name.clone(),Some(token) if *token != request.client => said("asker", &[("client", &asker_name), ("token", &plain_client(token, lines))]), _ => asker_name.clone(), }; fields.insert("asker".into(), json!(asker));ifletSome(reason) = &reason { fields.insert("reason".into(), json!(reason)); } fields.insert("toggles".into(), serde_json::to_value(&tables).unwrap_or(Value::Null));if !request.account { fields.insert("minutes".into(), json!(minutes_said)); fields.insert("durations".into(), serde_json::to_value(&durations).unwrap_or(Value::Null)); }// The account card stands until answered: no countdown.if !request.account { fields.insert("expires".into(), json!(said("waits", &[("n", &minutes_left(now, &request.expires_at).to_string())]))); }if behind > 0 { fields.insert("queue".into(), json!(said("behind", &[("n", &behind.to_string())]))); }let held = held.filter(|held| held.request_id() == request.id);let (status, acts) = match held {Some(Held::Pending(_)) => (Some(said("setting_up", &[])), Vec::new()),Some(Held::Failed { sentence, .. }) => (Some(sentence.to_string()), card_acts()),None => (None, card_acts()), };Some(UnlockCard { face: FACE_ID, request_id: request.id.clone(), client: request.client.clone(), token_name: request.token_name.clone(), title, reason, tables, minutes, durations, expires_at: request.expires_at.clone(), behind, fields, acts, status, account: request.account, ask, allow_all: allow_all_of(&waiting, request, lines), })}/// Why an answer is refused, by name.#[derive(Debug, Clone, PartialEq, Eq)]pubenumAnswerRefusal {/// No waiting request by that id (answered, expired or never asked).NotWaiting,/// A table the request did not ask for, or none at all.BadTables(String),/// Minutes that are not one of [`DURATIONS`].BadMinutes(u32),}implAnswerRefusal {pubfn code(&self) -> &'static str {matchself {AnswerRefusal::NotWaiting => "request_not_waiting",AnswerRefusal::BadTables(_) => "bad_tables",AnswerRefusal::BadMinutes(_) => "bad_minutes", } }pubfn sentence(&self) -> String {matchself {AnswerRefusal::NotWaiting => refused("not_waiting", &[]),AnswerRefusal::BadTables(why) => why.clone(),AnswerRefusal::BadMinutes(m) => refused("bad_minutes", &[("m", &m.to_string())]), } }}/// Why an answer is refused, in the `unlock` line set's words (`refused.<line>`).fn refused(line: &str, fills: &[(&str, &str)]) -> String {static LINES: std::sync::OnceLock<LineSet> = std::sync::OnceLock::new(); LINES .get_or_init(|| LineSet::shipped("unlock").expect("the kit ships the unlock set")) .say(&format!("refused.{line}"), fills) .unwrap_or_default()}/// What *Allow* may grant: the tables switched on (a non-empty subset of/// those asked, sorted) and the minutes: any of [`DURATIONS`], whatever the/// request suggested (the person's pick wins); the suggestion when none is/// given.pubfn allowed(request: &UnlockRequest, now: DateTime<Utc>, tables: Option<&[String]>, minutes: Option<u32>) -> Result<(Vec<String>, u32), AnswerRefusal> {if !is_waiting(request, now) {returnErr(AnswerRefusal::NotWaiting); }letmut chosen: Vec<String> = tables.map_or_else(|| request.tables.clone(), <[String]>::to_vec);// A closed table (Sites' list) is never granted, whatever was asked or picked. chosen.retain(|t| !crate::seal::agent::closed(t)); chosen.sort(); chosen.dedup();if chosen.is_empty() {returnErr(AnswerRefusal::BadTables(refused("no_tables", &[]))); }ifletSome(stray) = chosen.iter().find(|t| !request.tables.contains(t)) {returnErr(AnswerRefusal::BadTables(refused("not_asked", &[("table", stray.as_str())]))); }let minutes = minutes.unwrap_or(request.minutes);if !DURATIONS.contains(&minutes) {returnErr(AnswerRefusal::BadMinutes(minutes)); }Ok((chosen, minutes))}/// Whether an `unlock_grant` row has ended (the object stamped `ended_at`).pubfn grant_ended(row: &Value) -> bool { text(row, "ended_at").is_some()}/// After a window ends: of the `(table, version)` pairs this phone handed/// keys for (the newest version in the bundle), the tables whose current/// seal version has not moved past it. Each moves to its next version once;/// asking again after the advance answers nothing.pubfn to_advance(handed: &[(String, u32)], current: implFn(&str) -> u32) -> Vec<String> {letmut out: Vec<String> = handed.iter().filter(|(table, v)| current(table) <= *v).map(|(table, _)| table.clone()).collect(); out.sort(); out.dedup(); out}#[cfg(test)]#[path = "unlock_tests.rs"]mod tests;/// *Allow all* for the card's request: offered when it and at least one more waiting request are timed asks of the/// person's own Claude Code machines (never the one card for their Claude, which is answered on its own). The/// line names the others by machine, each once.fn allow_all_of(waiting: &[UnlockRequest], first: &UnlockRequest, lines: &LineSet) -> Option<AllowAll> {let together = |r: &UnlockRequest| !r.account && is_code(r);if !together(first) {returnNone; }let all: Vec<&UnlockRequest> = waiting.iter().filter(|r| together(r)).collect();if all.len() < 2 {returnNone; }letmut ids: Vec<String> = vec![first.id.clone()]; ids.extend(all.iter().filter(|r| r.id != first.id).map(|r| r.id.clone()));let mine = asker_said(first, lines);letmut others: Vec<String> = Vec::new();for r in all.iter().filter(|r| r.id != first.id) {let name = asker_said(r, lines);if !others.contains(&name) { others.push(name); } }let n = ids.len().to_string();let line = if others.iter().all(|o| *o == mine) { lines.say("card.all_same", &[("n", &n), ("client", &mine)]).unwrap_or_default() } else {let names: Vec<&str> = others.iter().map(String::as_str).collect(); lines.say("card.all_line", &[("names", &joined(&names, lines))]).unwrap_or_default() };Some(AllowAll { label: lines.say("card.allow_all", &[("n", &n)]).unwrap_or_default(), line, request_ids: ids })}/// The requests `unlock.allowAll` may answer: those named that still wait and are the person's own Claude Code/// timed asks, in the order named. Anything else named is left alone.pubfn allow_all_ids(rows: &[Value], now: DateTime<Utc>, named: &[String]) -> Vec<UnlockRequest> {let waiting = waiting(rows, now); named.iter().filter_map(|id| waiting.iter().find(|r| &r.id == id && !r.account && is_code(r)).cloned()).collect()}