//! THE LEDGER'S ROWS: what each Mac holds, as the owner reads it on the phone.//!//! The Disk tool is an ordinary package (no engine, no Swift, rows in its//! own made table `cotton_disk_claim`), carried here and installed into the file the Mac writes//! (`tool_packages::install_package`, the Domains tool's way). Each Mac writes//! only its own rows, keyed by `device_id` and `claim_id`; the owner's Drop//! sets `dropped`, and the Mac whose row it is reads that at its next pass//! ([`drops`]) and releases the claim by its OWN spool's path//! (`super::ledger`), never by anything the row says.//!//! What a session left loose at the top of home is told to the owner as//! Feedback too ([`loose_notes`]): one note per entry, filed by the Mac app's//! once-only writer, since a pass lists each entry only in the pass that//! claims it.use std::collections::{BTreeMap, BTreeSet};use cotton_core::definitions::{package::ToolPackage, TableDefinition, ToolDefinition};use cotton_store::Driver;use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::tables::{create_produced_record, delete_record, made_table, stored_from_row, update_produced_record};use cotton_tools::mcp::protocol::ToolFailure;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};usesuper::ledger::{claim_id, Claim, PassReport, SessionFate};pubconst TOOL_ID: &str = "disk";pubconst TABLE: &str = "disk_claim";pubconst HELD: &str = "Held";pubconst RELEASED: &str = "Released";/// A Released row is kept this long, so the owner sees what went and why.pubconst RELEASED_KEPT_DAYS: i64 = 7;/// The package, decoded from the JSON beside this file.#[must_use]pubfn package() -> ToolPackage {let tool: ToolDefinition = serde_json::from_str(include_str!("ledger_package/manifest.json")).expect("the Disk manifest parses");let table: TableDefinition = serde_json::from_str(include_str!("ledger_package/tables/disk_claim.json")).expect("disk_claim parses");// The card's picture, carried as the package's own `pictures/<sha256>.png`.let pictures = [(String::from("8ecb7aaab70615c06304e2c8194ae25371831c1dc1820a38102ab9281da89d52.png"), include_bytes!("ledger_package/pictures/8ecb7aaab70615c06304e2c8194ae25371831c1dc1820a38102ab9281da89d52.png") .to_vec(), )] .into_iter() .collect();ToolPackage { board: None, tool, tables: vec![table], pictures, samples: Default::default() }}/// Bring the Disk tool this database holds to this build's shape; `None`/// when it holds none. A tool is a record (72nd amendment, 21 Oct 2026): the/// Mac never installs it, so a Disk the person removed — its table kept,/// undrawn — stays removed, and a pass then writes no row.pubfn ensure_installed(ctx: &mutCtx<'_>) -> Result<Option<bool>, ToolFailure> {let tool = cotton_tools::mcp::handlers::tool_packages::live_tool_definitions(ctx)? .into_iter().find(|tool| tool.id == TOOL_ID);letSome(tool) = tool else { returnOk(None) };let present = cotton_tools::definitions::definition_rows(ctx, Some(TABLE))?.len() == 1;letmut package = package();let current = if present {Some(cotton_tools::mcp::handlers::tables::definition(ctx, TABLE)?) } else { None };ifletSome(current) = ¤t { package.tables[0] = upgraded_table(current, &package.tables[0])?; }// At this build's shape: a Disk tool installed by an older build (no// picture, another stock) is upgraded in place. package.tool = tool;if current.as_ref().is_some_and(|current| current == &package.tables[0]) {returnOk(Some(false)); } cotton_tools::mcp::handlers::tool_packages::install_package(ctx, &package, cotton_tools::mcp::handlers::tool_packages::Door::Cotton, false)?;Ok(Some(true))}/// The last package default is kept beside its resolved table, so an upgrade/// can distinguish the owner's edits from defaults supplied by an older build.fn upgraded_table(current: &TableDefinition, shipped: &TableDefinition) -> Result<TableDefinition, ToolFailure> {const BASE: &str = "cotton_package_base";let refused = || ToolFailure::new("Disk could not be updated without losing your definition edits.");let previous = match current.unknown.get(BASE) {Some(value) => TableDefinition::from_json(&value.to_string()).map_err(|_| refused())?,None => TableDefinition::from_json(include_str!("ledger_package/base/disk_claim.json")).expect("the first Disk package base parses"), };letmut raw = serde_json::to_value(current).expect("a table serializes");for key in [BASE, "edited", "base_hash"] { raw.as_object_mut().unwrap().remove(key); }let previous_raw = serde_json::to_value(&previous).expect("a package base serializes");let roots: Vec<String> = previous_raw.as_object().unwrap().keys().chain(raw.as_object().unwrap().keys()) .filter(|key| !matches!(key.as_str(), BASE | "edited" | "base_hash") && !current.unknown.contains_key(key.as_str())) .cloned().collect::<BTreeSet<_>>().into_iter().collect();let edits = cotton_core::definitions::leaf_edit_paths(&previous, &raw, &roots);letmut carrying = shipped.clone();for column in ¤t.columns {if previous.column(&column.key).is_none() && carrying.column(&column.key).is_none() { carrying.columns.push(column.clone()); } }let (mut resolved, dropped) = cotton_core::definitions::with_edits_reported(&carrying, &raw, &edits);if !dropped.is_empty() { returnErr(refused()); }for (key, value) in ¤t.unknown {if key != BASE { resolved.unknown.insert(key.clone(), value.clone()); } } resolved.unknown.insert(BASE.into(), serde_json::to_value(shipped).expect("a package default serializes"));Ok(resolved)}/// The claim ids the owner asked `device_id` to drop and that are still held.pubfn drops(db: &Driver, workspace_id: &str, device_id: &str) -> Result<BTreeSet<String>, String> {if !holds_table(db).map_err(|error| error.to_string())? {returnOk(BTreeSet::new()); }let rows = db .all( &format!("SELECT claim_id AS claim FROM {} \ WHERE workspace_id = ? AND deleted_at IS NULL \ AND device_id = ? AND dropped = 1 AND state = ?", made_table(TABLE) ), &[SqlValue::Text(workspace_id.into()),SqlValue::Text(device_id.into()),SqlValue::Text(HELD.into()), ], ) .map_err(|error| error.to_string())?;Ok(rows.iter().filter_map(|row| row.text("claim")).map(str::to_string).collect())}/// Whether this file holds the Disk tool's own table yet: a made table's/// records are rows of `cotton_<id>` (`tables::made_table`), made when its/// definition lands.fn holds_table(db: &Driver) -> cotton_store::Result<bool> {Ok(db .get("SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(made_table(TABLE))], )? .is_some())}/// What became of the session `external_id` (its tool's own id), as this/// file's Sessions say: no row is Unknown, and Unknown keeps a claim.pubfn session_fate(db: &Driver, external_id: &str) -> SessionFate {let row = db .get("SELECT state, ended_at FROM cotton_sessions WHERE external_id = ? OR id = ? \ ORDER BY last_active_at DESC LIMIT 1", &[SqlValue::Text(external_id.into()), SqlValue::Text(external_id.into())], ) .ok() .flatten();match row {None => SessionFate::Unknown,Some(row) if row.text("ended_at").is_some() => SessionFate::Ended,Some(row) if matches!(row.text("state"), Some("ended" | "failed" | "withdrawn")) => SessionFate::Ended,Some(_) => SessionFate::Live, }}/// One Mac's rows, as its last pass left them.pubstructMirror<'a> {pub device_id: &'a str,pub machine: &'a str,pub home: &'a std::path::Path,pub now: chrono::DateTime<chrono::Utc>,}/// Write `report` as this Mac's rows: every held claim, every release with/// why, a refused drop's reason, and the Released rows past their week gone./// Only fields that changed are written, so a quiet pass syncs nothing.pubfn mirror(ctx: &mutCtx<'_>, mirror: &Mirror<'_>, report: &PassReport) -> Result<(), ToolFailure> {if ensure_installed(ctx)?.is_none() {returnOk(()); }let existing = rows_of(ctx, mirror.device_id)?;let stamp = mirror.now.format("%Y-%m-%d").to_string();for (id, data) in held_rows(mirror, report) { write(ctx, existing.get(&id), data)?; }for (id, data) in released_rows(mirror, report) { write(ctx, existing.get(&id), data)?; }// A held row whose claim is no longer on this Mac's spool: its path went// by hand. The row says so rather than vanishing.for id in &report.vanished {ifletSome(row) = existing.get(id).filter(|row| row.state.as_deref() == Some(HELD)) {letmut data = Map::new(); data.insert("state".into(), Value::from(RELEASED)); data.insert("released_at".into(), Value::from(stamp.clone())); data.insert("why".into(), Value::from("it was removed by hand")); write(ctx, Some(row), data)?; } }// An adoption the scan no longer makes was never a thing of its own (a// folder now read as a series or as a cache's parts): its row goes.for id in &report.forgotten {ifletSome(row) = existing.get(id) {letmut args = Map::new(); args.insert("table".into(), Value::from(TABLE)); args.insert("id".into(), Value::from(row.record_id.clone())); delete_record(ctx, &args)?; } }let week_ago = mirror.now - chrono::Duration::days(RELEASED_KEPT_DAYS);for row in existing.values() {let old = row.state.as_deref() == Some(RELEASED) && row .released_at .as_deref() .and_then(|at| chrono::NaiveDate::parse_from_str(at, "%Y-%m-%d").ok()) .is_some_and(|at| at < week_ago.date_naive());if old {letmut args = Map::new(); args.insert("table".into(), Value::from(TABLE)); args.insert("id".into(), Value::from(row.record_id.clone())); delete_record(ctx, &args)?; } }Ok(())}/// Every claim a pass left standing, as its row: held, with why a drop was/// refused or when it goes. Keyed by claim id.#[must_use]pubfn held_rows(mirror: &Mirror<'_>, report: &PassReport) -> Vec<(String, Map<String, Value>)> { report .claims .iter() .map(|(id, claim)| {letmut data = held_row(claim, mirror);let why = ifletSome((_, why)) = report.refused.iter().find(|(refused, _)| refused == id) {Some(format!("Not dropped: {why}")) } elseif report.drops_pending.contains(id) {Some("Drops at the next pass, in a few minutes \u{2014} switch Drop off to keep it".to_string()) } else {None }; data.insert("why".into(), why.map_or(Value::Null, Value::from)); (id.clone(), data) }) .collect()}/// Every claim a pass released, as its row: Released today, and why.#[must_use]pubfn released_rows(mirror: &Mirror<'_>, report: &PassReport) -> Vec<(String, Map<String, Value>)> {let stamp = mirror.now.format("%Y-%m-%d").to_string(); report .released .iter() .map(|(claim, reason)| {letmut data = held_row(claim, mirror); data.insert("state".into(), Value::from(RELEASED)); data.insert("released_at".into(), Value::from(stamp.clone())); data.insert("why".into(), Value::from(reason.words())); (claim.id(), data) }) .collect()}/// One Feedback note a pass owes the owner: `key` is what the writer derives/// the row's id from, so filing it twice writes one row.#[derive(Debug, Clone, PartialEq)]pubstructLooseNote {pub key: String,pub text: String,pub context: Map<String, Value>,}/// One note per entry a session left loose at the top of home/// ([`PassReport::loose`]): "a session wrote <name> into ~ on <machine>",/// keyed by this Mac, the path and when it was claimed, so the same name left/// again after its claim went is told again.#[must_use]pubfn loose_notes(mirror: &Mirror<'_>, report: &PassReport) -> Vec<LooseNote> { report .loose .iter() .map(|path| {let name = path.file_name().map_or_else(|| path.display().to_string(), |name| name.to_string_lossy().into_owned());let id = claim_id(path);let claimed = report.claims.get(&id).map(|claim| claim.created_at.clone()).unwrap_or_default();let context = json!({"source": "ledger","machine": mirror.machine,"path": format!("~/{name}"),"claim_id": id, });LooseNote { key: format!("ledger-loose:{}:{}:{claimed}", mirror.device_id, path.display()), text: format!("a session wrote {name} into ~ on {}", mirror.machine), context: context.as_object().cloned().unwrap_or_default(), } }) .collect()}/// A held claim's row.fn held_row(claim: &Claim, mirror: &Mirror<'_>) -> Map<String, Value> {let (release_rule, idle_hours, keep_last) = matchsuper::ledger::Rule::parse(&claim.rule) {Some(super::ledger::Rule::SessionEnds) => (Some("session_ends"), None, None),Some(super::ledger::Rule::BudgetLru) => (Some("budget_lru"), None, None),Some(super::ledger::Rule::OwnerOnly) => (Some("owner_only"), None, None),Some(super::ledger::Rule::IdleHours(hours)) => (Some("idle_hours"), Some(hours), None),Some(super::ledger::Rule::KeepLast(count)) => (Some("keep_last"), None, Some(count)),None => (None, None, None), };let shown = claim .path .strip_prefix(mirror.home) .map(|rest| format!("~/{}", rest.display())) .unwrap_or_else(|_| claim.path.display().to_string());let name = claim.path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_else(|| shown.clone());let size = claim.bytes.map(|bytes| (bytes as f64 / 1e8).round() / 10.0);let data = json!({"name": name,"machine": mirror.machine,"kind": claim.kind.word(),"lane": claim.lane,"size_gb": size,"size_bytes": claim.bytes,"touched_at": claim.touched_at.as_deref().map(day),"rule": claim.rule,"release_rule": release_rule,"idle_hours": idle_hours,"keep_last": keep_last,"state": HELD,"path": shown,"session": claim.session,"device_id": mirror.device_id,"claim_id": claim.id(), }); data.as_object().cloned().unwrap_or_default()}/// The day of a moment as the spool spells it (`2026-10-09T…` → `2026-10-09`),/// the shape a date column takes.fn day(at: &str) -> String { at.chars().take(10).collect()}/// One existing row: its record id, what it holds, and the two fields read.structRow { record_id: String, data: Map<String, Value>, state: Option<String>, released_at: Option<String>,}fn rows_of(ctx: &Ctx<'_>, device_id: &str) -> Result<BTreeMap<String, Row>, ToolFailure> {let fail = |error: cotton_store::StoreError| ToolFailure::new(error.to_string());if !holds_table(ctx.db()).map_err(fail)? {returnOk(BTreeMap::new()); }let definition = cotton_tools::mcp::handlers::tables::definition(ctx, TABLE)?;let rows = ctx .db() .all( &format!("SELECT * FROM {} WHERE workspace_id = ? AND deleted_at IS NULL AND device_id = ?", made_table(TABLE) ), &[SqlValue::Text(ctx.workspace_id.into()), SqlValue::Text(device_id.into())], ) .map_err(fail)?;Ok(rows .iter() .filter_map(|row| {let stored = stored_from_row(&definition, row);let data: Map<String, Value> = stored.data;let claim = data.get("claim_id")?.as_str()?.to_string();Some(( claim,Row { record_id: stored.id, state: data.get("state").and_then(Value::as_str).map(str::to_string), released_at: data.get("released_at").and_then(Value::as_str).map(str::to_string), data, }, )) }) .collect())}/// Create the row, or patch only what changed. A row the owner asked to drop/// keeps `dropped` until it is Released.fn write(ctx: &mutCtx<'_>, existing: Option<&Row>, data: Map<String, Value>) -> Result<(), ToolFailure> {letmut args = Map::new(); args.insert("table".into(), Value::from(TABLE));match existing {None => {letmut data = data; data.entry("dropped").or_insert(Value::Bool(false)); args.insert("data".into(), Value::Object(data)); create_produced_record(ctx, &args)?; }Some(row) => {let patch: Map<String, Value> = data .into_iter() .filter(|(key, value)| row.data.get(key).unwrap_or(&Value::Null) != value) .collect();if patch.is_empty() {returnOk(()); } args.insert("id".into(), Value::from(row.record_id.clone())); args.insert("patch".into(), Value::Object(patch));// A value the row already holds in the table's own form (a number// it stores whole) is no change: the pass goes on to the next row// instead of ending with every later row unwritten.match update_produced_record(ctx, &args) {Err(failure) if failure.message() == cotton_core::records::RecordError::NothingToChange.to_string() => {} other => { other?; } } } }Ok(())}#[cfg(test)]mod reading_tests {usesuper::*;/// RULE: Disk definition upgrades carry owner edits forward while later package defaults still advance; a quiet pass does not rewrite the same definition. #[test]fn disk_definition_upgrades_preserve_owner_edits_without_pinning_package_defaults() {let base = TableDefinition::from_json(include_str!("ledger_package/base/disk_claim.json")).unwrap();letmut owner = serde_json::to_value(&base).unwrap(); owner["name"] = json!("Invented owner name");for column in owner["columns"].as_array_mut().unwrap() {if column["key"] == "size_gb" { column["name"] = json!("Invented size label"); } } owner["columns"].as_array_mut().unwrap().push(json!({"key":"owner_note", "name":"Owner note", "type":"text"}));let owner = TableDefinition::from_json(&owner.to_string()).unwrap();let shipped = package().tables.remove(0);let upgraded = upgraded_table(&owner, &shipped).unwrap(); assert_eq!(upgraded.name, owner.name); assert_eq!(upgraded.column("owner_note"), owner.column("owner_note")); assert_eq!(upgraded.column("size_gb").unwrap().name, owner.column("size_gb").unwrap().name); assert_eq!(upgraded.column("size_gb").unwrap().units, shipped.column("size_gb").unwrap().units); assert_eq!(upgraded_table(&upgraded, &shipped).unwrap(), upgraded);letmut later = shipped.clone(); later.plural = "Invented later package plural".into();let advanced = upgraded_table(&upgraded, &later).unwrap(); assert_eq!(advanced.plural, later.plural); assert_eq!(advanced.name, owner.name); }/// RULE: An unreadable remembered package base refuses an upgrade instead of guessing which values belong to the owner. #[test]fn an_unreadable_disk_package_base_never_overwrites_owner_edits() {let shipped = package().tables.remove(0);letmut held = shipped.clone(); held.unknown.insert("cotton_package_base".into(), json!("not a definition")); assert!(upgraded_table(&held, &shipped).is_err()); }/// RULE: A Disk row carries typed release facts and size units; raw spool paths and serialized release rules remain machinery, never page readings. #[test]fn disk_rows_resolve_rules_and_sizes_without_exposing_spool_paths() {let now = chrono::DateTime::parse_from_rfc3339("2026-10-01T12:00:00Z").unwrap().with_timezone(&chrono::Utc);let mirror = Mirror { device_id:"invented-device", machine:"Invented Mac", home:std::path::Path::new("/invented"), now };let definition = package().tables.remove(0);for (rule, key, limit) in [("owner_only", "owner_only", None), ("idle_hours:72", "idle_hours", Some(("idle_hours", 72))), ("keep_last:3", "keep_last", Some(("keep_last", 3)))] {let claim: Claim = serde_json::from_value(json!({"path":"/invented/cache/lane", "kind":"scratch", "lane":"invented", "created_at":"2026-10-01T12:00:00Z", "rule":rule, "bytes":2_300_000_000u64})).unwrap();let data = held_row(&claim, &mirror); assert_eq!(data["release_rule"], key);ifletSome((column, value)) = limit { assert_eq!(data[column], value); }let column = definition.column("release_rule").unwrap();let words = cotton_core::records::page::fact_words(&definition, column, &data["release_rule"], &data, None, None, cotton_core::records::page::Words::shipped()).unwrap(); assert_ne!(words, rule); assert_eq!(data["size_bytes"], 2_300_000_000u64); assert_eq!(definition.column("size_bytes").unwrap().column_type, cotton_core::definitions::ColumnType::Bytes); }for section in &definition.page { assert!(!section.columns().iter().any(|key| matches!(key.as_str(), "path" | "rule"))); } }}