//! `records.head {table}` — what a list says above its slips. //! //! A LIST WHOSE LAST WRITE WAS REFUSED SAYS SO AT ITS HEAD (architect, //! 14 Oct 2026). The MCP admission files one open Feedback row per refused //! cause with a typed `context.refused_write.table`; a list over that table //! reads the open ones, newest first, and draws the ONE line the core resolves //! from them (`cotton_core::rules::refused_write`), worded by the `feedback` //! definition. Resolving the row — by hand, or the server on the writer's next //! accepted write — takes the line away. //! //! The answer is `{lines: [{reason, since, line}]}`: the typed readings and //! the definition's line over them, at most one today. The rows are read in //! the database the list is drawn in; the server files them in the owner's //! personal database, where the samplers' tables (Machines, Quotas) live. use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use cotton_core::rules::refused_write::{head_line, newest, RefusedSample}; use crate::methods::MethodError; use crate::shell::client::ClientController; /// The open refused writes for `table`, as typed readings. pub fn refused_samples( driver: &cotton_store::driver::Driver, workspace_id: &str, table: &str, ) -> Result, String> { let rows = driver .all( "SELECT json_extract(context, '$.refused_write.reason') AS reason, coalesce(json_extract(context, '$.refused_write.first_failed_at'), created_at) AS since FROM cotton_feedback WHERE workspace_id = ? AND resolved_at IS NULL AND status = 'open' AND json_extract(context, '$.refused_write.table') = ?", &[SqlValue::Text(workspace_id.to_string()), SqlValue::Text(table.to_string())], ) .map_err(|error| error.to_string())?; Ok(rows .iter() .filter_map(|row| { Some(RefusedSample { reason: row.text("reason")?.to_string(), since: row.text("since")?.to_string() }) }) .collect()) } /// Answer `records.head`. pub fn read(client: &ClientController, request: &Value) -> Result { let table = request["table"] .as_str() .map(str::trim) .filter(|table| !table.is_empty()) .ok_or_else(|| MethodError::new("bad_request", "records.head takes the table whose list is drawn"))?; let clock = cotton_core::device::words::Clock::in_zone( client.clock().now().timestamp_millis(), client.time_zone().unwrap_or("UTC"), ); client .with_file(|file| { let Some(sample) = newest(refused_samples(file.driver, file.workspace_id, table)?) else { return Ok(json!({ "lines": [] })); }; let feedback = cotton_tools::definitions::table_definitions_from_driver(file.driver, file.workspace_id) .map_err(|failure| failure.to_string())? .definitions .into_iter() .find(|definition| definition.id == "feedback"); let line = feedback.as_ref().and_then(|definition| head_line(definition, &sample, &clock)); Ok(json!({ "lines": [{ "reason": sample.reason, "since": sample.since, "line": line }] })) }) .map_err(|reason| MethodError::new("unreadable", reason)) }