//! `get_record` — one record in full, by kind and id. //! //! KIND-GENERIC, and the totality is the point. The TypeScript's `switch` over //! `GetRecordKind` is exhaustive because the union is a type; here it is an //! exhaustive `match` over [`GetRecordKind`], so a kind added to the catalogue //! without an arm fails the BUILD rather than reaching an assistant as //! "unknown kind" from a validator that was supposed to have let it through. //! `catalogue_names_the_same_get_record_kinds` pins the enum against the //! generated `inputSchema` and against `surface::GET_RECORD_KINDS`, //! which is the verb grid's own copy. //! //! THREE KINDS ARE DELEGATIONS, not row reads. A memory entry, a money //! transaction and a thought each have a reader that answers more than a row — //! a memory's homes, a transaction's evidence and history, a thought's session //! messages — and each of those readers lives with its own tools. This module //! calls across rather than growing a second copy; the three one-line //! forwarders below are where that happens. //! //! Two scoping rules survive the move from the Postgres cell, and both matter: //! a bare id lookup is scoped to the workspace (the file, for an event, which //! carries no `workspace_id` and is never reached through a calendar), and `note`/`journal` are deliberately //! NOT filtered by `archived_at` — an assistant holding an id that search will //! not return has to be TOLD the note is archived, or it goes and makes a //! duplicate. use serde_json::{Map, Value}; use cotton_core::constants::SummaryKind; use crate::mcp::dispatch::{Ctx, ToolResult}; use crate::mcp::handlers::attachments::{attachments_of, NOTE}; use crate::mcp::handlers::common::{ fail, is_uuid, require_string, rows, summary_out, Valid, }; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::Query; // ── the vocabulary ────────────────────────────────────────────────────────── /// The kinds `get_record` can EXPAND. /// /// One more than the comment vocabulary in each direction: a money transaction /// and a thought expand but are never commented on, and a call is commented on /// but expands through `get_call`, which answers its provenance too. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GetRecordKind { Todo, Event, Note, Journal, Person, Document, Memory, Transaction, } impl GetRecordKind { pub const fn as_str(self) -> &'static str { match self { GetRecordKind::Todo => "todo", GetRecordKind::Event => "event", GetRecordKind::Note => "note", GetRecordKind::Journal => "journal", GetRecordKind::Person => "person", GetRecordKind::Document => "document", GetRecordKind::Memory => "memory", GetRecordKind::Transaction => "transaction", } } pub fn parse(value: &str) -> Option { GET_RECORD_KINDS .into_iter() .find(|kind| kind.as_str() == value) } } /// In the TypeScript's declared order — the refusal sentence prints it. pub const GET_RECORD_KINDS: [GetRecordKind; 8] = [ GetRecordKind::Todo, GetRecordKind::Event, GetRecordKind::Note, GetRecordKind::Journal, GetRecordKind::Person, GetRecordKind::Document, GetRecordKind::Memory, GetRecordKind::Transaction, ]; // ── the arguments ─────────────────────────────────────────────────────────── #[derive(Debug, Clone)] pub struct GetRecordArgs { pub kind: GetRecordKind, pub id: String, } /// `validateGetRecord`. pub fn validate_get_record(args: &Map) -> Valid { let named = args.get("kind").and_then(Value::as_str).unwrap_or_default(); let Some(kind) = GetRecordKind::parse(named) else { return fail(format!( "kind is required. Allowed: {}", GET_RECORD_KINDS .iter() .map(|kind| kind.as_str()) .collect::>() .join(", ") )); }; let Some(id) = require_string(args, "id").filter(|id| is_uuid(id) || kind == GetRecordKind::Transaction && crate::mcp::handlers::money::occurrences::identity(id).is_some()) else { return fail("id must be a uuid"); }; Ok(GetRecordArgs { kind, id }) } // ── the columns each kind answers with ────────────────────────────────────── const TODO_COLUMNS: &[&str] = &[ "id", "title", "notes", "status", "due_at", "priority", "completed_at", // A todo in the Bin is still read by its id, saying it is there. "trashed_at", "created_at", ]; /// The series fields come too: an assistant holding an event id has no other /// way to learn that this row is one occurrence standing in for another /// (`series_id` + `original_starts_at`), which instants the series skips /// (`exdates`), or that the row is on its way out (`trashed_at`) and every list /// has stopped showing it. const EVENT_COLUMNS: &[&str] = &[ "id", "title", "notes", "starts_at", "ends_at", "all_day", "location", "rrule", "exdates", "series_id", "original_starts_at", "trashed_at", "created_at", ]; /// `project_id` is on the row (`ddl.v1.ts:930`) and in the answer /// (`note/transforms.ts:14` writes `projectId`), and it is what tells a journal /// page opened inside a project from the owner's own: without it the page draws /// the owner's day switcher, and picking a day walks the reader out of the /// project (`note/[id].tsx:155, 538-550` renders a static heading instead). const NOTE_COLUMNS: &[&str] = &[ "id", "title", "body", "kind", "journal_date", "project_id", "created_at", "updated_at", "archived_at", // A note in the bin is read as one: deleted, until the bin is emptied. "trashed_at", "author_kind", "author_label", "managed_by", "external_id", ]; /// Schema v15 folded `how_we_met` into the summary, which is answered as ONE /// object with its provenance rather than three loose columns — the same shape /// the two thread reads carry. const PERSON_COLUMNS: &[&str] = &[ "id", "full_name", "org", "role_title", // `emails`/`phones` are no columns since v90: filled from the handles. "city", "timezone", "summary", "summary_by", "summary_updated_at", "birth_month", "birth_day", "birth_year", ]; /// The profile and the facts, never the page text. `password` is deliberately /// absent: an assistant filing statements has no use for it, and a secret that /// has passed through a model's context is a secret that lives in a transcript. const DOCUMENT_COLUMNS: &[&str] = &[ "id", "title", "original_name", "mime", "byte_size", "doc_type", "issuer", "summary", "facts", "status", "failed_stage", "error_code", "page_count", "source", "text_extracted", "created_at", // A document in the bin is read as one: deleted, until the bin is emptied. "trashed_at", ]; // ── the three delegations ─────────────────────────────────────────────────── /// `get_record` on a memory: the whole entry, whatever its status, with its /// homes — an assistant holding an id from a comment thread needs to be told /// the entry is archived, and where it briefs when it is not. /// /// Forwarded to the memory group, which owns every other reader of this shape /// (`recall`, `remember`, `memory_update`, `brief`). Two copies of "what a /// memory entry looks like" is the drift that ends in one entry reading two /// ways depending on which tool asked. fn memory_record(ctx: &Ctx<'_>, id: &str) -> Result, ToolFailure> { into_object(crate::mcp::handlers::records_2::memory::memory_record( ctx, id, )?) } /// The transaction and thought delegations answer a `Map`; the memory one /// answers a `Value` because `recall` lists them. One unwrapping, named. fn into_object(value: Value) -> Result, ToolFailure> { match value { Value::Object(map) => Ok(map), _ => Err(ToolFailure::new( "a record delegation answered something that is not an object", )), } } /// The same base shape `list_money_transactions` returns, plus the three reads /// no list page carries: the evidence that backs it, the projects it is filed /// under, and its history. /// /// One line, so the money group owns the shape and this module owns only the /// envelope. fn money_transaction_record(ctx: &Ctx<'_>, id: &str) -> Result, ToolFailure> { super::money::money_transaction_record(ctx, id) } // ── the tool ──────────────────────────────────────────────────────────────── pub fn get_record(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { if args.contains_key("table") { let mut answer = crate::mcp::handlers::tables::get_record_by_table(ctx, args)?; // The record page in one read: what it opens on, its head, fact // slips, the lists that link to it, its views and acts. A record // that moved answers where it went, with no page. let table = args.get("table").and_then(Value::as_str).unwrap_or_default().to_string(); if let (Some(id), Some(object)) = (answer.get("id").and_then(Value::as_str).map(str::to_string), answer.as_object_mut()) { if object.contains_key("data") { let view = args.get("view").and_then(Value::as_str).map(str::to_string); match crate::mcp::handlers::tables::record_page_read::page(ctx, &table, &id, view.as_deref()) { Ok(page) => answer["page"] = page, Err(why) => answer["pageRefused"] = Value::from(why), } } } return Ok(answer); } let args = validate_get_record(args)?; // A kind is read only while a tool here draws its table: the typed // refusal, as `get_record_by_table` and the phone's read answer it. crate::mcp::handlers::tables::definition(ctx, kind_table(args.kind.as_str()))?; if let Some(moved) = crate::mcp::record_moves::lookup_moved(ctx.db(), &args.id) .map_err(|error| ToolFailure::new(error.to_string()))? { return Ok(moved); } let record: Map = match args.kind { GetRecordKind::Todo => scoped(ctx, &args, "cotton_todos", TODO_COLUMNS)?, GetRecordKind::Event => scoped(ctx, &args, "cotton_events", EVENT_COLUMNS)?, GetRecordKind::Note | GetRecordKind::Journal => { let mut note = scoped(ctx, &args, "cotton_notes", NOTE_COLUMNS)?; note.insert( "attachments".to_string(), Value::Array(attachments_of(ctx, &NOTE, &args.id)?), ); note } GetRecordKind::Person => { let person = scoped(ctx, &args, "cotton_people", PERSON_COLUMNS)?; let person = crate::mcp::handlers::records_1::people::with_handles(ctx, person)?; let summary = summary_out(ctx, SummaryKind::Person, &args.id, &person)?; let mut rest = person.clone(); rest.remove("summary"); rest.remove("summary_by"); rest.remove("summary_updated_at"); // Inserted CONDITIONALLY: `summary: undefined` still puts the key // into the object the serializer walks, and "figure or silence" // means the key is absent. if let Some(summary) = summary { rest.insert("summary".to_string(), summary); } rest } GetRecordKind::Document => scoped(ctx, &args, "cotton_documents", DOCUMENT_COLUMNS)?, GetRecordKind::Memory => memory_record(ctx, &args.id)?, GetRecordKind::Transaction => money_transaction_record(ctx, &args.id)?, }; let mut out = Map::new(); out.insert("kind".to_string(), Value::from(args.kind.as_str())); for (key, value) in record { out.insert(key, value); } Ok(Value::Object(out)) } /// The table a record kind is a row of: a journal is a note; every other /// kind, a memory among them, is its own table's id. pub fn kind_table(kind: &str) -> &str { match kind { "journal" => "note", other => other, } } // ── a note's pictures ─────────────────────────────────────────────────────── /// One row by id, scoped to this workspace. /// /// Every kind but the event is workspace-keyed, which `ReadDb` already stamps /// on every query; an event is the file's own (27 Oct 2026: the object keeps /// no calendars, so a read through one found none of its events). The /// refusal names the kind the caller asked for rather than the table, because /// that is the word they typed. fn scoped( ctx: &Ctx<'_>, args: &GetRecordArgs, table: &str, columns: &[&str], ) -> Result, ToolFailure> { let query = Query::on(table).columns(columns).eq("id", args.id.clone()); rows(ctx, &query)? .into_iter() .next() .ok_or_else(|| ToolFailure::new(format!("no {} with id {}", args.kind.as_str(), args.id))) } #[cfg(test)] #[path = "record_tests.rs"] mod tests;