//! `brief`, `recall`, `remember`, `memory_update`, `memory_reorder`, //! `memory_archive` — the memory block of //! `packages/server/src/mcp/records.ts` (lines ~5977-7383). //! //! Three rules decide the shape of everything here, and all three are the //! owner's own rulings rather than this port's inventions. //! //! MEMORY IS A LINKED KIND, with NO global layer. An entry lives once and //! briefs in its PROJECTS through `cotton_project_links`, and the //! arrangement — pinned, position — is on the LINK, so one sentence is //! arranged once per project. A second home is a link, never a copy; an entry //! ALWAYS has a project, so `unlink_from_project` REFUSES the unlink that //! would leave one with none rather than archiving it — retiring the owner's //! own words is `memory_archive`, his own act. //! //! EVERY AGENT WRITE LANDS LIVE: a ruling given mid-session binds the next //! session now. Memory keeps no review state (owner, 25 Oct 2026). //! //! `remember` RECONCILES BEFORE IT WRITES. At or above //! [`MEMORY_NOOP_THRESHOLD`] the sentence is already there and nothing is //! written (or the project merely gains a link); below it but above the //! engine's similarity threshold the call answers `needsDecision` and writes //! NOTHING, so a duplicate never reaches the owner's feed by accident. //! //! The pure halves live in `cotton_core::engine` and are never re-derived //! here: `memory_briefing` compiles the briefing and mints the slug, //! `memory_retired_fields` names the fields a write path refuses, //! `memory_order` owns memory's own position step (1000, and a refusal rather than a renumber when the gap is gone). use std::collections::{BTreeMap, HashMap, HashSet}; use cotton_core::constants::{MemoryOriginKind, MemoryStatus, ProjectLinkKind}; use cotton_core::constants::{MEMORY_BRIEFING_BUDGET_TOKENS, MEMORY_BRIEFING_OWNER_TOKENS}; use cotton_core::rules::memory_briefing::{ compile_briefing, compile_briefing_whole, estimate_tokens, looks_like_secret, mint_memory_slug, owner_section_tokens, procedure_trigger, projects_for_repo, title_similarity, BriefingEntry, BriefingInput, BriefingProcedure, BriefingProjectInput, HasRepos, MEMORY_SIMILARITY_THRESHOLD, }; use cotton_core::rules::memory_order::{position_between, position_order, Positioned}; use cotton_core::rules::memory_retired_fields::RetiredField; use cotton_core::rules::shell_lines::LineRow; use cotton_core::rules::memory_technical::{technical_mark, technical_refusal}; use cotton_store::protocol::derived_id::{memory_id, project_link_id}; use cotton_store::schema::codecs::decode_row; use cotton_store::schema::specs::columns_of; use cotton_store::search::to_match_query; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value}; use crate::mcp::dispatch::{Ctx, ToolResult}; use crate::mcp::handlers::common::{ fail, flag, in_chunks, insert_row, is_uuid, iso_of_ms, maybe_row, now_iso, now_ms, optional_string, or_null, quoted, rows, text, today_in, update_row, workspace_timezone, ProjectRef, Valid, }; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::{Filter, Order, Query}; // ── the columns, as the TypeScript names them ─────────────────────────────── const MEMORY_COLUMNS: &[&str] = &[ "id", "slug", "title", "status", "machine", "visibility", "origin_kind", "origin_label", "source", "superseded_by", "source_external_id", "archived_at", "created_at", "updated_at", ]; const MEMORY_LINK_COLUMNS: &[&str] = &[ "id", "project_id", "record_id", "pinned", "position", "created_at", "updated_at", ]; const PROJECT_COLUMNS: &[&str] = &[ "id", "slug", "name", "repos", "brand", "description", "status", "summary_by", "summary_updated_at", ]; /// What the reconcile scan reads per entry row — the whole workspace is /// loaded, so bodies stay out of it. const ENTRY_COLUMNS: &[&str] = &["id", "slug", "title", "status", "updated_at"]; /// Similarity at or above which `remember` answers "that is already here". const MEMORY_NOOP_THRESHOLD: f64 = 0.92; /// How many FTS hits on the title join the candidate set. const CANDIDATE_FTS_LIMIT: i64 = 8; /// `MEMORY_TITLE_MAX` — the sentence IS the memory. pub const MEMORY_TITLE_MAX: usize = 280; // ── the rows ──────────────────────────────────────────────────────────────── /// One `cotton_memories` row. #[derive(Debug, Clone)] pub struct MemoryRow { pub id: String, pub slug: String, pub title: String, pub status: String, pub machine: Option, pub visibility: String, pub origin_kind: String, pub origin_label: Option, pub source: Option, pub superseded_by: Option, pub archived_at: Option, pub created_at: String, pub updated_at: String, } impl MemoryRow { fn of(row: &Map) -> Result { let required = |field| { text(row, field).ok_or_else(|| ToolFailure::new(format!("memory row is missing {field}"))) }; let status = required("status")?; if MemoryStatus::parse(&status).is_none() { return Err(ToolFailure::new(format!("unknown memory status: {status}"))); } let origin_kind = required("origin_kind")?; if MemoryOriginKind::parse(&origin_kind).is_none() { return Err(ToolFailure::new(format!("unknown memory origin: {origin_kind}"))); } Ok(MemoryRow { id: required("id")?, slug: required("slug")?, title: required("title")?, status, machine: text(row, "machine"), visibility: required("visibility")?, origin_kind, origin_label: text(row, "origin_label"), source: text(row, "source"), superseded_by: text(row, "superseded_by"), archived_at: text(row, "archived_at"), created_at: required("created_at")?, updated_at: required("updated_at")?, }) } } /// One project's membership of one entry — a `cotton_project_links` row with /// `record_kind = 'memory'`. The arrangement is this row's, not the entry's. #[derive(Debug, Clone)] pub struct MemoryLinkRow { pub id: String, pub project_id: String, pub record_id: String, pub pinned: bool, pub position: f64, } impl MemoryLinkRow { fn of(row: &Map) -> MemoryLinkRow { MemoryLinkRow { id: text(row, "id").unwrap_or_default(), project_id: text(row, "project_id").unwrap_or_default(), record_id: text(row, "record_id").unwrap_or_default(), pinned: flag(row, "pinned"), position: row .get("position") .and_then(Value::as_f64) .unwrap_or_default(), } } } /// One `cotton_memory_projects` row — the FULL read, which /// `common::ProjectRef` deliberately is not: `brief`'s working-context coda /// needs the summary and its provenance, and `projects_for_repo` needs the /// repos. #[derive(Debug, Clone)] pub struct MemoryProject { pub id: String, pub slug: String, pub name: String, pub repos: Vec, pub description: Option, pub summary_by: Option, pub summary_updated_at: Option, pub status: String, } impl HasRepos for MemoryProject { fn repos(&self) -> &[String] { &self.repos } } /// `repoList` — a JSON column that promises only "an array". fn repo_list(value: Option<&Value>) -> Vec { value .and_then(Value::as_array) .map(|items| { items .iter() .filter_map(|entry| entry.as_str().map(str::to_string)) .collect() }) .unwrap_or_default() } /// `memoryProjects` — every project, oldest first. pub fn memory_projects(ctx: &Ctx<'_>) -> Result, ToolFailure> { let query = Query::on("cotton_memory_projects") .columns(PROJECT_COLUMNS) .order_by("created_at", Order::Asc); Ok(rows(ctx, &query)? .into_iter() .map(|row| MemoryProject { id: text(&row, "id").unwrap_or_default(), slug: text(&row, "slug").unwrap_or_default(), name: text(&row, "name").unwrap_or_default(), repos: repo_list(row.get("repos")), description: text(&row, "description"), summary_by: text(&row, "summary_by"), summary_updated_at: text(&row, "summary_updated_at"), status: text(&row, "status").unwrap_or_default(), }) .collect()) } /// The same rows as `common`'s narrow shape, so the shared slug resolvers can /// be used rather than a second copy of their refusal sentences. fn refs_of(projects: &[MemoryProject]) -> Vec { projects .iter() .map(|project| ProjectRef { id: project.id.clone(), slug: project.slug.clone(), status: project.status.clone(), }) .collect() } // ── reading entries ───────────────────────────────────────────────────────── /// The file, decoded through the memories codecs — FTS reads land here. fn decode_memory_rows( found: Vec, ) -> Result, ToolFailure> { let columns = columns_of("cotton_memories") .ok_or_else(|| ToolFailure::new("cotton-mcp: no table spec for cotton_memories"))?; let mut out = Vec::with_capacity(found.len()); for row in &found { let decoded = decode_row(columns, row.columns()) .map_err(|error| ToolFailure::new(error.to_string()))?; out.push(MemoryRow::of(&decoded)?); } Ok(out) } /// Address one entry by id or by slug — one slug per workspace since schema /// v35, so `project` on a ref names the LINK a pin or a reorder applies to, /// never a disambiguator. fn memory_by_ref(ctx: &Ctx<'_>, reference: &MemoryRef) -> Result { let mut query = Query::on("cotton_memories").columns(MEMORY_COLUMNS); query = match (&reference.id, &reference.slug) { (Some(id), _) => query.eq("id", id.clone()), (None, Some(slug)) => query.eq("slug", slug.clone()), (None, None) => return Err(ToolFailure::new("address the entry by slug or id")), }; match maybe_row(ctx, &query)? { Some(row) => MemoryRow::of(&row), None => Err(ToolFailure::new(match (&reference.id, &reference.slug) { (Some(id), _) => format!("no memory with id {id}"), _ => format!( "no memory entry with slug {}", quoted(reference.slug.as_deref().unwrap_or_default()) ), })), } } /// Which links to read. Both halves may be given; an EMPTY list on either /// means "nothing matches", never "everything". #[derive(Debug, Default, Clone)] struct LinksBy { project_ids: Option>, memory_ids: Option>, } /// The memory links, in each project's own arrangement (pinned first, then /// position). fn memory_links(ctx: &Ctx<'_>, by: &LinksBy) -> Result, ToolFailure> { if by.project_ids.as_ref().is_some_and(Vec::is_empty) || by.memory_ids.as_ref().is_some_and(Vec::is_empty) { return Ok(Vec::new()); } let read = |memory_ids: Option<&[String]>| -> Result, ToolFailure> { let mut query = Query::on("cotton_project_links") .columns(MEMORY_LINK_COLUMNS) .eq("record_kind", "memory".to_string()); if let Some(project_ids) = &by.project_ids { query = query.filter(Filter::In( "project_id".to_string(), project_ids.iter().cloned().map(SqlValue::Text).collect(), )); } if let Some(memory_ids) = memory_ids { query = query.filter(Filter::In( "record_id".to_string(), memory_ids.iter().cloned().map(SqlValue::Text).collect(), )); } let query = query .order_by("pinned", Order::Desc) .order_by("position", Order::Asc); Ok(rows(ctx, &query)? .into_iter() .map(|row| MemoryLinkRow::of(&row)) .collect()) }; let Some(memory_ids) = &by.memory_ids else { return read(None); }; let mut found = in_chunks(memory_ids, |batch| read(Some(batch)))?; // The chunked read loses the global order the single read had, so it is // re-imposed here — pinned first, then position, then the id, exactly as // the TypeScript's comparator does. found.sort_by(|a, b| { b.pinned .cmp(&a.pinned) .then_with(|| a.position.total_cmp(&b.position)) .then_with(|| a.id.cmp(&b.id)) }); Ok(found) } fn links_by_memory(links: &[MemoryLinkRow]) -> HashMap> { let mut out: HashMap> = HashMap::new(); for link in links { out.entry(link.record_id.clone()) .or_default() .push(link.clone()); } out } /// The link's project as a reader names it. An ARCHIVED project's link is /// kept on disk (unarchiving the project brings its memory back) but is not a /// home anything briefs, so it is not answered here. fn memory_homes(links: &[MemoryLinkRow], projects: &[MemoryProject]) -> Vec { let mut homes: Vec<(String, bool, f64)> = Vec::new(); for link in links { let Some(project) = projects .iter() .find(|candidate| candidate.id == link.project_id) else { continue; }; if project.status != "active" { continue; } homes.push((project.slug.clone(), link.pinned, link.position)); } homes.sort_by(|a, b| a.0.cmp(&b.0)); homes .into_iter() .map(|(slug, pinned, position)| { let mut out = Map::new(); out.insert("slug".to_string(), Value::from(slug)); out.insert("pinned".to_string(), Value::from(pinned)); out.insert( "position".to_string(), crate::mcp::handlers::common::js_number(position), ); Value::Object(out) }) .collect() } fn memory_home_slugs(links: &[MemoryLinkRow], projects: &[MemoryProject]) -> Vec { memory_homes(links, projects) .into_iter() .map(|home| home["slug"].clone()) .collect() } /// The entry as every reader answers it. Key order is the TypeScript object's. fn memory_out( row: &MemoryRow, links: &[MemoryLinkRow], projects: &[MemoryProject]) -> Value { let mut out = Map::new(); out.insert("id".to_string(), Value::from(row.id.clone())); out.insert("slug".to_string(), Value::from(row.slug.clone())); out.insert("title".to_string(), Value::from(row.title.clone())); out.insert( "projects".to_string(), Value::Array(memory_homes(links, projects)), ); out.insert("status".to_string(), Value::from(row.status.clone())); out.insert( "originKind".to_string(), Value::from(row.origin_kind.clone()), ); out.insert("originLabel".to_string(), or_null(row.origin_label.clone())); out.insert("machine".to_string(), or_null(row.machine.clone())); out.insert("source".to_string(), or_null(row.source.clone())); out.insert( "supersededBy".to_string(), or_null(row.superseded_by.clone()), ); out.insert("archivedAt".to_string(), or_null(row.archived_at.clone())); out.insert("createdAt".to_string(), Value::from(row.created_at.clone())); out.insert("updatedAt".to_string(), Value::from(row.updated_at.clone())); Value::Object(out) } /// `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. /// /// `pub` for `records_2::record`, which is the reader that shows it. pub fn memory_record(ctx: &Ctx<'_>, id: &str) -> Result { let row = memory_by_ref( ctx, &MemoryRef { id: Some(id.to_string()), ..MemoryRef::default() }, )?; let links = memory_links( ctx, &LinksBy { memory_ids: Some(vec![id.to_string()]), ..LinksBy::default() }, )?; let projects = memory_projects(ctx)?; Ok(memory_out(&row, &links, &projects)) } /// Every non-archived PRIVATE entry — what the counts and the briefing read /// once. The visibility gate is the standing rule: nothing above private /// renders in any briefing, and the attention counts must not tease entries /// the briefing will not show. fn live_memories(ctx: &Ctx<'_>) -> Result, ToolFailure> { let query = Query::on("cotton_memories") .columns(MEMORY_COLUMNS) .eq("visibility", "private".to_string()) .filter(Filter::Ne( "status".to_string(), SqlValue::Text("archived".to_string()), )); rows(ctx, &query)?.iter().map(MemoryRow::of).collect() } /// The owner's name for the briefing's greeting — always `None` today, and /// that is the TypeScript's behaviour rather than a gap in this port. /// /// `ownerName` reads `profiles`, a PLATFORM table of the retired Postgres /// cell: `ddl.v1.ts` drops it by name ("platform table, not the user's"), so /// the file has no such table. The TypeScript destructures `const { data }` /// and never looks at `error`, so the read fails silently and the compiler /// falls back to "the owner". Answering `None` here IS that behaviour, spelled /// out — a `Query::on("profiles")` would raise "no table spec for profiles" /// and fail every `brief` call, which the TypeScript does not do. /// /// The day the server learns the owner's name from `registry.db`, this is the /// one function that changes. fn owner_name(_ctx: &Ctx<'_>) -> Result, ToolFailure> { Ok(None) } // ── brief ─────────────────────────────────────────────────────────────────── /// The procedures linked to the matched projects. /// /// A procedure is an ordinary note whose first line names the trigger a session /// matches on — [`procedure_trigger`] is the one place that rule lives, and /// `get_project` reads it through the same function so the two surfaces cannot /// disagree about what a procedure is. An archived note is not offered. fn procedures_for( ctx: &Ctx<'_>, projects: &[MemoryProject], ) -> Result, ToolFailure> { if projects.is_empty() { return Ok(Vec::new()); } let project_ids: Vec = projects.iter().map(|project| project.id.clone()).collect(); let links = rows( ctx, &Query::on("cotton_project_links") .columns(&["project_id", "record_id"]) .eq("record_kind", ProjectLinkKind::Note.as_str().to_string()) .filter(Filter::In( "project_id".to_string(), project_ids.iter().cloned().map(SqlValue::Text).collect(), )), )?; let note_ids: Vec = links .iter() .filter_map(|row| text(row, "record_id")) .collect(); if note_ids.is_empty() { return Ok(Vec::new()); } let notes = in_chunks(¬e_ids, |batch| { rows( ctx, &Query::on("cotton_notes") .columns(&["id", "title", "body", "archived_at"]) .eq("kind", ProjectLinkKind::Note.as_str().to_string()) // A trigger must contain this ASCII label. SQL only narrows // candidates; procedure_trigger still decides its first line. .filter(Filter::Static("instr(lower(body), 'trigger:') > 0")) // A note in the bin is no trigger: it is deleted, waiting. .filter(Filter::IsNull("trashed_at".to_string())) .filter(Filter::In( "id".to_string(), batch.iter().cloned().map(SqlValue::Text).collect(), )), ) })?; let triggers: HashMap = notes .iter() .filter(|row| text(row, "archived_at").is_none()) .filter_map(|row| { let id = text(row, "id")?; let trigger = procedure_trigger(text(row, "body").unwrap_or_default().as_str())?; let title = text(row, "title").unwrap_or_else(|| "(untitled)".to_string()); Some((id, (title, trigger))) }) .collect(); let slugs: HashMap<&str, &str> = projects .iter() .map(|project| (project.id.as_str(), project.slug.as_str())) .collect(); Ok(links .iter() .filter_map(|row| { let id = text(row, "record_id")?; let (title, trigger) = triggers.get(&id)?.clone(); let project = slugs.get(text(row, "project_id")?.as_str())?.to_string(); Some(BriefingProcedure { project, id, title, trigger, }) }) .collect()) } // ── the Owner layer ───────────────────────────────────────────────────────── /// The owner's own entries (owner, 12 Oct 2026): live in their PERSONAL /// database and briefing in no project — what is true of the owner whatever /// the work. Oldest first, the order the owner wrote them. Read straight off /// the driver, because `brief` in a project database reads it from the /// personal file before that file is taken (`cotton_server::mcp::before_file`). pub fn owner_entries_of( db: &cotton_store::Driver, workspace_id: &str, ) -> cotton_store::Result> { let rows = db.all( "SELECT m.slug, m.title, m.machine, m.created_at FROM cotton_memories m \ WHERE m.workspace_id = ? AND m.status = 'active' AND m.visibility = 'private' \ AND NOT EXISTS (SELECT 1 FROM cotton_project_links l \ WHERE l.record_kind = 'memory' AND l.record_id = m.id) \ ORDER BY m.created_at, m.slug", &[SqlValue::Text(workspace_id.to_string())], )?; Ok(rows .iter() .enumerate() .map(|(at, row)| BriefingEntry { slug: row.text("slug").unwrap_or_default().to_string(), title: row.text("title").unwrap_or_default().to_string(), pinned: false, position: at as f64, machine: row.text("machine").map(str::to_string), created_at: row.text("created_at").unwrap_or_default().to_string(), }) .collect()) } /// The Owner section's entries for a brief running here: what the dispatcher /// read from the personal file before this one was taken — it does so only /// when the brief runs in another database — else none in a project database, /// else this file's own. fn owner_for_brief(ctx: &Ctx<'_>) -> Result, ToolFailure> { if let Some(owner) = &ctx.services.owner_memory { return Ok(owner.to_vec()); } if ctx.file_kind()? == cotton_store::link_rule::FileKind::Shared { return Ok(Vec::new()); } owner_entries_of(ctx.db(), ctx.workspace_id) .map_err(|error| ToolFailure::new(error.to_string())) } /// The Owner section's cap, enforced at write time like a project's budget: an /// owner entry that would take the section past /// [`MEMORY_BRIEFING_OWNER_TOKENS`] is refused with the numbers, so it never /// lands only to be left out. A write that makes the section no longer passes. fn refuse_owner_over_cap( ctx: &Ctx<'_>, change: impl Fn(&mut Vec), ) -> Result<(), ToolFailure> { let mut entries = owner_entries_of(ctx.db(), ctx.workspace_id) .map_err(|error| ToolFailure::new(error.to_string()))?; let before = owner_section_tokens(&entries); change(&mut entries); let after = owner_section_tokens(&entries); if after > MEMORY_BRIEFING_OWNER_TOKENS as i64 && after > before { return Err(ToolFailure::new(format!( "the Owner section would be {after} tokens, over its {MEMORY_BRIEFING_OWNER_TOKENS}-token \ limit — nothing was written. It opens every brief, so make room first: tighten an \ entry with memory_update, or archive one that is no longer true with memory_archive." ))); } Ok(()) } pub fn brief(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_brief(args)?; let projects = memory_projects(ctx)?; let active: Vec = projects .iter() .filter(|project| project.status == "active") .cloned() .collect(); // Which projects brief: an explicit project wins; otherwise every active // project listing the caller's repo; otherwise none — and the compiler // says how to find one. There is no project-independent layer to fall // back to. let matched: Vec = if let Some(slug) = &args.project { let project_id = crate::mcp::handlers::common::resolve_project(&refs_of(&projects), Some(slug))?; active .iter() .filter(|project| Some(&project.id) == project_id.as_ref()) .cloned() .collect() } else if let Some(repo_url) = &args.repo_url { projects_for_repo(&active, repo_url) .into_iter() .cloned() .collect() } else { Vec::new() }; let stamp = now_iso(ctx); // The brief is the owner's memory entries and nothing else (owner, 24 Oct // 2026): no project context, no counts, no sessions, no tool instructions // ride after the compiled memory. A tool's instructions come with its // definition in list_tools. let budget = args .budget_tokens .unwrap_or(cotton_core::constants::MEMORY_BRIEFING_BUDGET_TOKENS); let mut input = briefing_input(ctx, &projects, &matched, args.machine.clone(), Some(budget))?; input.owner = Some(owner_for_brief(ctx)?); let result = compile_briefing(&input); let markdown = result.markdown.clone(); let mut out = Map::new(); out.insert("briefing".to_string(), Value::from(markdown.clone())); let tokens = estimate_tokens(&markdown); out.insert("tokensEstimate".to_string(), Value::from(tokens)); out.insert( "overBudget".to_string(), Value::from(result.over_budget || tokens > budget as i64), ); out.insert( "projects".to_string(), Value::Array( matched .iter() .map(|project| Value::from(project.slug.clone())) .collect(), ), ); out.insert("generatedAt".to_string(), Value::from(stamp)); Ok(Value::Object(out)) } /// The persisted-table projection of one project's session briefing. It uses /// the same input reader and compiler as [`brief`], so Settings never grows a /// second, almost-the-same briefing renderer. pub struct BriefingPreview { pub slug: String, pub name: String, pub markdown: String, pub tokens: i64, pub left_out: i64, } /// One snapshot of the shared inputs for the list. Each project still runs /// through the same compiler and budget as a session's single briefing. pub fn briefing_previews( ctx: &Ctx<'_>, projects: &[MemoryProject], selected: &[MemoryProject], ) -> Result, ToolFailure> { if selected.is_empty() { return Ok(Vec::new()); } let mut shared = briefing_input(ctx, projects, selected, None, None)?; shared.owner = Some(owner_for_brief(ctx)?); let mut previews = Vec::new(); for project in selected { let mut input = shared.clone(); input.projects.retain(|input| input.slug == project.slug); if let Some(procedures) = input.procedures.as_mut() { procedures.retain(|procedure| procedure.project == project.slug); } input.budget_tokens = Some(cotton_core::constants::MEMORY_BRIEFING_BUDGET_TOKENS); let result = compile_briefing(&input); let markdown = result.markdown; previews.push(BriefingPreview { slug: project.slug.clone(), name: project.name.clone(), tokens: estimate_tokens(&markdown), markdown, left_out: result.dropped.entries, }); } Ok(previews) } /// Everything `compile_briefing` reads for these projects, read the way `brief` /// reads it — one function, so the write-time budget check prices exactly the /// compile a session receives. fn briefing_input( ctx: &Ctx<'_>, projects: &[MemoryProject], matched: &[MemoryProject], machine: Option, budget_tokens: Option, ) -> Result { let live = live_memories(ctx)?; let briefed: HashMap = live .iter() .filter(|row| row.status == "active") .map(|row| (row.id.clone(), row.clone())) .collect(); let links = memory_links( ctx, &LinksBy { project_ids: Some(matched.iter().map(|project| project.id.clone()).collect()), ..LinksBy::default() }, )?; let owner = owner_name(ctx)?; let procedures = procedures_for(ctx, matched)?; Ok(BriefingInput { owner: None, owner_name: owner, generated_at: now_iso(ctx), machine, projects: matched .iter() .map(|project| BriefingProjectInput { slug: project.slug.clone(), name: project.name.clone(), entries: links .iter() .filter(|link| link.project_id == project.id) .filter_map(|link| { briefed.get(&link.record_id).map(|row| BriefingEntry { slug: row.slug.clone(), title: row.title.clone(), pinned: link.pinned, position: link.position, machine: row.machine.clone(), created_at: row.created_at.clone(), }) }) .collect(), }) .collect(), procedures: Some(procedures), budget_tokens, pointers: None, }) } /// The briefing limit, enforced at write time (design note d0e27772). /// /// At the owner's own budget a briefing carries every entry, so an entry that /// would take a project's briefing over it is refused HERE, with the numbers, /// instead of landing and quietly being left out of what sessions read. The /// check prices [`compile_briefing_whole`] — every entry kept — because a /// compile that left entries out would hide the size a new one adds to. `change` applies /// the write to one project's entries; the check compiles that project as /// `brief { project }` would, for the machine the entry briefs on, before and /// after. A write that makes the briefing no longer — a correction that /// shortens an entry, a supersede — always passes, so an over-budget briefing /// can always be brought back under. fn refuse_over_budget( ctx: &Ctx<'_>, project_ids: &[String], machine: Option<&str>, change: impl Fn(&mut Vec), ) -> Result<(), ToolFailure> { let projects = memory_projects(ctx)?; for project_id in project_ids { let Some(project) = projects.iter().find(|project| &project.id == project_id) else { continue; }; // The Owner section's whole cap is kept for it: it opens every brief, // and what it holds lives in another database. let left = MEMORY_BRIEFING_BUDGET_TOKENS.saturating_sub(MEMORY_BRIEFING_OWNER_TOKENS); let mut input = briefing_input( ctx, &projects, std::slice::from_ref(project), machine.map(str::to_string), Some(left), )?; let before = compile_briefing_whole(&input); if let Some(only) = input.projects.first_mut() { change(&mut only.entries); } let after = compile_briefing_whole(&input); if after.over_budget && after.tokens_estimate > before.tokens_estimate { let whole = after.tokens_estimate + (MEMORY_BRIEFING_BUDGET_TOKENS - left) as i64; return Err(ToolFailure::new(format!( "{}'s briefing would be {} tokens, over its {}-token limit — nothing was written. \ Every entry briefs whole at this limit, so make room first: tighten a \ long entry with memory_update, or archive one that is no longer true with \ memory_archive. If this is something an agent decided rather than the owner's \ own words, it belongs in the repository beside the code it is about, never in memory.", project.slug, whole, MEMORY_BRIEFING_BUDGET_TOKENS ))); } } Ok(()) } /// The ids of the projects an entry briefs in. fn home_project_ids(ctx: &Ctx<'_>, memory_id: &str) -> Result, ToolFailure> { Ok(memory_links( ctx, &LinksBy { memory_ids: Some(vec![memory_id.to_string()]), ..LinksBy::default() }, )? .into_iter() .map(|link| link.project_id) .collect()) } /// The hostname an entry briefs on, or `None` when it briefs everywhere. fn machine_of(ctx: &Ctx<'_>, memory_id: &str) -> Result, ToolFailure> { Ok( crate::mcp::handlers::common::row_by_id(ctx, "cotton_memories", memory_id)? .and_then(|row| text(&row, "machine")), ) } /// The entry a new line is priced as: the tail of the list, unpinned unless /// asked — the shape `remember` writes. fn priced_entry(slug: &str, title: &str, pinned: bool, machine: Option) -> BriefingEntry { BriefingEntry { slug: slug.to_string(), title: title.to_string(), pinned, position: f64::MAX, machine, created_at: String::new(), } } // ── recall ────────────────────────────────────────────────────────────────── /// What narrows an FTS read. #[derive(Debug, Default, Clone)] struct MemoryFilters { project_id: Option, status: Option, /// Filter archived rows INSIDE the query — before any LIMIT window. exclude_archived: bool, } fn filter_sql(filters: &MemoryFilters, alias: &str) -> (String, Vec) { let mut where_parts: Vec = Vec::new(); let mut params: Vec = Vec::new(); if let Some(status) = &filters.status { where_parts.push(format!("{alias}.status = ?")); params.push(SqlValue::Text(status.clone())); } if filters.exclude_archived { where_parts.push(format!("{alias}.status != 'archived'")); } ( if where_parts.is_empty() { String::new() } else { format!(" AND {}", where_parts.join(" AND ")) }, params, ) } /// Ranked FTS5 over `fts_memories`, best first — ties in the project's own /// arrangement when a project narrows the read, newest-first otherwise. fn memories_by_fts( ctx: &Ctx<'_>, matcher: &str, filters: &MemoryFilters, limit: i64, ) -> Result, ToolFailure> { let (extra_sql, extra_params) = filter_sql(filters, "m"); let scoped = filters.project_id.is_some(); let sql = format!( "SELECT m.*, bm25(fts_memories) AS fts_rank\n FROM fts_memories\n \ JOIN cotton_memories m ON m.rowid = fts_memories.rowid\n {}\n WHERE \ fts_memories.title MATCH ? AND m.workspace_id = ?{}\n ORDER BY fts_rank, {}\n \ LIMIT ?", if scoped { "JOIN cotton_project_links l ON l.record_kind = 'memory' AND l.record_id = m.id AND \ l.project_id = ?" } else { "" }, extra_sql, if scoped { "l.pinned DESC, l.\"position\" ASC" } else { "m.created_at DESC" }, ); let mut params: Vec = Vec::new(); if let Some(project_id) = &filters.project_id { params.push(SqlValue::Text(project_id.clone())); } params.push(SqlValue::Text(matcher.to_string())); params.push(SqlValue::Text(ctx.workspace_id.to_string())); params.extend(extra_params); params.push(SqlValue::Integer(limit)); let found = ctx .db() .all(&sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string()))?; decode_memory_rows(found) } /// `substringOr` — the `%`/`_` escape the ilike pair needs. fn substring_pattern(q: &str) -> String { let mut out = String::with_capacity(q.len() + 2); out.push('%'); for ch in q.chars() { if ch == '%' || ch == '_' { out.push('\\'); } out.push(ch); } out.push('%'); out } /// Search the current sentence over the ids a narrower read already found. fn substring_ids( ctx: &Ctx<'_>, q: &str, ids: Option<&[String]>, status: Option<&str>, ) -> Result, ToolFailure> { let pattern = substring_pattern(q); let mut sql = String::from( "SELECT id FROM cotton_memories WHERE workspace_id = ? \ AND title LIKE ? ESCAPE '\\'", ); let mut params = vec![ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(pattern), ]; if let Some(status) = status { sql.push_str(" AND status = ?"); params.push(SqlValue::Text(status.to_string())); } if let Some(ids) = ids { if ids.is_empty() { return Ok(Vec::new()); } sql.push_str(&format!(" AND id IN ({})", vec!["?"; ids.len()].join(", "))); params.extend(ids.iter().cloned().map(SqlValue::Text)); } let found = ctx .db() .all(&sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string()))?; Ok(found .iter() .filter_map(|row| row.text("id").map(str::to_string)) .collect()) } /// The owner's memory beyond the briefing. With `project`: that project's /// entries, in ITS arrangement — pinned first, then position. Without: every /// entry, newest-first, each carrying the projects it briefs in. pub fn recall(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_recall(args)?; let projects = memory_projects(ctx)?; let project_id = crate::mcp::handlers::common::resolve_project( &refs_of(&projects), args.project.as_deref(), )?; let filters = MemoryFilters { project_id: project_id.clone(), status: (args.status != "all").then(|| args.status.clone()), exclude_archived: false, }; let matcher = args.q.as_deref().and_then(to_match_query); let found: Vec = if let (Some(_), Some(matcher)) = (&args.q, &matcher) { memories_by_fts(ctx, matcher, &filters, args.limit)? } else if let Some(project_id) = &project_id { // The project's list, in the LINK's order; the rows behind it read in // chunks and re-seated in that order — never `ORDER BY created_at`, // which would make the page and the session disagree the first time // the owner dragged something. let links = memory_links( ctx, &LinksBy { project_ids: Some(vec![project_id.clone()]), ..LinksBy::default() }, )?; let ids: Vec = links.iter().map(|link| link.record_id.clone()).collect(); let matching = match &args.q { Some(q) => Some( substring_ids(ctx, q, Some(&ids), filters.status.as_deref())? .into_iter() .collect::>(), ), None => None, }; let by_id: HashMap = in_chunks(&ids, |batch| { let mut query = Query::on("cotton_memories") .columns(MEMORY_COLUMNS) .filter(Filter::In( "id".to_string(), batch.iter().cloned().map(SqlValue::Text).collect(), )); if let Some(status) = &filters.status { query = query.eq("status", status.clone()); } rows(ctx, &query)?.iter().map(MemoryRow::of).collect() })? .into_iter() .filter(|row| matching.as_ref().is_none_or(|ids| ids.contains(&row.id))) .map(|row| (row.id.clone(), row)) .collect(); links .iter() .filter_map(|link| by_id.get(&link.record_id).cloned()) .take(args.limit as usize) .collect() } else { let matching = match &args.q { Some(q) => Some(substring_ids(ctx, q, None, filters.status.as_deref())?), None => None, }; let mut query = Query::on("cotton_memories").columns(MEMORY_COLUMNS); if let Some(status) = &filters.status { query = query.eq("status", status.clone()); } if let Some(matching) = matching { query = query.filter(Filter::In( "id".to_string(), matching.into_iter().map(SqlValue::Text).collect(), )); } let query = query.order_by("created_at", Order::Desc).limit(args.limit); rows(ctx, &query)? .iter() .map(MemoryRow::of) .collect::, _>>()? }; let links = links_by_memory(&memory_links( ctx, &LinksBy { memory_ids: Some(found.iter().map(|row| row.id.clone()).collect()), ..LinksBy::default() }, )?); let mut out = Map::new(); out.insert( "memories".to_string(), Value::Array( found .iter() .map(|row| { memory_out( row, links.get(&row.id).map(Vec::as_slice).unwrap_or(&[]), &projects, ) }) .collect(), ), ); Ok(Value::Object(out)) } // ── remember ──────────────────────────────────────────────────────────────── /// What the reconcile scan reads per entry row. #[derive(Debug, Clone)] struct EntryRow { id: String, slug: String, title: String, status: String, updated_at: String, } fn entry_rows(ctx: &Ctx<'_>) -> Result, ToolFailure> { let query = Query::on("cotton_memories").columns(ENTRY_COLUMNS); Ok(rows(ctx, &query)? .into_iter() .map(|row| EntryRow { id: text(&row, "id").unwrap_or_default(), slug: text(&row, "slug").unwrap_or_default(), title: text(&row, "title").unwrap_or_default(), status: text(&row, "status").unwrap_or_default(), updated_at: text(&row, "updated_at").unwrap_or_default(), }) .collect()) } /// Rule 6: credentials never enter memory. Named refusal, in `lines`' words. fn refuse_secrets(title: Option<&str>, lines: &[LineRow]) -> Result<(), ToolFailure> { let Some(title) = title else { return Ok(()) }; match looks_like_secret(title) { Some(kind) => Err(ToolFailure::new(cotton_core::rules::memory_technical::secret_refusal(kind, lines))), None => Ok(()), } } /// The position a new link lands on: a step past the last link of the /// project's list. 0 sorts FIRST, so a link written at the column's floor /// would put every assistant's transcription at the top of the owner's own /// list. fn next_position(links: &[MemoryLinkRow]) -> f64 { let mut last = 0.0_f64; for link in links { if link.position > last { last = link.position; } } last + cotton_core::rules::memory_order::POSITION_STEP } /// The tail of one project's list — one targeted read. `pub` for /// `link_to_project`, which places a memory the same way `remember` does. pub fn next_memory_position_in(ctx: &Ctx<'_>, project_id: &str) -> Result { Ok(next_position(&memory_links( ctx, &LinksBy { project_ids: Some(vec![project_id.to_string()]), ..LinksBy::default() }, )?)) } /// One link row: the entry joins the project at the tail of its unpinned band /// unless pinned. Idempotent — the id is derived, and a second write of the /// same membership is answered by the row that exists. /// /// The TypeScript passes `ignoreDuplicates: true`; the store has no such /// flag, so this reads THEN skips, which is the same convergence asked of the /// database this server actually has. fn write_memory_link( ctx: &mut Ctx<'_>, project_id: &str, memory_id: &str, pinned: bool, position: Option, ) -> Result<(), ToolFailure> { let id = project_link_id(project_id, "memory", memory_id); if crate::mcp::handlers::common::row_by_id(ctx, "cotton_project_links", &id)?.is_some() { return Ok(()); } let position = match position { Some(position) => position, None => next_memory_position_in(ctx, project_id)?, }; let mut patch = Map::new(); patch.insert("project_id".to_string(), Value::from(project_id)); patch.insert("record_kind".to_string(), Value::from("memory")); patch.insert("record_id".to_string(), Value::from(memory_id)); patch.insert("note".to_string(), Value::Null); patch.insert("applied_by".to_string(), Value::from("agent")); patch.insert("pinned".to_string(), Value::from(pinned)); patch.insert( "position".to_string(), crate::mcp::handlers::common::js_number(position), ); insert_row(ctx, "cotton_project_links", &id, patch) } /// The other direction, for `link_to_project`: an ARCHIVED entry given a home /// is back. `superseded_by` is cleared with the status (the column's CHECK /// pairs them). `pub` for the projects group. pub fn restore_if_archived(ctx: &mut Ctx<'_>, memory_id: &str) -> Result { let row = memory_by_ref( ctx, &MemoryRef { id: Some(memory_id.to_string()), ..MemoryRef::default() }, )?; if row.status != "archived" { return Ok(false); } let mut patch = Map::new(); patch.insert("status".to_string(), Value::from("active")); patch.insert("archived_at".to_string(), Value::Null); patch.insert("superseded_by".to_string(), Value::Null); update_row(ctx, "cotton_memories", &row.id, patch)?; Ok(true) } /// Words worth matching on: four letters or more, so "the" and "a" do not /// make every entry a candidate for every other. fn significant_tokens(title: &str) -> Vec { let mut seen: Vec = Vec::new(); for token in title .to_lowercase() .split(|ch: char| !ch.is_ascii_alphanumeric()) .filter(|token| token.len() >= 4) { if !seen.iter().any(|held| held == token) { seen.push(token.to_string()); } } seen } /// The reconcile step's candidate set, WORKSPACE-WIDE: FTS top-8 on the title /// ∪ titles at or above the similarity threshold, over live rows. One /// sentence lives once and briefs in many projects, so a candidate in another /// project is a candidate. fn candidates_for( ctx: &Ctx<'_>, entries: &[EntryRow], title: &str, ) -> Result, ToolFailure> { let mut by_slug: Vec<(EntryRow, f64)> = Vec::new(); for row in entries.iter().filter(|row| row.status != "archived") { let similarity = title_similarity(title, &row.title); if similarity >= MEMORY_SIMILARITY_THRESHOLD { by_slug.push((row.clone(), similarity)); } } let tokens = significant_tokens(title); if !tokens.is_empty() { let needed = std::cmp::min(2, tokens.len()); let matcher = tokens .iter() .map(|token| format!("\"{token}\"")) .collect::>() .join(" OR "); // Archived rows are filtered inside the query: the LIMIT must fall on // live rows, or a pile of archived look-alikes crowds the real // candidate out of the window. A malformed match must not refuse the // write; similarity alone stands. let hits = memories_by_fts( ctx, &matcher, &MemoryFilters { exclude_archived: true, ..MemoryFilters::default() }, CANDIDATE_FTS_LIMIT, ) .unwrap_or_default(); for hit in hits { if by_slug.iter().any(|(row, _)| row.slug == hit.slug) { continue; } let shared = significant_tokens(&hit.title) .into_iter() .filter(|token| tokens.contains(token)) .count(); if shared < needed { continue; } let Some(row) = entries.iter().find(|row| row.slug == hit.slug) else { continue; }; let similarity = title_similarity(title, &hit.title); by_slug.push((row.clone(), similarity)); } } by_slug.sort_by(|a, b| b.1.total_cmp(&a.1)); Ok(by_slug) } pub fn remember(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let lines = crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id); let args = validate_remember(args, &lines)?; refuse_secrets(Some(&args.title), &lines)?; if let Some(mark) = technical_mark(&args.title, args.machine.is_some()) { return Err(ToolFailure::new(technical_refusal(mark, &lines))); } let projects = memory_projects(ctx)?; // An entry briefs in its project, or — with none, in the personal // database only — in the Owner section that opens every brief. let project_id = match &args.project { Some(slug) => { let Some(project_id) = crate::mcp::handlers::common::resolve_project( &refs_of(&projects), Some(slug.as_str()), )? else { return Err(ToolFailure::new( "project is required — list_projects names them; a memory briefs in its projects", )); }; Some(project_id) } None if ctx.file_kind()? == cotton_store::link_rule::FileKind::Shared => { return Err(ToolFailure::new( "project is required here — a memory briefs in its projects. An entry about the \ owner whatever the project lives in their personal database: call again with \ database set to it and no project.", )); } None => None, }; let said_where = |out: &mut Map| match &args.project { Some(project) => { out.insert("project".to_string(), Value::from(project.clone())); } None => { out.insert("owner".to_string(), Value::from(true)); } }; let stamp = now_iso(ctx); let entries = entry_rows(ctx)?; if args.decision.is_none() { let candidates = candidates_for(ctx, &entries, &args.title)?; if let Some((row, _)) = candidates .iter() .find(|(_, similarity)| *similarity >= MEMORY_NOOP_THRESHOLD) { // The sentence exists. If it already briefs in this project, // nothing to do; if not, the project gains the link — not a // duplicate, not a no-op. let homes = memory_links( ctx, &LinksBy { memory_ids: Some(vec![row.id.clone()]), ..LinksBy::default() }, )?; let mut existing = Map::new(); existing.insert("slug".to_string(), Value::from(row.slug.clone())); existing.insert("title".to_string(), Value::from(row.title.clone())); // An Owner entry is in this file already: there is nothing to link. let Some(project_id) = &project_id else { let mut out = Map::new(); out.insert("action".to_string(), Value::from("noop")); out.insert("existing".to_string(), Value::Object(existing)); out.insert( "note".to_string(), Value::from( "an entry already says this — nothing written; memory_update it if the \ wording should change", ), ); return Ok(Value::Object(out)); }; if homes.iter().any(|link| &link.project_id == project_id) { let mut out = Map::new(); out.insert("action".to_string(), Value::from("noop")); out.insert("existing".to_string(), Value::Object(existing)); out.insert( "note".to_string(), Value::from( "an entry already says this — nothing written; memory_update it if the \ wording should change", ), ); return Ok(Value::Object(out)); } let machine = machine_of(ctx, &row.id)?; refuse_over_budget( ctx, std::slice::from_ref(project_id), machine.as_deref(), |entries| { entries.push(priced_entry( &row.slug, &row.title, args.pinned.unwrap_or(false), machine.clone(), )); }, )?; write_memory_link(ctx, project_id, &row.id, args.pinned.unwrap_or(false), None)?; ctx.commit()?; let mut out = Map::new(); out.insert("action".to_string(), Value::from("linked")); out.insert("slug".to_string(), Value::from(row.slug.clone())); said_where(&mut out); out.insert("existing".to_string(), Value::Object(existing)); out.insert( "note".to_string(), Value::from(format!( "an entry already says this — it now briefs in {} too; nothing else was \ written", args.project.as_deref().unwrap_or_default() )), ); return Ok(Value::Object(out)); } if !candidates.is_empty() { let homes = links_by_memory(&memory_links( ctx, &LinksBy { memory_ids: Some(candidates.iter().map(|(row, _)| row.id.clone()).collect()), ..LinksBy::default() }, )?); let mut out = Map::new(); out.insert("needsDecision".to_string(), Value::from(true)); out.insert( "candidates".to_string(), Value::Array( candidates .iter() .map(|(row, _)| { let mut candidate = Map::new(); candidate.insert("slug".to_string(), Value::from(row.slug.clone())); candidate.insert("title".to_string(), Value::from(row.title.clone())); candidate.insert( "updatedAt".to_string(), Value::from(row.updated_at.clone()), ); candidate.insert( "projects".to_string(), Value::Array(memory_home_slugs( homes.get(&row.id).map(Vec::as_slice).unwrap_or(&[]), &projects, )), ); Value::Object(candidate) }) .collect(), ), ); out.insert( "hint".to_string(), Value::from( "similar entries exist — nothing was written. Read them and call again with \ decision: { action: \"update\", target: } to correct one, { action: \ \"supersede\", target: } when this fact replaces it, or { action: \ \"add\" } when it is genuinely different.", ), ); return Ok(Value::Object(out)); } } else if args.decision.as_ref().is_some_and(|d| d.action == "noop") { let mut out = Map::new(); out.insert("action".to_string(), Value::from("noop")); out.insert( "note".to_string(), Value::from("nothing written, as decided"), ); return Ok(Value::Object(out)); } if let Some(decision) = args.decision.as_ref().filter(|d| d.action == "update") { let target = entries .iter() .find(|row| Some(&row.slug) == decision.target.as_ref() && row.status != "archived") .ok_or_else(|| { ToolFailure::new(format!( "no live entry with slug {} to update — recall to find it, or decide add", quoted(decision.target.as_deref().unwrap_or_default()) )) })? .clone(); let homes = home_project_ids(ctx, &target.id)?; refuse_over_budget( ctx, &homes, machine_of(ctx, &target.id)?.as_deref(), |entries| { for entry in entries.iter_mut().filter(|entry| entry.slug == target.slug) { entry.title = args.title.clone(); } }, )?; refuse_owner_over_cap(ctx, |entries| { for entry in entries.iter_mut().filter(|entry| entry.slug == target.slug) { entry.title = args.title.clone(); } })?; let mut patch = Map::new(); patch.insert("title".to_string(), Value::from(args.title.clone())); if let Some(source) = &args.source { patch.insert("source".to_string(), Value::from(source.clone())); } update_row(ctx, "cotton_memories", &target.id, patch)?; ctx.commit()?; let mut out = Map::new(); out.insert("action".to_string(), Value::from("update")); out.insert("slug".to_string(), Value::from(target.slug.clone())); out.insert( "note".to_string(), Value::from("the prior state is version-snapshotted"), ); return Ok(Value::Object(out)); } let mut superseding: Option = None; if let Some(decision) = args.decision.as_ref().filter(|d| d.action == "supersede") { superseding = entries .iter() .find(|row| Some(&row.slug) == decision.target.as_ref() && row.status != "archived") .cloned(); if superseding.is_none() { return Err(ToolFailure::new(format!( "no live entry with slug {} to supersede — recall to find it, or decide add", quoted(decision.target.as_deref().unwrap_or_default()) ))); } } let taken: std::collections::BTreeSet = entries.iter().map(|row| row.slug.clone()).collect(); let slug = match &args.slug { Some(slug) => { if taken.contains(slug) { return Err(ToolFailure::new(format!( "slug {} already exists — decide update or supersede against it, or omit slug \ to mint a fresh one", quoted(slug) ))); } slug.clone() } None => mint_memory_slug(&args.title, &taken), }; let priced = |entries: &mut Vec| { if let Some(superseding) = &superseding { entries.retain(|entry| entry.slug != superseding.slug); } entries.push(priced_entry( &slug, &args.title, args.pinned.unwrap_or(false), args.machine.clone(), )); }; match &project_id { Some(project_id) => refuse_over_budget( ctx, std::slice::from_ref(project_id), args.machine.as_deref(), priced, )?, None => refuse_owner_over_cap(ctx, priced)?, } // Every agent write lands LIVE: a ruling given mid-session must bind the // next session now. // Derived from (workspace, slug) — `idx_cotton_memories_slug` is unique per // workspace, so two files merging on the same slug have to be ONE entry. let id = memory_id(ctx.file.namespace(), &slug); let mut patch = Map::new(); patch.insert("slug".to_string(), Value::from(slug.clone())); patch.insert("title".to_string(), Value::from(args.title.clone())); // The sentence is the memory; the column stays until the format freeze. patch.insert("body".to_string(), Value::from("")); patch.insert("status".to_string(), Value::from("active")); patch.insert("machine".to_string(), or_null(args.machine.clone())); patch.insert("visibility".to_string(), Value::from("private")); patch.insert("origin_kind".to_string(), Value::from("agent")); patch.insert("origin_label".to_string(), Value::from(ctx.agent)); patch.insert("source".to_string(), or_null(args.source.clone())); patch.insert("source_external_id".to_string(), Value::Null); patch.insert("superseded_by".to_string(), Value::Null); patch.insert("archived_at".to_string(), Value::Null); insert_row(ctx, "cotton_memories", &id, patch)?; // The home: the tail of THIS project's list (pinned, when asked). The // link's position is read BEFORE the entry lands, which is the same order // the TypeScript's awaits give. if let Some(project_id) = &project_id { write_memory_link(ctx, project_id, &id, args.pinned.unwrap_or(false), None)?; } if let Some(superseding) = &superseding { // The old fact closes pointing at the new one — in ONE patch, because // the column's CHECK pairs the successor with the archived status. Its // links stay: an archived entry keeps its homes. let mut patch = Map::new(); patch.insert("status".to_string(), Value::from("archived")); patch.insert("archived_at".to_string(), Value::from(stamp.clone())); patch.insert("superseded_by".to_string(), Value::from(id.clone())); update_row(ctx, "cotton_memories", &superseding.id, patch)?; } ctx.commit()?; let mut out = Map::new(); if let Some(superseding) = &superseding { out.insert("action".to_string(), Value::from("supersede")); out.insert("slug".to_string(), Value::from(slug)); said_where(&mut out); out.insert( "superseded".to_string(), Value::from(superseding.slug.clone()), ); out.insert("status".to_string(), Value::from("active")); return Ok(Value::Object(out)); } out.insert("action".to_string(), Value::from("add")); out.insert("slug".to_string(), Value::from(slug)); said_where(&mut out); out.insert("status".to_string(), Value::from("active")); out.insert( "note".to_string(), Value::from("live in the next briefing"), ); Ok(Value::Object(out)) } // ── memory_update ─────────────────────────────────────────────────────────── /// The one link a pin or a reorder addresses, or the refusal that names how /// to make one. fn link_for( ctx: &Ctx<'_>, row: &MemoryRow, project_id: &str, project_slug: &str, ) -> Result { memory_links( ctx, &LinksBy { memory_ids: Some(vec![row.id.clone()]), project_ids: Some(vec![project_id.to_string()]), }, )? .into_iter() .next() .ok_or_else(|| { ToolFailure::new(format!( "[{}] is not linked to {project_slug} — link_to_project {{ project: \ \"{project_slug}\", records: [{{ kind: \"memory\", id: \"{}\" }}] }} first", row.slug, row.id )) }) } pub fn memory_update(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let lines = crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id); let args = validate_memory_update(args, &lines)?; refuse_secrets(args.title.as_deref(), &lines)?; let row = memory_by_ref(ctx, &args.reference)?; // The machine the entry will brief on after this call: a `machine` key // moves it, `null` unscopes it, absence keeps what it has. let machine_after: Option = match &args.machine { Some(Value::String(machine)) => Some(machine.clone()), Some(_) => None, None => row.machine.clone(), }; if let Some(title) = &args.title { if let Some(mark) = technical_mark(title, machine_after.is_some()) { return Err(ToolFailure::new(technical_refusal(mark, &lines))); } } if args.title.is_some() || args.machine.is_some() { let homes = home_project_ids(ctx, &row.id)?; let title_after = args.title.clone().unwrap_or_else(|| row.title.clone()); refuse_over_budget(ctx, &homes, machine_after.as_deref(), |entries| { for entry in entries.iter_mut().filter(|entry| entry.slug == row.slug) { entry.title = title_after.clone(); entry.machine = machine_after.clone(); } })?; refuse_owner_over_cap(ctx, |entries| { for entry in entries.iter_mut().filter(|entry| entry.slug == row.slug) { entry.title = title_after.clone(); } })?; } let mut update = Map::new(); if let Some(title) = &args.title { update.insert("title".to_string(), Value::from(title.clone())); } if let Some(source) = &args.source { update.insert("source".to_string(), Value::from(source.clone())); } if let Some(machine) = &args.machine { update.insert("machine".to_string(), machine.clone()); } let touched = !update.is_empty(); if touched { update_row(ctx, "cotton_memories", &row.id, update)?; } // Pinning is PER PROJECT — it is the link's: the entry's row is left // alone when the pin is the whole change. if let Some(pinned) = args.pinned { let projects = memory_projects(ctx)?; let Some(project_id) = crate::mcp::handlers::common::resolve_project( &refs_of(&projects), args.reference.project.as_deref(), )? else { return Err(ToolFailure::new( "pinned is per project — pass project to say which of the entry's projects pins it", )); }; let slug = args.reference.project.clone().unwrap_or_default(); let link = link_for(ctx, &row, &project_id, &slug)?; if link.pinned != pinned { let mut patch = Map::new(); patch.insert("pinned".to_string(), Value::from(pinned)); update_row(ctx, "cotton_project_links", &link.id, patch)?; } } ctx.commit()?; let mut out = Map::new(); out.insert("updated".to_string(), Value::from(true)); out.insert("slug".to_string(), Value::from(row.slug.clone())); out.insert( "note".to_string(), Value::from(if touched { "the prior state is version-snapshotted".to_string() } else { format!( "pinned {} {} — the arrangement is that project's; nothing else changed", if args.pinned == Some(true) { "in" } else { "off in" }, args.reference.project.as_deref().unwrap_or("undefined") ) }), ); Ok(Value::Object(out)) } // ── memory_archive ────────────────────────────────────────────────────────── pub fn memory_archive(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_memory_archive(args)?; let row = memory_by_ref(ctx, &args.reference)?; archive_memory_row(ctx, &row, args.reason.as_deref()) } /// Archive EVERYWHERE, keeping the links: the entry leaves every briefing, /// and un-archiving it restores its homes. fn archive_memory_row( ctx: &mut Ctx<'_>, row: &MemoryRow, reason: Option<&str>, ) -> Result { let mut patch = Map::new(); patch.insert("status".to_string(), Value::from("archived")); patch.insert("archived_at".to_string(), Value::from(now_iso(ctx))); update_row(ctx, "cotton_memories", &row.id, patch)?; ctx.commit()?; // The reason lands ON the entry, as this assistant, so the owner's memory // says who retired it and why — same trail as every agent write. A failed // comment is LOGGED, never raised: the archive already happened, and // failing the call would report an archive that did not. if let Some(reason) = reason { let id = ctx.new_uuid(); let mut comment = Map::new(); comment.insert("record_kind".to_string(), Value::from("memory")); comment.insert("record_id".to_string(), Value::from(row.id.clone())); comment.insert( "body".to_string(), Value::from(format!("Archived: {reason}")), ); comment.insert("author_kind".to_string(), Value::from("agent")); comment.insert("author_label".to_string(), Value::from(ctx.agent)); // RESOLVED AT BIRTH. An open root comment by an agent is what Home // counts as an assistant asking the owner something, and "Archived: // why" asks nothing — it is a record of what was done (design note // d0e27772: Cotton asks only what only the owner knows). The owner // still reads it on the entry, and restoring the entry is the undo. let now = now_iso(ctx); comment.insert("resolved_at".to_string(), Value::from(now)); comment.insert("resolved_by_kind".to_string(), Value::from("agent")); comment.insert("resolved_by_label".to_string(), Value::from(ctx.agent)); let wrote = insert_row(ctx, "cotton_comments", &id, comment).and_then(|()| ctx.commit()); if let Err(error) = wrote { tracing::error!("memory archive comment failed: {}", error.message()); } } let mut out = Map::new(); out.insert("archived".to_string(), Value::from(true)); out.insert("slug".to_string(), Value::from(row.slug.clone())); Ok(Value::Object(out)) } // ── memory_reorder ────────────────────────────────────────────────────────── /// Move ONE entry in the owner's own order FOR ONE PROJECT. `after` names the /// entry it should follow, `before` the entry it should precede, neither /// means the head. /// /// The slot is the gap between the named neighbour and ITS neighbour, which /// is why this reads the band rather than just the one link. The band is the /// project's list and the link's own pinned state; a move never crosses the /// pinned line. When the gap is exhausted this REFUSES: renumbering the band /// would be one op per row in a log that is forever, on a device that is not /// the one the owner is looking at. pub fn memory_reorder(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_memory_reorder(args)?; let target = memory_by_ref(ctx, &args.reference)?; let projects = memory_projects(ctx)?; let slug = args.reference.project.clone().unwrap_or_default(); let Some(project_id) = crate::mcp::handlers::common::resolve_project(&refs_of(&projects), Some(slug.as_str()))? else { return Err(ToolFailure::new( "project is required — the order is the project's, and one entry is arranged per \ project", )); }; let target_link = link_for(ctx, &target, &project_id, &slug)?; // The band: this project's links, minus archived or non-private entries, // in the ONE comparator every reader uses — re-deriving it in SQL is how // a rail and a list come to disagree. let links = memory_links( ctx, &LinksBy { project_ids: Some(vec![project_id.clone()]), ..LinksBy::default() }, )?; let ids: Vec = links.iter().map(|link| link.record_id.clone()).collect(); let slug_by_id: BTreeMap = in_chunks(&ids, |batch| { let query = Query::on("cotton_memories") .columns(&["id", "slug"]) .eq("visibility", "private".to_string()) .filter(Filter::Ne( "status".to_string(), SqlValue::Text("archived".to_string()), )) .filter(Filter::In( "id".to_string(), batch.iter().cloned().map(SqlValue::Text).collect(), )); Ok(rows(ctx, &query)? .into_iter() .filter_map(|row| Some((text(&row, "id")?, text(&row, "slug")?))) .collect::>()) })? .into_iter() .collect(); let mut band: Vec<(MemoryLinkRow, String)> = links .iter() .filter(|link| { slug_by_id.contains_key(&link.record_id) && link.pinned == target_link.pinned && link.record_id != target.id }) .filter_map(|link| { slug_by_id .get(&link.record_id) .map(|slug| (link.clone(), slug.clone())) }) .collect(); band.sort_by(|x, y| { position_order( &Positioned { pinned: x.0.pinned, position: x.0.position, slug: x.1.clone(), }, &Positioned { pinned: y.0.pinned, position: y.0.position, slug: y.1.clone(), }, ) }); // The slot is the GAP between the named neighbour and ITS neighbour: // `{ after: "a" }` in a=1000, b=2000 must land at 1500, not at 2000, or // the move is a no-op that looks like it worked. let anchor = args.after.as_ref().or(args.before.as_ref()); let (lower, upper): (Option, Option) = match anchor { None => (None, band.first().map(|entry| entry.0.position)), Some(anchor) => { let Some(at) = band.iter().position(|entry| entry.1 == *anchor) else { return Err(ToolFailure::new(format!( "no memory entry with slug \"{anchor}\" in {slug}'s list — reorder is within \ one project's entries" ))); }; if args.after.is_some() { ( Some(band[at].0.position), band.get(at + 1).map(|entry| entry.0.position), ) } else { ( at.checked_sub(1) .and_then(|index| band.get(index)) .map(|entry| entry.0.position), Some(band[at].0.position), ) } } }; let Some(position) = position_between(lower, upper) else { return Err(ToolFailure::new( "those two entries are adjacent with no room between them — reorder against a \ different neighbour, or ask the owner to arrange this list in the app", )); }; let mut patch = Map::new(); patch.insert( "position".to_string(), crate::mcp::handlers::common::js_number(position), ); update_row(ctx, "cotton_project_links", &target_link.id, patch)?; ctx.commit()?; let mut out = Map::new(); out.insert("slug".to_string(), Value::from(target.slug)); out.insert("project".to_string(), Value::from(slug)); out.insert( "position".to_string(), crate::mcp::handlers::common::js_number(position), ); Ok(Value::Object(out)) } // ── the validators ────────────────────────────────────────────────────────── /// `MEMORY_SLUG_RE` — `^[a-z0-9][a-z0-9-]{0,63}$`, as a check rather than a /// regex. fn is_memory_slug(value: &str) -> bool { let bytes = value.as_bytes(); if bytes.is_empty() || bytes.len() > 64 { return false; } if !(bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit()) { return false; } bytes[1..] .iter() .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-') } const MEMORY_LIST_STATUSES: &[&str] = &["active", "archived", "all"]; const REMEMBER_ACTIONS: &[&str] = &["add", "update", "supersede", "noop"]; /// How an entry is addressed. `project` names the LINK a pin or a reorder /// applies to, never a disambiguator — one slug per workspace since v35. #[derive(Debug, Clone, Default)] pub struct MemoryRef { pub id: Option, pub slug: Option, pub project: Option, } fn memory_ref(args: &Map) -> Valid { let id = optional_string(args, "id"); let slug = optional_string(args, "slug"); let mut project = optional_string(args, "project"); // A generic Settings row is addressed by its project membership // (`project/`), because that is where pin and position live. The // memory engine still writes the durable uuid, while retaining the project // as the default for per-project acts. let id = id.map(|id| match id.split_once('/') { Some((scoped_project, memory)) if is_uuid(memory) => { if let Some(named) = project.as_deref().filter(|named| *named != scoped_project) { return Err(ToolFailure::new(format!( "the entry id belongs to project {scoped_project}, not {named}" ))); } project.get_or_insert_with(|| scoped_project.to_string()); Ok(memory.to_string()) } _ => Ok(id), }).transpose()?; if let Some(id) = &id { if !is_uuid(id) { return fail("id must be a uuid"); } } if id.is_none() && slug.is_none() { return fail("address the entry by slug or id"); } Ok(MemoryRef { id, slug, project }) } #[derive(Debug, Clone)] pub struct BriefArgs { pub repo_url: Option, pub project: Option, pub machine: Option, pub budget_tokens: Option, } fn validate_brief(args: &Map) -> Valid { let budget_tokens = match args.get("budgetTokens") { None | Some(Value::Null) => None, Some(value) => match value.as_f64().filter(|value| value.is_finite()) { Some(value) => Some(value.trunc().clamp(400.0, 6000.0) as usize), None => return fail("budgetTokens must be a number"), }, }; Ok(BriefArgs { repo_url: optional_string(args, "repoUrl"), project: optional_string(args, "project"), machine: optional_string(args, "machine"), budget_tokens, }) } #[derive(Debug, Clone)] pub struct RecallArgs { pub status: String, pub limit: i64, pub project: Option, pub q: Option, } fn validate_recall(args: &Map) -> Valid { for key in args.keys() { if !["q", "project", "status", "limit"].contains(&key.as_str()) { return fail(format!("unknown recall argument: {key}")); } } let status = match args.get("status") { None => "active".to_string(), Some(Value::String(value)) if MEMORY_LIST_STATUSES.contains(&value.as_str()) => { value.clone() } Some(_) => { return fail(format!( "status must be one of {}", MEMORY_LIST_STATUSES.join(", ") )) } }; Ok(RecallArgs { status, limit: crate::mcp::handlers::common::bounded_limit(args, 100, 300), project: optional_string(args, "project"), q: optional_string(args, "q"), }) } #[derive(Debug, Clone)] pub struct RememberDecision { pub action: String, pub target: Option, } #[derive(Debug, Clone)] pub struct RememberArgs { pub title: String, /// `None`: an Owner entry — the personal database's own, briefing in no /// project but first in every brief. pub project: Option, pub source: Option, pub pinned: Option, pub machine: Option, pub slug: Option, pub decision: Option, } fn validate_remember(args: &Map, lines: &[LineRow]) -> Valid { let Some(title) = crate::mcp::handlers::common::require_string(args, "title") else { return fail("title is required"); }; if title.chars().count() > MEMORY_TITLE_MAX { return fail(format!( "the sentence IS the memory — at most {MEMORY_TITLE_MAX} characters; a longer thought \ is several thoughts, split it into separate calls" )); } // The body left the product. Refused rather than dropped: a caller that // sent depth must learn where it goes. if args.contains_key("body") { return fail(RetiredField::Body.say(lines)); } if args.contains_key("kind") || args.contains_key("layer") { return fail(RetiredField::Taxonomy.say(lines)); } // The flag left the file at schema v34. Refused rather than dropped, for // the same reason `body` is: a caller that sent it believes the entry is // marked temporary, and a silent drop leaves it believing that for ever. if args.contains_key("dated") { return fail(RetiredField::Dated.say(lines)); } let slug = optional_string(args, "slug"); if let Some(slug) = &slug { if !is_memory_slug(slug) { return fail("slug must be kebab-case, ≤64 chars"); } } match args.get("pinned") { None | Some(Value::Bool(_)) => {} Some(_) => return fail("pinned must be a boolean"), } let mut decision: Option = None; match args.get("decision") { None => { // `remember`'s `force` — "create even though a similar entry // exists" — is exactly decision.add. if args.get("force") == Some(&Value::Bool(true)) { decision = Some(RememberDecision { action: "add".to_string(), target: None, }); } } Some(Value::Object(raw)) => { let action = match raw.get("action").and_then(Value::as_str) { Some(action) if REMEMBER_ACTIONS.contains(&action) => action.to_string(), _ => { return fail(format!( "decision.action must be one of {}", REMEMBER_ACTIONS.join(", ") )) } }; let target = optional_string(raw, "target"); if (action == "update" || action == "supersede") && target.is_none() { return fail(format!( "decision.{action} needs target — the candidate's slug" )); } decision = Some(RememberDecision { action, target }); } Some(_) => return fail("decision must be an object { action, target? }"), } match args.get("owner") { None | Some(Value::Bool(_)) => {} Some(_) => return fail("owner must be a boolean"), } let project = optional_string(args, "project"); if project.is_some() && args.get("owner") == Some(&Value::Bool(true)) { return fail( "owner: true is an entry with no project — the Owner section of every brief; pass \ project or owner, not both", ); } Ok(RememberArgs { title, project, source: optional_string(args, "source"), pinned: args.get("pinned").and_then(Value::as_bool), machine: optional_string(args, "machine"), slug, decision, }) } #[derive(Debug, Clone)] pub struct MemoryUpdateArgs { pub reference: MemoryRef, pub title: Option, pub source: Option, /// `Some(Value::Null)` clears it — the TypeScript's explicit `null`. pub machine: Option, pub pinned: Option, } fn validate_memory_update(args: &Map, lines: &[LineRow]) -> Valid { let reference = memory_ref(args)?; let mut out = MemoryUpdateArgs { reference, title: None, source: None, machine: None, pinned: None, }; let title = optional_string(args, "title"); if let Some(title) = title { if title.chars().count() > MEMORY_TITLE_MAX { return fail(format!( "the title IS the entry — at most {MEMORY_TITLE_MAX} characters" )); } out.title = Some(title); } if args.contains_key("body") { return fail(RetiredField::Body.say(lines)); } // Before every other check, so a call whose ONLY field is a retired // category is told what happened to the category rather than "send at // least one field to change" — a true sentence that answers a question // nobody asked. if args.contains_key("kind") || args.contains_key("layer") { return fail(RetiredField::Taxonomy.say(lines)); } if args.contains_key("dated") { return fail(RetiredField::Dated.say(lines)); } if let Some(source) = optional_string(args, "source") { out.source = Some(source); } match args.get("machine") { None => {} Some(Value::Null) => out.machine = Some(Value::Null), Some(Value::String(machine)) => { let trimmed = machine.trim(); out.machine = Some(if trimmed.is_empty() { Value::Null } else { Value::from(trimmed) }); } Some(_) => return fail("machine must be a hostname or null"), } match args.get("pinned") { None => {} Some(Value::Bool(pinned)) => { // Per project: a pin with no project is a question with no answer // — the entry may brief in several lists, and "pinned" names one. if out.reference.project.is_none() { return fail( "pinned is per project — pass project to say which of the entry's projects \ pins it", ); } out.pinned = Some(*pinned); } Some(_) => return fail("pinned must be a boolean"), } // Re-homing left this tool with the memory-home change: an entry's projects are its // links, edited with link_to_project / unlink_from_project like any // record. if args.contains_key("moveToProject") { return fail( "moveToProject is gone — a memory's projects are links: link_to_project { project, \ records: [{ kind: \"memory\", id }] } adds one, unlink_from_project removes one", ); } if out.title.is_none() && out.source.is_none() && out.machine.is_none() && out.pinned.is_none() { return fail("send at least one field to change"); } Ok(out) } #[derive(Debug, Clone)] pub struct MemoryReorderArgs { pub reference: MemoryRef, pub before: Option, pub after: Option, } fn validate_memory_reorder(args: &Map) -> Valid { let reference = memory_ref(args)?; // `optional_string` normalises an empty or whitespace-only value to // absent, so a client that sends `before: ""` alongside a real `after` is // asking for one neighbour, not two. let before = optional_string(args, "before"); let after = optional_string(args, "after"); if before.is_some() && after.is_some() { // Two neighbours is two different requests. Refusing is the only // honest answer: silently preferring one would put the entry // somewhere the assistant did not ask for, in the owner's own // arrangement. return fail("give before or after, not both"); } if reference.project.is_none() { return fail( "project is required — the order is the project's; say which list is being arranged", ); } Ok(MemoryReorderArgs { reference, before, after, }) } #[derive(Debug, Clone)] pub struct MemoryArchiveArgs { pub reference: MemoryRef, pub reason: Option, } fn validate_memory_archive(args: &Map) -> Valid { Ok(MemoryArchiveArgs { reference: memory_ref(args)?, reason: optional_string(args, "reason"), }) } #[cfg(test)] mod current_format_tests { use super::*; #[test] fn a_settings_memory_identity_keeps_its_project_for_per_project_actions() { // RULE: A Settings row is a project membership, while the writer uses // the durable memory uuid. Commands must not lose the project when // pinning or arranging the row. let mut args = Map::new(); args.insert( "id".into(), Value::from("garden/56a18d98-db49-4e3d-8446-37d8afb48bc2"), ); let reference = memory_ref(&args).expect("scoped generic id"); assert_eq!(reference.id.as_deref(), Some("56a18d98-db49-4e3d-8446-37d8afb48bc2")); assert_eq!(reference.project.as_deref(), Some("garden")); } // RULE: Missing columns and old enum values are errors, never empty strings or active/user defaults that change what an assistant is told. #[test] fn memory_rows_require_the_current_fields_and_enums() { let value = serde_json::json!({ "id": "m", "slug": "synthetic", "title": "Synthetic sentence", "status": "active", "visibility": "private", "origin_kind": "user", "created_at": "2026-10-03", "updated_at": "2026-10-03" }); let row = value.as_object().unwrap(); assert!(MemoryRow::of(row).is_ok()); for field in [ "id", "slug", "title", "status", "visibility", "origin_kind", "created_at", "updated_at", ] { let mut missing = row.clone(); missing.remove(field); assert!(MemoryRow::of(&missing).is_err(), "{field}"); } for (field, old) in [("status", "proposed"), ("origin_kind", "unknown")] { let mut old_row = row.clone(); old_row.insert(field.into(), Value::from(old)); assert!(MemoryRow::of(&old_row).is_err()); } } }