//! `create_note`, `update_note`, `archive_note`, `unarchive_note`, //! `append_journal`, `upsert_managed_note`, `list_managed_notes` — the notes //! and journal block of `packages/server/src/mcp/records.ts`. use cotton_store::protocol::derived_id::project_link_id; use serde_json::{Map, Value}; use crate::mcp::dispatch::{Ctx, ToolResult}; use crate::mcp::handlers::attachments::{apply_attachments, NOTE}; use crate::mcp::handlers::common::{ author_stamp, insert_row, maybe_row, now_iso, or_null, project_by_slug, projects, put, rows, text, today_in, update_row, workspace_timezone, Valid, }; use crate::mcp::handlers::records_1::validate::{ validate_append_journal, validate_create_note, validate_create_table_note, validate_id, validate_list_managed_notes, validate_note_id, validate_update_note, validate_upsert_managed_note, }; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::{Filter, Order, Query}; /// The table a note's pictures live in (schema v32) — the mechanism itself is /// `handlers::attachments`, shared with a thought's pictures. pub const ATTACHMENTS: &str = NOTE.table; // ── notes ─────────────────────────────────────────────────────────────────── pub fn create_note(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_create_note(args)?; insert_note(ctx, args) } /// `create_record { table: "note" }`'s write: a title alone is a note /// (`validate_create_table_note` says why). pub fn create_table_note(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_create_table_note(args)?; insert_note(ctx, args) } fn insert_note( ctx: &mut Ctx<'_>, args: crate::mcp::handlers::records_1::validate::CreateNoteArgs, ) -> ToolResult { let id = ctx.new_uuid(); let mut patch = Map::new(); patch.insert("kind".to_string(), Value::from("note")); patch.insert("title".to_string(), or_null(args.title)); patch.insert("body".to_string(), Value::from(args.body)); for (key, value) in author_stamp(ctx) { patch.insert(key, value); } insert_row(ctx, "cotton_notes", &id, patch)?; // Inside the SAME transaction as the note: an attachment's foreign key // names the note, and a picture refused halfway must leave no note behind // for the caller to wonder about. if let Some(attachments) = &args.attachments { apply_attachments(ctx, &NOTE, &id, attachments)?; } ctx.commit()?; // Its hashtags file it at once, as a phone's own edit does. crate::mcp::handlers::records_1::note_tags::file_stored(ctx, &id)?; ctx.commit()?; let row = maybe_row( ctx, &Query::on("cotton_notes") .columns(&["id", "title", "kind"]) .eq("id", id.clone()), )? .ok_or_else(|| ToolFailure::new(format!("no note with id {id}")))?; Ok(Value::Object(row)) } /// Rewrite a note's title and/or body. LIVE notes only: an assistant editing /// something the user archived would be writing where they cannot see it. The /// prior text survives in its `cotton_changes` row (written by the act), which is /// what makes handing an assistant an edit tool safe at all. pub fn update_note(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_update_note(args)?; let live = Query::on("cotton_notes") .eq("id", args.id.clone()) .filter(Filter::IsNull("archived_at".to_string())) .filter(Filter::IsNull("trashed_at".to_string())); if maybe_row(ctx, &live)?.is_none() { return Err(ToolFailure::new(format!( "no live note with id {} (it may be archived or in the bin — get_record will say)", args.id ))); } let mut patch = Map::new(); for (key, value) in author_stamp(ctx) { patch.insert(key, value); } if let Some(title) = args.title { patch.insert("title".to_string(), Value::from(title)); } if let Some(body) = args.body { patch.insert("body".to_string(), Value::from(body)); } if let Some(pinned) = args.pinned { patch.insert("pinned".to_string(), Value::Bool(pinned)); } update_row(ctx, "cotton_notes", &args.id, patch)?; if let Some(attachments) = &args.attachments { apply_attachments(ctx, &NOTE, &args.id, attachments)?; } ctx.commit()?; crate::mcp::handlers::records_1::note_tags::file_stored(ctx, &args.id)?; ctx.commit()?; let row = maybe_row( ctx, &Query::on("cotton_notes") .columns(&["id", "title", "kind", "journal_date"]) .eq("id", args.id.clone()), )? .ok_or_else(|| ToolFailure::new(format!("no note with id {}", args.id)))?; Ok(Value::Object(row)) } pub fn archive_note(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let id = validate_note_id(args)?; // Looked up before it is written so that "already archived" (idempotent, a // retried sync run) stays distinguishable from "not a note you can reach". let existing = maybe_row( ctx, &Query::on("cotton_notes") .columns(&["id", "title", "archived_at"]) .eq("id", id.clone()), )? .ok_or_else(|| ToolFailure::new(format!("no note with id {id}")))?; let title = or_null(text(&existing, "title")); if text(&existing, "archived_at").is_some() { let mut out = Map::new(); out.insert("id".to_string(), Value::from(id)); out.insert("title".to_string(), title); out.insert("alreadyArchived".to_string(), Value::Bool(true)); return Ok(Value::Object(out)); } let mut patch = Map::new(); patch.insert("archived_at".to_string(), Value::from(now_iso(ctx))); update_row(ctx, "cotton_notes", &id, patch)?; ctx.commit()?; let mut out = Map::new(); out.insert("id".to_string(), Value::from(id)); out.insert("title".to_string(), title); out.insert("alreadyArchived".to_string(), Value::Bool(false)); Ok(Value::Object(out)) } pub fn unarchive_note(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let id = validate_id(args)?; let existing = maybe_row( ctx, &Query::on("cotton_notes") .columns(&["id", "title", "archived_at"]) .eq("id", id.clone()), )? .ok_or_else(|| ToolFailure::new(format!("no note with id {id}")))?; let title = or_null(text(&existing, "title")); if text(&existing, "archived_at").is_none() { let mut out = Map::new(); out.insert("id".to_string(), Value::from(id)); out.insert("title".to_string(), title); out.insert("alreadyLive".to_string(), Value::Bool(true)); return Ok(Value::Object(out)); } let mut patch = Map::new(); patch.insert("archived_at".to_string(), Value::Null); update_row(ctx, "cotton_notes", &id, patch)?; ctx.commit()?; let mut out = Map::new(); out.insert("id".to_string(), Value::from(id)); out.insert("title".to_string(), title); out.insert("alreadyLive".to_string(), Value::Bool(false)); Ok(Value::Object(out)) } /// Put a note in the bin, or take it out: the note's Delete and its Undo /// (and the bin's Restore, which clears the same column). Only a note goes /// in. Journal days have their own Bin kind and retain their dated contents. pub fn set_trashed(ctx: &mut Ctx<'_>, id: &str, trashed: bool) -> Valid<()> { let note = Query::on("cotton_notes").columns(&["id"]).eq("id", id.to_string()).eq("kind", "note".to_string()); if maybe_row(ctx, ¬e)?.is_none() { return Err(ToolFailure::new(format!("no note with id {id}"))); } let kind = cotton_core::constants::BinKind::Note; if trashed { crate::mcp::handlers::bin::put_away(ctx, kind, id) } else { let args = serde_json::json!({"kind": kind.as_str(), "id": id}); crate::mcp::handlers::bin::restore_from_bin(ctx, args.as_object().unwrap()).map(|_| ()) } } // ── the journal ───────────────────────────────────────────────────────────── /// Append to a day's page, creating it if absent. /// /// One page per day PER CONTEXT is enforced by a partial unique index, so this /// reads-then-writes rather than upserting: the append has to know the existing /// body to add to it. The context is `project_id` — NULL is the owner's own /// daily page — and BOTH sides of the lookup filter on it, because a lookup /// that filtered on neither would let an assistant's project entry take over /// his own page for the day. pub fn append_journal(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_append_journal(args)?; let date = match args.date { Some(date) => date, None => today_in(&workspace_timezone(ctx)?, ctx.now.timestamp_millis())?, }; // Resolved BEFORE anything is read or written: an unknown slug refuses // here, naming the projects that do exist, and nothing has been touched. let project = match &args.project { None => None, Some(slug) => Some(project_by_slug(&projects(ctx)?, slug)?), }; // Archived pages are read too, and deliberately: the one-page-per-day // unique index does not exclude them, so treating an archived page as // absent would make the insert below fail on a constraint the caller cannot // see. Writing to the day means the day is wanted, so it comes back out of // the archive. let mut lookup = Query::on("cotton_notes") .columns(&["id", "body", "archived_at", "created_at"]) .eq("kind", "journal".to_string()) .eq("journal_date", date.clone()) .order_by("created_at", Order::Asc) .limit(1); lookup = match &project { None => lookup.filter(Filter::IsNull("project_id".to_string())), Some(project) => lookup.eq("project_id", project.id.clone()), }; let existing = rows(ctx, &lookup)?.into_iter().next(); let (note_id, created, unarchived) = match existing { Some(existing) => { let id = text(&existing, "id").unwrap_or_default(); let was_archived = text(&existing, "archived_at").is_some(); let body = format!( "{}\n\n{}", text(&existing, "body").unwrap_or_default(), args.text ) .trim() .to_string(); let mut patch = Map::new(); patch.insert("body".to_string(), Value::from(body)); patch.insert("archived_at".to_string(), Value::Null); update_row(ctx, "cotton_notes", &id, patch)?; ctx.commit()?; (id, false, was_archived) } None => { let id = ctx.new_uuid(); let mut patch = Map::new(); patch.insert("kind".to_string(), Value::from("journal")); patch.insert("journal_date".to_string(), Value::from(date.clone())); patch.insert("title".to_string(), Value::Null); patch.insert("body".to_string(), Value::from(args.text.clone())); patch.insert( "project_id".to_string(), project .as_ref() .map_or(Value::Null, |project| Value::from(project.id.clone())), ); for (key, value) in author_stamp(ctx) { patch.insert(key, value); } insert_row(ctx, "cotton_notes", &id, patch)?; ctx.commit()?; (id, true, false) } }; let mut out = Map::new(); out.insert("id".to_string(), Value::from(note_id.clone())); out.insert("journal_date".to_string(), Value::from(date)); if let Some(project) = &project { out.insert("project".to_string(), Value::from(project.slug.clone())); // The mirror is re-asserted on the APPEND path too, not only on create: // a page whose link row was removed heals on the next entry rather than // staying invisible to every surface that reads the links table. if let Some(reason) = mirror_after_text(ctx, &project.id, ¬e_id) { out.insert("link".to_string(), Value::from(reason)); } } out.insert("created".to_string(), Value::Bool(created)); out.insert("unarchived".to_string(), Value::Bool(unarchived)); Ok(Value::Object(out)) } /// The mirror write, AFTER the person's words are already on disk — which is /// why it cannot throw. /// /// A `ToolFailure` here would reach the assistant as "the call failed", and the /// natural response to a failed append is to send it again — which appends the /// SAME paragraph a second time. The mirror being absent costs a reader one /// section row; a doubled paragraph costs the owner words they have to delete. fn mirror_after_text(ctx: &mut Ctx<'_>, project_id: &str, note_id: &str) -> Option { match ensure_journal_mirror(ctx, project_id, note_id) { Ok(()) => None, Err(failure) => Some(format!( "failed ({}) — the text was saved; the next append or link_to_project converges it", failure.message() )), } } /// The link row that MIRRORS a project page's `project_id` column. /// /// Its id is derived (`projectLinkId`), so a replay converges on the row that /// is already there rather than minting a sibling, and the insert is SKIPPED /// when it exists rather than upserted: a blind re-insert would restamp /// `created_at` and move the page in every arrival-ordered read. fn ensure_journal_mirror(ctx: &mut Ctx<'_>, project_id: &str, note_id: &str) -> Valid<()> { let id = project_link_id(project_id, "journal", note_id); if maybe_row( ctx, &Query::on("cotton_project_links") .columns(&["id"]) .eq("id", id.clone()), )? .is_some() { return Ok(()); } let mut patch = Map::new(); patch.insert("project_id".to_string(), Value::from(project_id)); patch.insert("record_kind".to_string(), Value::from("journal")); patch.insert("record_id".to_string(), Value::from(note_id)); patch.insert("note".to_string(), Value::Null); patch.insert("applied_by".to_string(), Value::from("agent")); insert_row(ctx, "cotton_project_links", &id, patch)?; ctx.commit()?; Ok(()) } // ── managed notes ─────────────────────────────────────────────────────────── /// Publish a note whose source of truth lives elsewhere, keyed by the manager's /// own `externalId`. Idempotent by content: an unchanged `sourceHash` writes /// nothing at all, which is what lets a sync run on a timer without filling the /// record's history with edits that changed no text. pub fn upsert_managed_note(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_upsert_managed_note(args)?; let existing = maybe_row( ctx, &Query::on("cotton_notes") .columns(&["id", "source_hash", "archived_at", "trashed_at", "managed_by"]) .eq("external_id", args.external_id.clone()), )?; // The external id is unique per WORKSPACE, not per manager, so a second // manager claiming the same key must be refused rather than silently // overwriting the first one's note. if let Some(existing) = &existing { let owner = text(existing, "managed_by"); if owner.as_deref() != Some(args.managed_by.as_str()) { return Err(ToolFailure::new(format!( "externalId {} belongs to {}", crate::mcp::handlers::common::quoted(&args.external_id), match owner { Some(owner) => crate::mcp::handlers::common::quoted(&owner), None => crate::mcp::handlers::common::quoted("an unmanaged note"), } ))); } } if let Some(existing) = existing { let id = text(&existing, "id").unwrap_or_default(); let archived = text(&existing, "archived_at").is_some() || text(&existing, "trashed_at").is_some(); let unchanged = args.source_hash.is_some() && text(&existing, "source_hash") == args.source_hash && !archived; if unchanged { let mut out = Map::new(); out.insert("id".to_string(), Value::from(id)); out.insert("status".to_string(), Value::from("unchanged")); return Ok(Value::Object(out)); } let mut patch = Map::new(); patch.insert("title".to_string(), or_null(args.title)); patch.insert("body".to_string(), Value::from(args.body)); patch.insert("source_hash".to_string(), or_null(args.source_hash)); patch.insert("managed_by".to_string(), Value::from(args.managed_by)); // A source that came back is not archived, or in the bin, any more. patch.insert("archived_at".to_string(), Value::Null); patch.insert("trashed_at".to_string(), Value::Null); for (key, value) in author_stamp(ctx) { patch.insert(key, value); } update_row(ctx, "cotton_notes", &id, patch)?; ctx.commit()?; crate::mcp::handlers::records_1::note_tags::file_stored(ctx, &id)?; ctx.commit()?; let mut out = Map::new(); out.insert("id".to_string(), Value::from(id)); out.insert( "status".to_string(), Value::from(if archived { "restored" } else { "updated" }), ); return Ok(Value::Object(out)); } let id = ctx.new_uuid(); let mut patch = Map::new(); patch.insert("kind".to_string(), Value::from("note")); patch.insert("title".to_string(), or_null(args.title)); patch.insert("body".to_string(), Value::from(args.body)); patch.insert("managed_by".to_string(), Value::from(args.managed_by)); patch.insert("external_id".to_string(), Value::from(args.external_id)); patch.insert("source_hash".to_string(), or_null(args.source_hash)); for (key, value) in author_stamp(ctx) { patch.insert(key, value); } insert_row(ctx, "cotton_notes", &id, patch)?; ctx.commit()?; crate::mcp::handlers::records_1::note_tags::file_stored(ctx, &id)?; ctx.commit()?; let mut out = Map::new(); out.insert("id".to_string(), Value::from(id)); out.insert("status".to_string(), Value::from("created")); Ok(Value::Object(out)) } /// The manager's own index: what it published, and whether it still shows. pub fn list_managed_notes(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_list_managed_notes(args)?; let query = Query::on("cotton_notes") .columns(&["id", "external_id", "source_hash", "archived_at", "trashed_at"]) .eq("managed_by", args.managed_by) .limit(args.limit); let notes: Vec = rows(ctx, &query)? .into_iter() .map(|row| { let mut item = Map::new(); item.insert("id".to_string(), or_null(text(&row, "id"))); item.insert("externalId".to_string(), or_null(text(&row, "external_id"))); item.insert("sourceHash".to_string(), or_null(text(&row, "source_hash"))); // Put away either way: archived, or in the bin. let hidden = text(&row, "archived_at").is_some() || text(&row, "trashed_at").is_some(); item.insert("archived".to_string(), Value::Bool(hidden)); Value::Object(item) }) .collect(); let mut out = Map::new(); put(&mut out, "notes", Some(Value::Array(notes))); Ok(Value::Object(out)) }