//! The project tools — `list_projects`, `get_project`, `create_project`, //! `update_project`, `link_to_project`, `unlink_from_project`. //! //! A project is the workspace's working-context primitive: the one row that //! gathers what a piece of work IS — its description, the git repos that brief //! it, and (through `cotton_project_links`) the chats, people, notes, todos, //! events, meetings, documents, pages, locations, transactions, //! memories and goals that belong to it. //! //! `get_project` is THE session-start read: one call, the whole working //! context, compact rows with counts so the assistant drills in with the //! existing per-kind tools rather than pulling payloads it may not need. pub mod brand; pub mod engine_shim; pub mod kinds; pub mod read; pub mod sections; pub mod validate; pub mod write; #[cfg(test)] #[path = "mod_tests.rs"] mod tests; use cotton_core::constants::ProjectLinkKind; use serde_json::{Map, Value}; use crate::mcp::dispatch::{Ctx, HandlerGroup}; use crate::mcp::handlers::common::{in_chunks, or_null, quoted, read_rows, rows, text, ProjectRef, ID_CHUNK}; use crate::mcp::handlers::projects::brand::read_project_brand; use crate::mcp::handlers::projects::engine_shim::project_kind_filter_holds; use crate::mcp::handlers::projects::kinds::kind_source; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::{Filter, Order, Query, ReadDb}; pub fn handlers() -> HandlerGroup { &[ ("list_projects", read::list_projects), ("get_project", read::get_project), ("create_project", write::create_project), ("update_project", write::update_project), ("link_to_project", write::link_to_project), ("unlink_from_project", write::unlink_from_project), ] } /// Every column of `cotton_memory_projects` a project tool reads — /// `memoryProjects`'s own select list. pub const PROJECT_COLUMNS: &[&str] = &[ "id", "slug", "name", "repos", "brand", "description", "status", "summary_by", "summary_updated_at", ]; /// Every project, oldest first. /// /// The FULL row, unlike [`crate::mcp::handlers::common::projects`], which reads /// the three columns a slug lookup needs: these tools answer with the name, the /// repos, the brand kit and the summary's provenance. pub fn memory_projects(ctx: &Ctx<'_>) -> Result>, ToolFailure> { rows( ctx, &Query::on("cotton_memory_projects") .columns(PROJECT_COLUMNS) .order_by("created_at", Order::Asc), ) } /// The slug-lookup view of the same rows, for the resolvers in `common`. pub fn as_refs(projects: &[Map]) -> Vec { projects .iter() .map(|project| ProjectRef { id: text(project, "id").unwrap_or_default(), slug: text(project, "slug").unwrap_or_default(), status: text(project, "status").unwrap_or_default(), }) .collect() } fn known_project_slugs(projects: &[Map]) -> Vec { projects .iter() .filter(|project| text(project, "status").as_deref() == Some("active")) .filter_map(|project| text(project, "slug")) .collect() } /// Address one ACTIVE project by slug, or refuse naming the ones that exist. pub fn project_by_slug<'a>( projects: &'a [Map], slug: &str, ) -> Result<&'a Map, ToolFailure> { if let Some(found) = projects.iter().find(|project| { text(project, "slug").as_deref() == Some(slug) && text(project, "status").as_deref() == Some("active") }) { return Ok(found); } let known = known_project_slugs(projects); Err(ToolFailure::new(if known.is_empty() { "this workspace has no projects yet — list_projects to confirm, or create_project to start \ one" .to_string() } else { format!( "unknown project {} — list_projects names them; the active projects are: {}", quoted(slug), known.join(", ") ) })) } /// The repos column as a list of strings — anything else reads as none. pub fn repo_list(value: Option<&Value>) -> Vec { match value { Some(Value::Array(entries)) => entries .iter() .filter_map(|entry| entry.as_str().map(str::to_string)) .collect(), _ => Vec::new(), } } /// The compact reading of one project row every project tool answers with. /// /// A project's DESCRIPTION is its summary (R80 — the column keeps its /// historical name because a synced table's column name is wire protocol), so /// it carries the same provenance every other summary does: who wrote the /// paragraph, and when. Both keys are absent when there is nothing to say, so a /// project nobody has described still reads clean. pub fn project_out(project: &Map) -> Map { let mut out = Map::new(); out.insert("slug".to_string(), or_null(text(project, "slug"))); out.insert("name".to_string(), or_null(text(project, "name"))); if let Some(description) = text(project, "description").filter(|d| !d.is_empty()) { out.insert("description".to_string(), Value::from(description)); } if let Some(by) = text(project, "summary_by").filter(|by| !by.is_empty()) { out.insert("summaryBy".to_string(), Value::from(by)); } if let Some(at) = text(project, "summary_updated_at").filter(|at| !at.is_empty()) { out.insert("summaryUpdatedAt".to_string(), Value::from(at)); } out.insert( "repos".to_string(), Value::Array( repo_list(project.get("repos")) .into_iter() .map(Value::from) .collect(), ), ); out.insert("status".to_string(), or_null(text(project, "status"))); // Absent when there is none — the key is omitted rather than sent as null, // exactly like `description`, so a project nobody has branded reads clean. if let Some(brand) = read_project_brand(project.get("brand")) { out.insert("brand".to_string(), Value::Object(brand)); } out } // ── the link rows ─────────────────────────────────────────────────────────── /// One `cotton_project_links` row, as every reader here wants it. #[derive(Debug, Clone)] pub struct LinkRow { pub id: String, pub project_id: String, pub record_kind: String, pub record_id: String, pub note: Option, /// The link's own arrangement (v34) — meaningful for memory, where a /// project's list IS the link order; NULL position for every other kind. pub pinned: bool, pub position: Option, pub created_at: String, } pub const LINK_COLUMNS: &[&str] = &[ "id", "project_id", "record_kind", "record_id", "note", "pinned", "position", "created_at", ]; pub fn links_of(read: &ReadDb<'_>, project_ids: &[String]) -> Result, ToolFailure> { if project_ids.is_empty() { return Ok(Vec::new()); } let found = in_chunks(project_ids, |batch| { read_rows( read, &Query::on("cotton_project_links") .columns(LINK_COLUMNS) .filter(Filter::In( "project_id".to_string(), batch.iter().map(|id| id.clone().into()).collect(), )) .order_by("created_at", Order::Asc), ) })?; Ok(found .into_iter() .map(|row| LinkRow { id: text(&row, "id").unwrap_or_default(), project_id: text(&row, "project_id").unwrap_or_default(), record_kind: text(&row, "record_kind").unwrap_or_default(), record_id: text(&row, "record_id").unwrap_or_default(), note: text(&row, "note"), pinned: crate::mcp::handlers::common::flag(&row, "pinned"), position: row.get("position").and_then(Value::as_f64), created_at: text(&row, "created_at").unwrap_or_default(), }) .collect()) } // ── reading the rows a set of links point at ──────────────────────────────── /// One `{kind, id}` a caller wants the row behind. #[derive(Debug, Clone)] pub struct KindRef { pub kind: ProjectLinkKind, pub id: String, } /// Bulk-read the rows behind a set of links, one query per TABLE. Rows that no /// longer exist simply do not come back — the caller decides what a dangling /// link means (`get_project` drops it; `link_to_project` refuses to create one). /// /// Keyed by `kind:id`, not `table:id`, and the two are not the same map: `note` /// and `journal` share `cotton_notes`, so a table-keyed answer cannot say which /// of the two a row IS. A row whose discriminator does not match the kind asked /// for is left OUT, which makes it read as a missing row — and a missing row is /// exactly what a `journal` link against a plain note's id should be. pub fn read_linked_rows( read: &ReadDb<'_>, refs: &[KindRef], ) -> Result>, ToolFailure> { // Insertion-ordered so the reads run in the order the kinds were named, // which is what makes a failure reproducible. let mut by_table: Vec<(&'static str, Vec<&'static str>, Vec)> = Vec::new(); for entry in refs { let source = kind_source(entry.kind); let slot = match by_table .iter() .position(|(table, _, _)| *table == source.table) { Some(index) => &mut by_table[index], None => { by_table.push((source.table, Vec::new(), Vec::new())); by_table.last_mut().expect("just pushed") } }; // UNIONed, not first-wins: two kinds on one table may project different // columns (journal reads `project_id`, a plain note has no use for it), // and taking whichever kind was seen first would drop the other's. // The filter's own columns too: a filter asked of a row that never // read its column holds for every row (a binned password was listed). let filtered = source.where_clause.map(|filter| filter.columns()).unwrap_or_default(); for column in source.columns.iter().copied().chain(filtered) { if !slot.1.contains(&column) { slot.1.push(column); } } if !slot.2.contains(&entry.id) { slot.2.push(entry.id.clone()); } } let mut row_by_table_id: std::collections::HashMap> = std::collections::HashMap::new(); for (table, columns, ids) in &by_table { if *table == "cotton_call_log" { for row in crate::mcp::handlers::calls::read_calls_for_ids(read.driver(),read.workspace_id(),ids).map_err(|e|ToolFailure::new(e.to_string()))? { if let Some(id)=text(&row,"id").filter(|id|ids.contains(id)) {row_by_table_id.insert(format!("{table}:{id}"),row);} } continue; } for batch in ids.chunks(ID_CHUNK) { let found = read_rows( read, &Query::on(table).columns(columns).filter(Filter::In( "id".to_string(), batch.iter().map(|id| id.clone().into()).collect(), )), )?; for row in found { if let Some(id) = text(&row, "id") { row_by_table_id.insert(format!("{table}:{id}"), row); } } } } let mut row_by_kind = std::collections::HashMap::new(); for entry in refs { let source = kind_source(entry.kind); let Some(row) = row_by_table_id.get(&format!("{}:{}", source.table, entry.id)) else { continue; }; if let Some(filter) = source.where_clause { if !project_kind_filter_holds(filter, row) { continue; } } row_by_kind.insert(format!("{}:{}", entry.kind, entry.id), row.clone()); } Ok(row_by_kind) }