//! Three pieces of another package that this group needs and that package does //! not have yet. Each names its PERMANENT HOME; move it there rather than //! writing a second copy. //! //! PROJECT_KIND_TABLES belongs in `cotton_core::services::projects` — the //! port of `packages/core/src/services/projects.service.ts`. It is the ONE //! fact this reader and the app's project page genuinely share (R46): two //! hand-written copies of a table name is how one reader ends up answering //! with nothing. //! //! MEETING_TITLE belongs in `handlers::records_2::meetings`, which owns the //! meeting tools and has its own copy. It is here so this group COMPILES ON //! ITS OWN — a handler group that cannot build without a sibling group's //! uncommitted file is a commit nobody can bisect. Delete this one and import //! theirs the moment both are on `main`. //! //! THE MEMORY WRITERS (`next_memory_position_in`, `memories_orphaned_by`, //! `restore_if_archived`) belong in `handlers::records_2::memory` — they are //! `records.ts`'s, exported there for `projects.ts` exactly as they are //! borrowed here. An entry ALWAYS has a project: an unlink that would leave //! one with none is REFUSED rather than archived (`memories_orphaned_by`), //! and an ARCHIVED entry given a home is back. use cotton_core::constants::ProjectLinkKind; use serde_json::{Map, Value}; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::{maybe_row, rows, text, update_row}; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::{Filter, Order, Query}; // ── core's project-kind registry ──────────────────────────────────────────── /// The row discriminator a kind is narrowed by, when it shares its table. /// /// Both forms are one column and one comparison on purpose: a general SQL /// fragment here would be a second query language for whoever adds the next /// kind. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ProjectKindFilter { /// `column = value`. Equals(&'static str, &'static str), /// `column IS NULL` — "a report is a ROOT" is not a value. IsNull(&'static str), /// `column = value AND other IS NULL` — a note is a `note` row that is /// not in the bin, on the table it shares with the journal. EqualsAndNull(&'static str, &'static str, &'static str), } impl ProjectKindFilter { /// The discriminator: the column a kind sharing its table is told by. pub fn column(self) -> &'static str { match self { ProjectKindFilter::Equals(column, _) | ProjectKindFilter::IsNull(column) | ProjectKindFilter::EqualsAndNull(column, _, _) => column, } } /// Every column the filter reads — what a read must select for the /// filter to be asked of its rows at all. pub fn columns(self) -> Vec<&'static str> { match self { ProjectKindFilter::Equals(column, _) | ProjectKindFilter::IsNull(column) => vec![column], ProjectKindFilter::EqualsAndNull(column, _, other) => vec![column, other], } } } pub struct ProjectKindTable { pub table: &'static str, pub where_clause: Option, } /// Where each linkable kind's rows live. Exhaustive over [`ProjectLinkKind`], /// which is the totality the TypeScript asserts at module load. pub const fn project_kind_table(kind: ProjectLinkKind) -> ProjectKindTable { use ProjectLinkKind::*; let (table, where_clause) = match kind { Thread => ("cotton_msg_threads", None), EmailThread => ("cotton_email_threads", None), Person => ("cotton_people", None), // The notes out of the bin: a binned note is deleted, waiting. Note => ( "cotton_notes", Some(ProjectKindFilter::EqualsAndNull("kind", "note", "trashed_at")), ), Journal => ( "cotton_notes", Some(ProjectKindFilter::Equals("kind", "journal")), ), // The todos out of the bin. Todo => ("cotton_todos", Some(ProjectKindFilter::IsNull("trashed_at"))), // The events out of the bin: a binned event is deleted, waiting. Event => ( "cotton_events", Some(ProjectKindFilter::IsNull("trashed_at")), ), // The documents out of the bin. Document => ( "cotton_documents", Some(ProjectKindFilter::IsNull("trashed_at")), ), Transaction => ("cotton_money_transactions", None), // Photos and videos (v31): the ones out of the bin. Photo => ( "cotton_photos", Some(ProjectKindFilter::IsNull("trashed_at")), ), Video => ( "cotton_videos", Some(ProjectKindFilter::IsNull("trashed_at")), ), // Albums (v42): a dismissed album is a tombstone the pass compares // against, never a member a page shows — the person declined it. Album => ( "cotton_media_albums", Some(ProjectKindFilter::Equals("state", "kept")), ), // Memory (v34): ACTIVE entries only. A dropped entry keeps its links so // restoring it restores its homes, but it is not a member a page or a // briefing shows. Memory => ( "cotton_memories", Some(ProjectKindFilter::Equals("status", "active")), ), Call => ("cotton_call_log", None), // A password (v6 of the Rust ladder): the LIVE ones. A secret in the // bin is still sealed and still a row, and a project page listing it // would be listing something the person has already removed. Secret => ( "cotton_secrets", Some(ProjectKindFilter::IsNull("trashed_at")), ), // A repository (v19). No filter: a repository the file holds is a // member of the project that named it, held or not — "origin Forgejo, // not held yet" is a state the page prints rather than a row it hides. Repository => ("cotton_repos", None), }; ProjectKindTable { table, where_clause, } } /// Does one already-read row satisfy the filter? This server narrows in Rust /// rather than in SQL (it reads several kinds out of one table in one query), /// so both halves of the same decision live next to each other. pub fn project_kind_filter_holds(filter: ProjectKindFilter, row: &Map) -> bool { match filter { ProjectKindFilter::Equals(column, value) => { row.get(column).and_then(Value::as_str) == Some(value) } ProjectKindFilter::IsNull(column) => { matches!(row.get(column), None | Some(Value::Null)) } ProjectKindFilter::EqualsAndNull(column, value, other) => { row.get(column).and_then(Value::as_str) == Some(value) && matches!(row.get(other), None | Some(Value::Null)) } } } // ── the memory writers `records.ts` exports for `projects.ts` ─────────────── /// The step between two links of one project's list — core's `POSITION_STEP`. const POSITION_STEP: f64 = 1024.0; /// 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 (R46). pub fn next_memory_position_in(ctx: &Ctx<'_>, project_id: &str) -> Result { let links = rows( ctx, &Query::on("cotton_project_links") .columns(&["position"]) .eq("record_kind", "memory".to_string()) .eq("project_id", project_id.to_string()), )?; let mut last = 0.0_f64; for link in links { let position = link .get("position") .and_then(Value::as_f64) .unwrap_or_default(); if position > last { last = position; } } Ok(last + POSITION_STEP) } /// D3's replacement, for `unlink_from_project`: which of `memory_ids` this /// project is the ONLY home of, as `(id, label)` pairs in the order asked. /// /// This used to be `archive_if_homeless`, which retired the entry in the same /// call with an agent's comment for a reason. It is gone: an unlink is /// bookkeeping, and a memory entry is the owner's own words, so nothing here /// decides that words he kept stop briefing. The caller refuses instead and /// says what to do — another project, or `memory_archive`, which is his own. /// /// An entry that is ALREADY archived is not reported: it has left every /// briefing anyway, and refusing its unlink would pin the twenty entries the /// old rule retired to the projects they no longer belong to. pub fn memories_orphaned_by( ctx: &Ctx<'_>, memory_ids: &[String], project_id: &str, ) -> Result, ToolFailure> { let mut orphaned = Vec::new(); for memory_id in memory_ids { let Some(row) = maybe_row( ctx, &Query::on("cotton_memories") .columns(&["id", "slug", "status"]) .eq("id", memory_id.to_string()), )? else { continue; }; if text(&row, "status").as_deref() == Some("archived") { continue; } let links = rows( ctx, &Query::on("cotton_project_links") .columns(&["id", "project_id"]) .eq("record_kind", "memory".to_string()) .eq("record_id", memory_id.to_string()), )?; let elsewhere = links .iter() .any(|link| text(link, "project_id").as_deref() != Some(project_id)); if !elsewhere { orphaned.push(( memory_id.clone(), text(&row, "slug").unwrap_or_else(|| memory_id.clone()), )); } } Ok(orphaned) } /// 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 fn restore_if_archived(ctx: &mut Ctx<'_>, memory_id: &str) -> Result { let Some(row) = maybe_row( ctx, &Query::on("cotton_memories") .columns(&["id", "status"]) .eq("id", memory_id.to_string()), )? else { return Ok(false); }; if text(&row, "status").as_deref() != Some("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", memory_id, patch)?; Ok(true) } /// A project's own journal pages, newest day first — read by the IDENTITY /// COLUMN rather than by the links table (§3.2). pub fn project_journal_rows( ctx: &Ctx<'_>, project_id: &str, limit: i64, ) -> Result>, ToolFailure> { rows( ctx, &Query::on("cotton_notes") .columns(&["id", "journal_date", "body", "author_label"]) .eq("kind", "journal".to_string()) .eq("project_id", project_id.to_string()) .filter(Filter::IsNull("archived_at".to_string())) .order_by("journal_date", Order::Desc) .limit(limit), ) }