//! `read.record` — one record's own columns, and the CONVERSATION on it.//!//! ## Why this read grew a second half//!//! *"A comment on an answer note is the whole re-ask gesture"*//! (`docs/tools/assistant.md`). An assistant's answer note is an ORDINARY note//! — `author_kind = 'agent'`, `managed_by IS NULL` — so the note screen was//! where the gesture had to live, and the note screen had no comment surface at//! all: the port gap `[managed-note-has-no-comment-thread]` said so in as many//! words, *"no comments read and no comment verb on this phone"*. The verb was//! already there (`create_comment` / `resolve_comment` go over the ordinary//! write rail, and the memory and meeting screens both use them). The READ is//! what was missing, and this is it.//!//! ## Why it is composed rather than a second read//!//! **A screen has exactly one read** (`reads_tests::no_two_reads_share_a_name_or_a_screen`),//! so the thread cannot arrive as a second call racing the first to paint the//! same page. And `get_record`'s own shape must not grow a phone screen's needs//! — it is an assistant's tool, and `reads.rs` says so beside this very entry.//! [`ReadSource::Composed`](super::reads::ReadSource::Composed)'s own taxonomy//! names this exact case: *"a page drawing a meeting AND its transcript AND its//! comment threads is one `Controller` calling three handlers"*. So the tool//! answers the record, unchanged and uncopied, and the join this file adds is//! the one no tool asks for.//!//! ## Threads, not a flat list//!//! `list_comments` answers a flat list shaped for an assistant — a rendered//! author string and a resolved boolean. A screen needs three things that shape//! cannot express: which rows are REPLIES to which, whether a reply came from//! an agent or from the owner, and WHEN a thread was resolved. That is the same//! reason `reads_work::comment_threads` reads the table directly for a meeting,//! and this is that function with the kind as an argument rather than baked in//! — one shape for every screen that draws a conversation.//!//! ## The whole conversation, and no ceiling//!//! **Every list read states its ceiling out loud** (`swift-ios-ffi.md`), and//! this one answers the record's comments WHOLE, on purpose. A record's//! conversation is a handful of rows — the re-ask gesture is one question and//! one answer, repeated a few times on a note somebody is still thinking about//! — and a page that stopped early would hide the very reply the person opened//! the screen for, at the bottom, where a "load more" cannot be tapped from a//! notification. The server's own reader of the same table caps at 40 because//! it is filling a model's context window and pays for every row; a screen is//! not. If a cap is ever wanted here it is a decision with a ledger row, not a//! number somebody adds to the SQL.//!//! ## What it does NOT do//!//! It answers `threads` for EVERY kind `read.record` serves, and asks no//! question about which kinds deserve one: `cotton_comments.record_kind` is the//! authority on where a comment may be written, the tool refuses a kind it does//! not admit, and a read that second-guessed it would be a second opinion about//! the same column. A record nobody has commented on answers `[]`, which is not//! a special case — it is the empty conversation.use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};use cotton_store::driver::Driver;use cotton_tools::mcp::dispatch::Ctx;usesuper::traffic::tool;/// The record, plus its conversation.////// The arguments are `get_record`'s own — `kind` and `id` — and they are passed/// through untouched, so the tool's validation is the app's validation for/// free. They are READ here as well, for the join, and a missing one is left to/// the tool to refuse: two sentences for one missing argument would be one of/// them wrong.pubfn record(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> Result<Value, String> {letmut record = tool(ctx, "get_record", args)?;let kind = text(args, "kind");let id = text(args, "id");let threads = match (&kind, &id) { (Some(kind), Some(id)) => threads_on(ctx.db(), kind, id)?,// Unreachable in practice: `get_record` refuses before this line when// either is missing. Answering the empty conversation rather than// panicking keeps the shape whole for a caller that somehow gets here. _ => Value::Array(Vec::new()), };// **Merged into the record's own object, not wrapped around it.** This read// has answered `get_record`'s row at the top level since it was written,// and two screens decode it there; a `{ record, threads }` envelope would// be a shape change dressed as an addition, and every field would go// missing at once on a phone that had not shipped yet.// `get_record` answers an object or it refuses. If that ever stops being// true, the record travels unchanged rather than being replaced by a shape// this file invented.// A NOTE carries its projects too: the note sheet's kebab files it, and a// screen has one read. The link's kind is the ROW's (`note` or `journal` —// both answer to `note` here because both live in `cotton_notes`), never// the argument's, or a journal page would read as filed nowhere.let project_half = match (kind.as_deref(), id.as_deref(), &record) { (Some("note"), Some(id), Value::Object(row)) => {let row_kind = row.get("kind").and_then(Value::as_str).unwrap_or("note");Some(super::reads::day::record_projects_in( ctx.db(), ctx.workspace_id, row_kind, id, )?) } _ => None, };ifletSome(object) = record.as_object_mut() { object.insert("threads".to_string(), threads);ifletSome((projects, links)) = project_half { object.insert("projects".to_string(), Value::Array(projects)); object.insert("projectLinks".to_string(), Value::Array(links)); } }Ok(record)}fn text(args: &Map<String, Value>, key: &str) -> Option<String> { args.get(key) .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) .map(str::to_string)}/// One record's comments, as THREADS — a root and its replies, oldest first.////// A row whose `parent_id` names a root that is not on this record cannot/// happen (`create_comment` writes the parent's own kind and id), and a row/// whose parent has been erased is left out of the answer rather than promoted/// to a root: a reply drawn as if it opened the thread reads as somebody saying/// something they did not say.pubfn threads_on(db: &Driver, kind: &str, id: &str) -> Result<Value, String> {let rows = db .all("SELECT id, parent_id, body, author_kind, author_label, anchor, resolved_at, \ created_at \ FROM cotton_comments \ WHERE record_kind = ? AND record_id = ? \ ORDER BY created_at ASC, id ASC", &[SqlValue::Text(kind.to_string()),SqlValue::Text(id.to_string()), ], ) .map_err(|error| error.to_string())?;letmut threads: Vec<Value> = Vec::new();for row in &rows {if row.text("parent_id").is_some_and(|parent| !parent.is_empty()) {continue; }letSome(root_id) = row.text("id") else {continue; };let replies: Vec<Value> = rows .iter() .filter(|reply| reply.text("parent_id").is_some_and(|parent| parent == root_id)) .map(comment) .collect();letmut thread = comment(row);ifletSome(object) = thread.as_object_mut() { object.insert("replies".to_string(), Value::Array(replies)); } threads.push(thread); }Ok(Value::Array(threads))}/// One comment row, in the app's own spelling.////// `resolvedAt` is the INSTANT and not a boolean, deliberately: the screen says/// when a thread was settled, and a boolean would be the same fact with the/// only interesting half thrown away.////// `anchor` travels as the WHOLE object, for the same reason `list_comments`/// echoes it whole: a pin on a picture has no quote at all, so a screen given/// the quote alone would be told an image-anchored thread is anchored to/// nothing — and `NotePins` reads `thread["anchor"]` to place the pin it draws.fn comment(row: &cotton_store::driver::Row) -> Value { json!({"id": row.text("id"),"body": row.text("body"),"authorKind": row.text("author_kind"),"authorLabel": row.text("author_label"),"anchor": anchor_of(row),"resolvedAt": row.text("resolved_at"),"createdAt": row.text("created_at"), })}/// The stored `anchor` text as its tree.////// The column is TEXT holding JSON — this read goes through the raw driver/// rather than the tools' codec-aware reader, so the parse happens here. A row/// with no anchor, and a row whose anchor is not a JSON OBJECT, both answer/// null: a screen asks `anchor.attachment` and `anchor.quote`, and anything/// that cannot be asked those questions is the same absence to it.fn anchor_of(row: &cotton_store::driver::Row) -> Value { row.text("anchor") .and_then(|raw| serde_json::from_str::<Value>(raw).ok()) .filter(Value::is_object) .unwrap_or(Value::Null)}#[cfg(test)]#[path = "record_thread_tests.rs"]mod tests;