//! 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.pubmod brand;pubmod engine_shim;pubmod kinds;pubmod read;pubmod sections;pubmod validate;pubmod write;#[cfg(test)]#[path = "mod_tests.rs"]mod tests;use cotton_core::constants::ProjectLinkKind;use serde_json::{Map, Value};usecrate::mcp::dispatch::{Ctx, HandlerGroup};usecrate::mcp::handlers::common::{in_chunks, or_null, quoted, read_rows, rows, text, ProjectRef, ID_CHUNK};usecrate::mcp::handlers::projects::brand::read_project_brand;usecrate::mcp::handlers::projects::engine_shim::project_kind_filter_holds;usecrate::mcp::handlers::projects::kinds::kind_source;usecrate::mcp::protocol::ToolFailure;usecrate::mcp::read_db::{Filter, Order, Query, ReadDb};pubfn 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.pubconst 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.pubfn memory_projects(ctx: &Ctx<'_>) -> Result<Vec<Map<String, Value>>, 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`.pubfn as_refs(projects: &[Map<String, Value>]) -> Vec<ProjectRef> { 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<String, Value>]) -> Vec<String> { 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.pubfn project_by_slug<'a>( projects: &'a [Map<String, Value>], slug: &str,) -> Result<&'a Map<String, Value>, ToolFailure> {ifletSome(found) = projects.iter().find(|project| { text(project, "slug").as_deref() == Some(slug) && text(project, "status").as_deref() == Some("active") }) {returnOk(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.pubfn repo_list(value: Option<&Value>) -> Vec<String> {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.pubfn project_out(project: &Map<String, Value>) -> Map<String, Value> {letmut out = Map::new(); out.insert("slug".to_string(), or_null(text(project, "slug"))); out.insert("name".to_string(), or_null(text(project, "name")));ifletSome(description) = text(project, "description").filter(|d| !d.is_empty()) { out.insert("description".to_string(), Value::from(description)); }ifletSome(by) = text(project, "summary_by").filter(|by| !by.is_empty()) { out.insert("summaryBy".to_string(), Value::from(by)); }ifletSome(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.ifletSome(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)]pubstructLinkRow {pub id: String,pub project_id: String,pub record_kind: String,pub record_id: String,pub note: Option<String>,/// 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<f64>,pub created_at: String,}pubconst LINK_COLUMNS: &[&str] = &["id","project_id","record_kind","record_id","note","pinned","position","created_at",];pubfn links_of(read: &ReadDb<'_>, project_ids: &[String]) -> Result<Vec<LinkRow>, ToolFailure> {if project_ids.is_empty() {returnOk(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)]pubstructKindRef {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.pubfn read_linked_rows( read: &ReadDb<'_>, refs: &[KindRef],) -> Result<std::collections::HashMap<String, Map<String, Value>>, ToolFailure> {// Insertion-ordered so the reads run in the order the kinds were named,// which is what makes a failure reproducible.letmut by_table: Vec<(&'static str, Vec<&'static str>, Vec<String>)> = 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()); } }letmut row_by_table_id: std::collections::HashMap<String, Map<String, Value>> = std::collections::HashMap::new();for (table, columns, ids) in &by_table {if *table == "cotton_call_log" {for row incrate::mcp::handlers::calls::read_calls_for_ids(read.driver(),read.workspace_id(),ids).map_err(|e|ToolFailure::new(e.to_string()))? {ifletSome(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 {ifletSome(id) = text(&row, "id") { row_by_table_id.insert(format!("{table}:{id}"), row); } } } }letmut row_by_kind = std::collections::HashMap::new();for entry in refs {let source = kind_source(entry.kind);letSome(row) = row_by_table_id.get(&format!("{}:{}", source.table, entry.id)) else {continue; };ifletSome(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)}