//! `list_devices` — the whole MCP surface of the `device` primitive (v13).//!//! ONE verb, and it reads. The four the grid refuses are refused for one//! reason with four faces: every write to `cotton_devices` is a person on a//! screen. Joining is six digits compared on two devices; approving is a tap on//! that comparison; renaming is the label a person recognises their own Mac by;//! revoking is the act that decides who may open this database at all, and it//! is MONOTONE — nothing undoes one. A tool for any of them is a tool an//! assistant could be talked into calling.//!//! **`appVersion` IS CURRENT, and that is new.** The column used to hold//! whatever was true on the day a device joined — a Mac serving the database on//! 0.5.0 answered 0.1.0 for ever — because nothing ever rewrote it. Two writers//! do now, both of them in `cotton-server`: the chokepoint, when a device's own//! `x-cotton-device-app` header differs from its row, and the boot that knows//! what THIS build is, for the Mac's own row. Neither is in this crate; what//! this tool gains is that the column it already read has stopped lying.//!//! WHAT IS NOT IN THE ANSWER, and why://!//! - **last seen.** It is not in the file. `cotton_devices` deliberately has no//! `last_seen_at` column — it would be rewritten on every request by one//! machine about itself, which would put the whole set of devices' traffic on//! the wire — so it lives in each server's own `registry.db` and only that//! server's own device listings can merge it on. A tool answering from the//! file would have to invent one.//! - **serving / standing by.** Which Mac currently holds the tunnel is the//! relay election, and the election state lives in the SERVER's runtime.//! `cotton-tools` depends on `cotton-store` and `cotton-core` only — that is//! what lets the phone link it — so this tool cannot see it, and a guess//! ("it published a relay identity key, so it must be serving") would be//! wrong every time two Macs are on and one won. `relayIdentityKey` is//! reported as the plain fact it is: this device published a key it can be//! recognised by on the tunnel.//!//! Cotton note "Devices — how a machine is admitted to your database".use serde_json::{Map, Value};usecrate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult};usecrate::mcp::handlers::common::{optional_boolean, or_null, rows, text};usecrate::mcp::read_db::{Filter, Order, Query};const COLUMNS: &[&str] = &[// The row — one APPROVAL of a key. A key re-approved after a revocation// holds a row per approval (store version 41), so `deviceId` repeats and// this is what tells the rows apart."id","device_id","name","platform","app_version","relay_identity_key","approved_at","approved_by_device","revoked_at","revoked_by_device","revoked_reason",// Version 14 — the reading `cotton_machines` used to carry, on the row that// already says which Mac this is."cpu_count","mem_total_gb","mem_free_pct","load1","disk_free_gb","sessions_running","sessions_cap","build_lock_held",// Version 24 — what this Mac has promised and what it may promise. The// budget is what admits a job now; the lock above is one of the costs// inside it rather than the throttle it used to be."mem_committed_gb","mem_budget_gb","session_peak_gb","session_peak_samples",// Version 27 — where this Mac stands in the SERVING ORDER the person wrote// down: lower is preferred, NULL is last."serving_rank","agents","account_ids",// Which repositories this Mac can start a session in (v37)."repos","host_version","sampled_at",// What the machine IS (v39) — its chip, its OS version, the size of the// volume its data directory is on. Constants, recorded once; NULL until// the Mac has said."chip","os_version","disk_total_gb",// Why this Mac is holding a downloaded update (v40) — the app's own// sentence, NULL while it holds none."update_hold",// What iOS last told a phone about Cotton's notifications (v126), so its// row can say when they are off."push_authorization",// What the serving Mac's Anthropic work is holding and spent today, and// the owner's daily cap for it (v134)."ai_holds","ai_spend","ai_day_cap_usd",// What a device said of itself with its last exchange (v135)."reported_state",// Where this Mac's copy stands (v132): the schema its file is at and the// moment the copy was last level with the Mac that serves — what "Serve// from this Mac" is offered on and what its sheet says."schema_version","copy_as_of",];/// A number as it was read, or `null`. NEVER a zero: a Mac nobody has sampled/// has no numbers, and drawing 0% free would say it is out of memory.fn number(row: &Map<String, Value>, column: &str) -> Value { row.get(column).cloned().unwrap_or(Value::Null)}/// A JSON object column, parsed. The column is `NOT NULL DEFAULT '{}'` and/// CHECKed to be an object, so this is the decoder and not a fallback.fn object(row: &Map<String, Value>, column: &str) -> Value {match row.get(column) {Some(Value::String(raw)) => serde_json::from_str::<Value>(raw) .ok() .filter(Value::is_object) .unwrap_or_else(|| Value::Object(Map::new())),Some(value @ Value::Object(_)) => value.clone(), _ => Value::Object(Map::new()), }}/// Every device approved to open this database, newest approval first.////// A revoked device is IN the answer by default and says so. Leaving it out/// would make "this key is cut off" indistinguishable from "this key was never/// here", and the two have opposite answers to the only question anybody asks/// of this list.pubfn list_devices(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let include_revoked = optional_boolean(args, "includeRevoked")?.unwrap_or(true);letmut query = Query::on("cotton_devices") .columns(COLUMNS) .order_by("approved_at", Order::Desc);if !include_revoked { query = query.filter(Filter::IsNull("revoked_at".to_string())); }let out: Vec<Value> = rows(ctx, &query)? .iter() .map(|row| {letmut one = Map::new(); one.insert("id".to_string(), or_null(text(row, "id"))); one.insert("deviceId".to_string(), or_null(text(row, "device_id"))); one.insert("name".to_string(), or_null(text(row, "name"))); one.insert("platform".to_string(), or_null(text(row, "platform"))); one.insert("appVersion".to_string(), or_null(text(row, "app_version"))); one.insert("pushAuthorization".to_string(), or_null(text(row, "push_authorization")));// The plain fact, not an election: a Mac publishes a key it can be// recognised by on the tunnel, and a phone has none. one.insert("publishesRelayIdentity".to_string(),Value::Bool(text(row, "relay_identity_key").is_some()), ); one.insert("approvedAt".to_string(), or_null(text(row, "approved_at"))); one.insert("approvedBy".to_string(), or_null(text(row, "approved_by_device")), ); one.insert("revokedAt".to_string(), or_null(text(row, "revoked_at"))); one.insert("revokedBy".to_string(), or_null(text(row, "revoked_by_device")), ); one.insert("revokedReason".to_string(), or_null(text(row, "revoked_reason")), );// What this Mac is like right now, as its session host last// reported (version 14). Every number is null until the first// sample lands — `sampledAt` is what says how old the rest is, and// a Mac that has never reported reads as nulls rather than zeros. one.insert("cpuCount".to_string(), number(row, "cpu_count")); one.insert("memTotalGb".to_string(), number(row, "mem_total_gb")); one.insert("memFreePct".to_string(), number(row, "mem_free_pct")); one.insert("load1".to_string(), number(row, "load1")); one.insert("diskFreeGb".to_string(), number(row, "disk_free_gb")); one.insert("sessionsRunning".to_string(), number(row, "sessions_running"), ); one.insert("sessionsCap".to_string(), number(row, "sessions_cap")); one.insert("buildLockHeld".to_string(), number(row, "build_lock_held"));// The budget (version 24). Null until a helper that measures has// reported: a Mac showing "committed 0 of 0 GB" would read as one// with nothing free, which is the opposite of what an unmeasured// Mac means. one.insert("memCommittedGb".to_string(), number(row, "mem_committed_gb"), ); one.insert("memBudgetGb".to_string(), number(row, "mem_budget_gb")); one.insert("sessionPeakGb".to_string(), number(row, "session_peak_gb")); one.insert("sessionPeakSamples".to_string(), number(row, "session_peak_samples"), );// The serving order (version 27) — the person's own column: lower// is preferred and `null` is last, which is what a Mac nobody has// placed answers. It is STILL NOT an election: what this says is// where the person would like the household's name to be answered// from, and which line the relay actually holds remains the// server's runtime and no column in this file. one.insert("servingRank".to_string(), number(row, "serving_rank")); one.insert("schemaVersion".to_string(), number(row, "schema_version")); one.insert("copyAsOf".to_string(), or_null(text(row, "copy_as_of")));// JSON objects keyed by the agent — `{"claude-code": "2.1.274"}`// and `{"claude-code": "<account id>"}`. An absent key is "not// installed" / "not signed in", never a null column. one.insert("agents".to_string(), object(row, "agents")); one.insert("accountIds".to_string(), object(row, "account_ids"));// `{"<repository url>": "present" | "clonable"}`, or NULL for a Mac// that has never said — which is not the same as `{}`, a Mac that// looked and holds none, so the null is kept. one.insert("repos".to_string(),match row.get("repos") {None | Some(Value::Null) => Value::Null,Some(_) => object(row, "repos"), }, ); one.insert("hostVersion".to_string(), or_null(text(row, "host_version"))); one.insert("sampledAt".to_string(), or_null(text(row, "sampled_at")));// What the machine IS (version 39): the chip's name, the OS// version, the data volume's size. Null until the Mac has said —// and unlike the numbers above, not dated by `sampledAt`: a// constant is as current as the day it was recorded. one.insert("chip".to_string(), or_null(text(row, "chip"))); one.insert("osVersion".to_string(), or_null(text(row, "os_version"))); one.insert("diskTotalGb".to_string(), number(row, "disk_total_gb"));// Why this Mac has not installed the update it holds (version// 40): the sentence `UpdateGate` wrote, or null while it holds// none — so a device page can say what a Mac that is behind is// waiting for, rather than only that it is behind. one.insert("updateHold".to_string(), or_null(text(row, "update_hold")));// What the serving Mac's server says of its Anthropic work// (version 134): a typed hold, today's spend as// `{day, totalUsd, capUsd, byWork}`, and the owner's daily cap// — null while unset, which is the $5 default.// The owner's order "make this Mac a runner" and the serving// Mac's answer to it, with the row's scope (`device::runner_steps`). one.insert("scope".to_string(), or_null(text(row, "scope"))); one.insert("runnerOrderedAt".to_string(), or_null(text(row, "runner_ordered_at"))); one.insert("runnerConfirmedAt".to_string(), or_null(text(row, "runner_confirmed_at"))); one.insert("runnerProblem".to_string(), or_null(text(row, "runner_problem"))); one.insert("aiHolds".to_string(), text(row, "ai_holds") .and_then(|said| cotton_core::device::ai_hold::AiHold::from_json(&said) .and_then(|hold| serde_json::to_value(hold).ok())) .unwrap_or(Value::Null), ); one.insert("aiSpend".to_string(),match row.get("ai_spend") {None | Some(Value::Null) => Value::Null,Some(_) => object(row, "ai_spend"), }, ); one.insert("aiDayCapUsd".to_string(), number(row, "ai_day_cap_usd"));// What the device said of itself with its last exchange (version// 135): build, schema, last answer, unsent, databases listed, the// open card's problem and a copy in progress — null until it has.let reported = match row.get("reported_state") {None | Some(Value::Null) => Value::Null,Some(_) => object(row, "reported_state"), }; one.insert("reportedState".to_string(), reported);Value::Object(one) }) .collect();letmut answer = Map::new(); answer.insert("devices".to_string(), Value::Array(out));Ok(Value::Object(answer))}/// The tools this group implements.pubfn handlers() -> HandlerGroup { &[ ("archive_database", database_server_required), ("list_databases", database_server_required), ("list_devices", list_devices),// What a phone keeps: the rules on its device row (`keep_rules`). ("list_keep_rules", crate::mcp::handlers::keep_rules::list_keep_rules), ("set_keep_rule", crate::mcp::handlers::keep_rules::set_keep_rule), ("clear_keep_rule", crate::mcp::handlers::keep_rules::clear_keep_rule),// Who may hold a record: the owner's only-you hold and release (`audience`). ("set_audience", crate::mcp::handlers::audience::set_audience), ]}fn database_server_required(_: &mutCtx<'_>, _: &Map<String, Value>) -> ToolResult {Err(crate::mcp::protocol::ToolFailure::new("Ask the Mac serving your Personal database"))}