//! 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};usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::{maybe_row, rows, text, update_row};usecrate::mcp::protocol::ToolFailure;usecrate::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)]pubenumProjectKindFilter {/// `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),}implProjectKindFilter {/// The discriminator: the column a kind sharing its table is told by.pubfn column(self) -> &'static str {matchself {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.pubfn columns(self) -> Vec<&'static str> {matchself {ProjectKindFilter::Equals(column, _) | ProjectKindFilter::IsNull(column) => vec![column],ProjectKindFilter::EqualsAndNull(column, _, other) => vec![column, other], } }}pubstructProjectKindTable {pub table: &'static str,pub where_clause: Option<ProjectKindFilter>,}/// Where each linkable kind's rows live. Exhaustive over [`ProjectLinkKind`],/// which is the totality the TypeScript asserts at module load.pubconstfn project_kind_table(kind: ProjectLinkKind) -> ProjectKindTable {useProjectLinkKind::*;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.pubfn project_kind_filter_holds(filter: ProjectKindFilter, row: &Map<String, Value>) -> 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).pubfn next_memory_position_in(ctx: &Ctx<'_>, project_id: &str) -> Result<f64, ToolFailure> {let links = rows( ctx, &Query::on("cotton_project_links") .columns(&["position"]) .eq("record_kind", "memory".to_string()) .eq("project_id", project_id.to_string()), )?;letmut 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.pubfn memories_orphaned_by( ctx: &Ctx<'_>, memory_ids: &[String], project_id: &str,) -> Result<Vec<(String, String)>, ToolFailure> {letmut orphaned = Vec::new();for memory_id in memory_ids {letSome(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).pubfn restore_if_archived(ctx: &mutCtx<'_>, memory_id: &str) -> Result<bool, ToolFailure> {letSome(row) = maybe_row( ctx, &Query::on("cotton_memories") .columns(&["id", "status"]) .eq("id", memory_id.to_string()), )?else {returnOk(false); };if text(&row, "status").as_deref() != Some("archived") {returnOk(false); }letmut 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).pubfn project_journal_rows( ctx: &Ctx<'_>, project_id: &str, limit: i64,) -> Result<Vec<Map<String, Value>>, 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), )}