//! The owner's own verbs over sessions and links (sub-step 4f). //! //! The phone has one write path — `write { tool }`, running the same handler //! an assistant runs, over the replica and into the outbox — so a screen that //! renames a session, files it under a project or says where a saved record //! came from needs a NAME here. //! //! WHY THEY ARE OWNER-SCOPE. `McpScope::Owner` — a word no token carries — is //! how the owner's own app does what an assistant is refused. use serde_json::{json, Map, Value}; use cotton_core::constants::LinkKind; use cotton_store::link_rule::FileKind; use cotton_store::protocol::derived_id::{link_id_for, LinkRow}; use crate::mcp::dispatch::{Ctx, ToolResult}; use crate::mcp::handlers::common::{ fail, insert_row, is_uuid, now_iso, optional_string, require_string, require_uuid, row_by_id, rows, text, update_row, Valid, }; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::{Filter, Query}; // ── sessions ──────────────────────────────────────────────────────────────── /// The longest title a session row holds — the table's own CHECK. const SESSION_TITLE_MAX: usize = 140; /// The OWNER'S OWN NAME for a session. The row's title is otherwise the /// agent's (its `/rename`, or the hooks' ` · · `); this is /// the one write that is the person's, and the hooks send a title only when /// the agent's own one CHANGES, so it holds until somebody renames the session /// again — whichever rename is later wins. pub fn rename_session(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let id = require_uuid(args, "id")?; let title = args .get("title") .and_then(Value::as_str) .map(|title| title.split_whitespace().collect::>().join(" ")) .unwrap_or_default(); if title.is_empty() { return Err(ToolFailure::new("title is required — the words to call the session")); } if title.chars().count() > SESSION_TITLE_MAX { return Err(ToolFailure::new(format!( "a session's title is at most {SESSION_TITLE_MAX} characters" ))); } if row_by_id(ctx, "cotton_sessions", &id)?.is_none() { return Err(ToolFailure::new("no session with that id")); } let mut patch = Map::new(); patch.insert("title".into(), Value::from(title.clone())); update_row(ctx, "cotton_sessions", &id, patch)?; ctx.commit()?; Ok(json!({ "id": id, "title": title })) } pub fn move_session(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let id = require_uuid(args, "id")?; let project_id = match args.get("projectId") { Some(Value::Null) => None, Some(Value::String(_)) => Some(require_uuid(args, "projectId")?), _ => { return Err(ToolFailure::new( "projectId must be a uuid, or null to take the session out of any project", )) } }; let Some(session) = row_by_id(ctx, "cotton_sessions", &id)? else { return Err(ToolFailure::new("no session with that id")); }; // A PROJECT'S STANDING CONVERSATION IS THAT PROJECT'S. It is the one // session the project page talks to (at most one per project, a UNIQUE // index), so filing it elsewhere would leave the project with no // conversation and give another project a second. if text(&session, "kind").as_deref() == Some("conversation") { return Err(ToolFailure::new( "that session is its project's own conversation, and it moves with nothing — only a \ thread is filed under a project", )); } if let Some(project) = &project_id { if row_by_id(ctx, "cotton_memory_projects", project)?.is_none() { return Err(ToolFailure::new("no project with that id")); } } let value = project_id.clone().map_or(Value::Null, Value::from); let mut patch = Map::new(); patch.insert("project_id".into(), value.clone()); update_row(ctx, "cotton_sessions", &id, patch)?; // AND EVERY TURN IN IT. A prompt carries its own `project_id` so the // project's own reads do not have to join through the session; leaving // them behind would file the session in one place and its work in // another. let prompts = rows( ctx, &Query::on("cotton_prompts") .columns(&["id"]) .eq("session_id", id.clone()), )?; let moved = prompts.len(); for prompt in prompts { if let Some(prompt_id) = text(&prompt, "id") { let mut prompt_patch = Map::new(); prompt_patch.insert("project_id".into(), value.clone()); update_row(ctx, "cotton_prompts", &prompt_id, prompt_patch)?; } } ctx.commit()?; Ok(json!({ "id": id, "projectId": value, "turnsMoved": moved })) } // ── the generic edge ──────────────────────────────────────────────────────── /// One end of a `cotton_links` edge, read off a call. struct LinkEnd { kind: String, id: String, } /// A kind the `cotton_links` CHECK admits, and a non-blank id. /// /// The id is NOT required to be a uuid: `photo` and `video` records are keyed /// `photo:` (`derived_id::photo_record_id`), so a uuid gate here would /// refuse the two kinds v31 added to this very table. fn link_end(args: &Map, kind_key: &str, id_key: &str) -> Valid { let Some(kind) = require_string(args, kind_key) else { return fail(format!("{kind_key} is required")); }; if LinkKind::parse(&kind).is_none() { return fail(format!( "{kind_key} must be one of: {}", LinkKind::ALL .iter() .map(|kind| kind.as_str()) .collect::>() .join(", ") )); } let Some(id) = require_string(args, id_key) else { return fail(format!("{id_key} is required")); }; Ok(LinkEnd { kind, id }) } /// One edge, as a caller reads it back. fn link_out(row: &Map) -> Value { json!({ "id": text(row, "id"), "fromKind": text(row, "from_kind"), "fromId": text(row, "from_id"), "toKind": text(row, "to_kind"), "toId": text(row, "to_id"), "toDatabase": text(row, "to_database"), "createdAt": text(row, "created_at"), }) } /// Write one provenance edge between two records. /// /// The port of `linksService.createLink` (`packages/core/src/services/links.service.ts`). /// The verb exists for records a CLIENT creates out of another record — the /// news reader's "Save as note" and "Save as todo", where the note and the todo /// are ordinary rows written by ordinary verbs and the only thing that remembers /// where they came from is this edge. Everything the ROUTER files keeps writing /// its own edges beside the record it creates. /// /// DIRECTION IS THE CALLER'S, and the convention across the app is derived → /// source (`todo → meeting`), so the NEW record is `from`. /// /// IDEMPOTENT BY THE EDGE, twice over: the row's id is DERIVED from the natural /// key the table already enforces (`uq_cotton_links_ends`), so every writer on every device converges on ONE row and a re-link /// after an unlink is that row returning rather than a sibling; and an edge /// already stated is handed back AS IT STANDS, keeping its original /// `created_at`, because the fact has existed since the first time somebody said /// it. The callers that say the same thing twice are ordinary ones — the pending /// link drain runs on mount and on every inbox fold, and two of those overlap. /// /// `toDatabase` names the database `toId` is in when it is not this one. The /// database is one of the edge's ends: a link to this database's X and a link /// to another database's X with the same id are two rows. Only the personal /// database may point into another one (the link rule mint enforces), so a /// `toDatabase` from any other database is refused here with that reason, and /// one naming this very database is the same as none. pub fn create_link(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let from = link_end(args, "fromKind", "fromId")?; let to = link_end(args, "toKind", "toId")?; let to_database = match optional_string(args, "toDatabase") { None => None, Some(database) if !is_uuid(&database) => return fail("toDatabase must be a database id"), Some(database) if database == ctx.workspace_id => None, Some(database) => Some(database), }; if to_database.is_some() && ctx.file_kind()? != FileKind::Personal { return fail( "only the personal database can link to a record in another database; link from \ there, or link to a record in this database", ); } let mut query = Query::on("cotton_links") .eq("from_kind", from.kind.clone()) .eq("from_id", from.id.clone()) .eq("to_kind", to.kind.clone()) .eq("to_id", to.id.clone()); query = match &to_database { None => query.filter(Filter::IsNull("to_database".to_string())), Some(database) => query.eq("to_database", database.clone()), }; let existing = rows(ctx, &query.limit(1))?; if let Some(row) = existing.first() { return Ok(link_out(row)); } let id = link_id_for( &LinkRow { from_kind: &from.kind, from_id: &from.id, to_kind: &to.kind, to_id: &to.id, to_database: to_database.as_deref(), }, ctx.file.id(), ); let mut patch = Map::new(); patch.insert("workspace_id".into(), Value::from(ctx.workspace_id)); patch.insert("from_kind".into(), Value::from(from.kind.clone())); patch.insert("from_id".into(), Value::from(from.id.clone())); patch.insert("to_kind".into(), Value::from(to.kind.clone())); patch.insert("to_id".into(), Value::from(to.id.clone())); patch.insert("to_database".into(), to_database.clone().map_or(Value::Null, Value::from)); insert_row(ctx, "cotton_links", &id, patch)?; ctx.commit()?; Ok(json!({ "id": id, "fromKind": from.kind, "fromId": from.id, "toKind": to.kind, "toId": to.id, "toDatabase": to_database, "createdAt": now_iso(ctx), })) }