//! The project tools' `validateX` functions — a port of the project block of //! `packages/server/src/mcp/protocol.ts`, with its refusal sentences unchanged. use cotton_core::constants::ProjectLinkKind; use cotton_core::rules::memory_briefing::normalize_repo_url; use cotton_core::templates::PROJECT_TEMPLATE_IDS; use serde_json::{Map, Value}; use crate::mcp::handlers::common::{ fail, is_true, optional_string, quoted, require_string, Clearable, Valid, }; /// What every git remote normalizes to: `host/path`, with a hostname that is /// actually a hostname. /// /// The cheapest test that separates a remote from the two things an assistant /// sends instead — a shorthand (`org/repo`, whose "host" carries no dot) and a /// local path (`/Users/…`, whose host is empty). fn is_repo_remote(normalized: &str) -> bool { if normalized.is_empty() || normalized.chars().any(char::is_whitespace) { return false; } let mut parts = normalized.split('/'); let Some(host) = parts.next() else { return false; }; if host.is_empty() || !host.contains('.') || host.starts_with('.') || host.ends_with('.') { return false; } let path: Vec<&str> = parts.collect(); !path.is_empty() && path.iter().all(|segment| !segment.is_empty()) } /// One of the three repo arguments, normalized through the SAME function /// `projectsForRepo` matches with — a project linked in one spelling and /// briefed in another is the whole failure this normalization prevents. fn repo_argument(args: &Map, key: &str) -> Valid>> { let Some(value) = args.get(key) else { return Ok(None); }; let Some(entries) = value.as_array() else { return fail(format!("{key} must be an array of git remotes")); }; let mut repos: Vec = Vec::new(); for entry in entries { let Some(entry) = entry.as_str() else { return fail(format!("{key} must be an array of git remotes")); }; let normalized = normalize_repo_url(entry); if !is_repo_remote(&normalized) { return fail(format!( "{} is not a git remote — send the URL git itself states \ (https://github.com/org/repo, git@github.com:org/repo.git, \ ssh://git@host/org/repo), not a shorthand or a local path", quoted(entry) )); } // De-duplicated AFTER normalization, so two spellings of one repo // cannot both survive; first occurrence keeps its place. if !repos.contains(&normalized) { repos.push(normalized); } } Ok(Some(repos)) } // ── create_project ────────────────────────────────────────────────────────── pub struct CreateProjectArgs { pub slug: String, pub name: String, pub description: Option, pub repos: Option>, pub template: Option, } pub fn validate_create_project(args: &Map) -> Valid { let Some(slug) = require_string(args, "slug") else { return fail("slug is required — short, stable, lowercase, e.g. \"pyro\""); }; let Some(name) = require_string(args, "name") else { return fail("name is required — the project's display name"); }; let repos = repo_argument(args, "repos")?; let template = match optional_string(args, "template") { None => None, Some(template) => { if !PROJECT_TEMPLATE_IDS.contains(&template.as_str()) { return fail(format!( "no project template \"{template}\" — the templates are {}, and \ create_project's own `template` description says what each one seeds", PROJECT_TEMPLATE_IDS.join(", ") )); } Some(template) } }; Ok(CreateProjectArgs { slug, name, description: optional_string(args, "description"), repos, template, }) } // ── update_project ────────────────────────────────────────────────────────── /// The brand argument's three states. `null` clears; a string or a list is /// refused here only far enough to say "this is not a brand kit at all" — /// every RULE about what a kit may contain lives in `parse_project_brand`. pub type BrandArg = Clearable; pub struct UpdateProjectArgs { pub slug: String, pub name: Option, /// The replacement description; an EMPTY string clears it. pub description: Option, pub status: Option, pub repos: Option>, pub add_repos: Option>, pub remove_repos: Option>, pub brand: BrandArg, } pub fn validate_update_project(args: &Map) -> Valid { let Some(slug) = require_string(args, "slug") else { return fail("slug is required — the project's slug, from list_projects"); }; let name = match args.get("name") { None => None, Some(_) => match optional_string(args, "name") { Some(name) => Some(name), None => return fail("name must be a non-empty string"), }, }; let description = match args.get("description") { None => None, Some(Value::String(raw)) => Some(raw.trim().to_string()), Some(_) => return fail("description must be a string (empty clears it)"), }; let status = match args.get("status") { None => None, Some(Value::String(raw)) if raw == "active" || raw == "archived" => Some(raw.clone()), Some(_) => return fail("status must be \"active\" or \"archived\""), }; let brand = match args.get("brand") { None => Clearable::Unchanged, Some(Value::Null) => Clearable::Cleared, Some(Value::Object(object)) => Clearable::Set(Value::Object(object.clone())), Some(_) => return fail("brand must be an object, or null to clear it"), }; let repos = repo_argument(args, "repos")?; let add_repos = repo_argument(args, "addRepos")?; let remove_repos = repo_argument(args, "removeRepos")?; if repos.is_some() && (add_repos.is_some() || remove_repos.is_some()) { return fail( "repos REPLACES the whole list — send it on its own, or use addRepos/removeRepos to \ edit the list in place", ); } if name.is_none() && description.is_none() && status.is_none() && repos.is_none() && add_repos.is_none() && remove_repos.is_none() && brand.is_unchanged() { return fail( "send at least one change: name, description, status, brand, repos \ (replaces the list), addRepos or removeRepos", ); } Ok(UpdateProjectArgs { slug, name, description, status, repos, add_repos, remove_repos, brand, }) } // ── get_project ───────────────────────────────────────────────────────────── pub struct GetProjectArgs { pub slug: String, /// Mint a short-lived download link per brand asset. Off by default — a /// signed url is a bearer credential and this is the session-start call. pub include_brand_asset_urls: bool, /// `limit: "all"` — the owner's own screen is drawing this project, so /// every linked group answers EVERY row rather than the assistant's /// fifty (`GROUP_CAP`). Only the phone's read seam spells it; the MCP /// door refuses a string `limit` before this runs. pub whole_groups: bool, } pub fn validate_get_project(args: &Map) -> Valid { let Some(slug) = require_string(args, "slug") else { return fail("slug is required — the project's slug, from list_projects"); }; match args.get("includeBrandAssetUrls") { None | Some(Value::Bool(_)) => {} Some(_) => return fail("includeBrandAssetUrls must be true or false"), } Ok(GetProjectArgs { slug, include_brand_asset_urls: is_true(args, "includeBrandAssetUrls"), whole_groups: args.get("limit").and_then(Value::as_str) == Some(super::super::common::WHOLE_SET), }) } // ── link / unlink ─────────────────────────────────────────────────────────── /// One `{ kind, id, note?, pinned? }` a link call names. pub struct ProjectRecordRef { pub kind: ProjectLinkKind, pub id: String, /// Whether this membership pins the record in the project's list. Only a /// MEMORY link has a pin — `pinned` lives on the link row and only the /// memory list reads it — so any other kind naming it is refused rather /// than silently ignored: a caller that thought it was pinning a todo /// would otherwise be told it had worked. pub pinned: Option, /// THREE states, and the difference matters: `Unchanged` (the key absent) /// leaves whatever note the link already carries, a string sets it, and an /// explicit `null` clears it. Reading "absent" as "clear" is how an /// assistant merely re-asserting a membership erased the note the owner had /// typed on it. pub note: Clearable, } pub struct LinkToProjectArgs { pub project: String, pub records: Vec, } fn link_kinds_sentence() -> String { ProjectLinkKind::ALL .iter() .map(|kind| kind.as_str()) .collect::>() .join(", ") } /// The shared shape of link/unlink: a project slug plus 1-50 record refs. fn project_record_refs(args: &Map, with_note: bool) -> Valid { let Some(project) = require_string(args, "project") else { return fail("project is required — the project's slug, from list_projects"); }; let Some(entries) = args.get("records").and_then(Value::as_array) else { return fail("records must be a non-empty array of { kind, id }"); }; if entries.is_empty() { return fail("records must be a non-empty array of { kind, id }"); } if entries.len() > 50 { return fail("at most 50 records per call — split the rest into another call"); } let mut records = Vec::with_capacity(entries.len()); for entry in entries { let Some(record) = entry.as_object() else { return fail("each record is { kind, id }"); }; let kind = record .get("kind") .and_then(Value::as_str) .and_then(ProjectLinkKind::parse); let Some(kind) = kind else { return fail(format!("kind must be one of {}", link_kinds_sentence())); }; let Some(id) = require_string(record, "id") else { return fail("each record needs its id"); }; let mut note = Clearable::Unchanged; if with_note { match record.get("note") { None => {} // `null` is the only way to CLEAR a note, and it has to be // explicit — omitting the key means "leave it alone". Some(Value::Null) => note = Clearable::Cleared, Some(Value::String(raw)) if !raw.trim().is_empty() => { // An empty string stays refused: it reads as a typo far // more often than as an intention, and the caller that // really means "clear" has `null`. if raw.chars().count() > 500 { return fail("a record's note is at most 500 characters"); } note = Clearable::Set(raw.trim().to_string()); } Some(_) => { return fail( "a record's note must be a non-empty string, or null to clear an existing \ note", ); } } } // A pin is the memory list's arrangement and nothing else's, so it is // read on the LINK call alone (unlinking takes the whole membership // away, pin and all). let mut pinned = None; if with_note { match record.get("pinned") { None | Some(Value::Null) => {} Some(Value::Bool(flag)) => { if kind != ProjectLinkKind::Memory { return fail(format!( "only a memory entry can be pinned in a project — drop pinned from \ the {kind} record" )); } pinned = Some(*flag); } Some(_) => return fail("a record's pinned must be true or false"), } } records.push(ProjectRecordRef { kind, id, note, pinned, }); } Ok(LinkToProjectArgs { project, records }) } pub fn validate_link_to_project(args: &Map) -> Valid { project_record_refs(args, true) } pub fn validate_unlink_from_project(args: &Map) -> Valid { project_record_refs(args, false) }