//! `create_project`, `update_project`, `link_to_project`, //! `unlink_from_project` — the four writes. use crate::mcp::writer::Retract; use std::collections::BTreeMap; use cotton_core::constants::{mirrored_project_column, ProjectLinkKind, SummaryKind}; use cotton_core::rules::memory_briefing::normalize_repo_url; use cotton_core::transforms::project_slug::is_reserved_project_slug; use cotton_core::rules::summaries::{summary_patch_for, StoredSummary}; use cotton_store::protocol::derived_id::{memory_project_id, project_link_id}; use serde_json::{Map, Value}; use crate::mcp::dispatch::{Ctx, ToolResult}; use crate::mcp::handlers::common::{insert_row, now_iso, rows, text, update_row, Clearable}; use crate::mcp::handlers::projects::brand::read_project_brand; use crate::mcp::handlers::projects::brand::{brand_is_empty, parse_project_brand}; use crate::mcp::handlers::projects::engine_shim::{ memories_orphaned_by, next_memory_position_in, restore_if_archived, }; use crate::mcp::handlers::projects::kinds::title_of; use crate::mcp::handlers::projects::validate::{ validate_create_project, validate_link_to_project, validate_unlink_from_project, validate_update_project, }; use crate::mcp::handlers::projects::{ links_of, memory_projects, project_by_slug, project_out, read_linked_rows, repo_list, KindRef, LinkRow, PROJECT_COLUMNS, }; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::Query; /// Slug shape, mirroring the store CHECK — refused here so the constraint /// failure never has to translate SQL into advice. fn slug_shape_holds(slug: &str) -> bool { let bytes = slug.as_bytes(); if bytes.is_empty() || bytes.len() > 64 { return false; } let first_ok = bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit(); first_ok && bytes .iter() .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-') } /// What the caller means by `description`, in the summary grammar (R73): /// `None` KEEPS, a string SETS, and an EMPTY string CLEARS. /// /// The empty case is normalised HERE rather than left to core, which refuses a /// blank string outright: "" has meant "clear it" on this tool since the project /// verbs shipped, and the app's writer normalises the same way before it calls. /// TRIMMED as well, because `update_summary` trims and both app editors trim on /// save — prose stored with a stray leading space is prose the app's next Save /// reads as a CHANGE, which re-stamps the provenance and resets the staleness /// cue: the exact resetting-by-looking that R67's no-op exists to prevent. fn summary_text(description: Option<&str>) -> Option> { let description = description?; let trimmed = description.trim(); Some((!trimmed.is_empty()).then(|| trimmed.to_string())) } // ── create_project ────────────────────────────────────────────────────────── pub fn create_project(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_create_project(args)?; // The template branch is decided HERE rather than inside the writer below, // so the project writer stays free of the seeding it does not own. match &args.template { None => create_project_row( ctx, &args.slug, &args.name, args.description.as_deref(), args.repos.as_deref(), ), Some(template) => crate::mcp::handlers::project_templates::create_project_from_template( ctx, &args, template, ), } } /// The project row itself — the writer `create_project` and /// `createProjectFromTemplate` share, so its slug rules, its reserved-word /// refusal and its summary provenance are ONE implementation. pub fn create_project_row( ctx: &mut Ctx<'_>, slug: &str, name: &str, description: Option<&str>, repos: Option<&[String]>, ) -> ToolResult { if !slug_shape_holds(slug) { return Err(ToolFailure::new( "slug must be 1-64 chars of a-z, 0-9 and dashes, starting with a letter or digit — \ e.g. \"pyro\"", )); } if is_reserved_project_slug(slug) { return Err(ToolFailure::new(format!( "\"{slug}\" is reserved — it names a page of the app, not a project" ))); } let projects = memory_projects(ctx)?; if let Some(taken) = projects .iter() .find(|project| text(project, "slug").as_deref() == Some(slug)) { return Err(ToolFailure::new( if text(taken, "status").as_deref() == Some("archived") { format!( "a project \"{slug}\" exists but is archived — update_project {{ slug: \ \"{slug}\", status: \"active\" }} brings it back" ) } else { format!("a project \"{slug}\" already exists — link to it, or pick another slug") }, )); } // A description written at birth is a summary like any other, so it carries // its author: without this, a project created WITH a paragraph would be the // one summary in the file whose page could not say who wrote it, and whose // staleness cue could never start counting. // // The SAME decision the update path and the app's writer use (R91), asked // of a row that does not exist yet: prose is a change and comes back // stamped, while no summary at birth reads as a clear over an already-clear // row and comes back as no patch at all. let born = summary_patch_for( &StoredSummary::default(), SummaryKind::Project, summary_text(description).flatten().as_deref(), ctx.agent, &now_iso(ctx), ); if let Some(refusal) = born.refusal { return Err(ToolFailure::new(refusal.say(&crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id)))); } // DERIVED from (workspace, slug), never minted. Two devices that each made // a project called "cotton" before they were joined are ONE row when the // files merge; a minted uuid on each would be two rows and one // `UNIQUE (workspace_id, slug)` — a rejection over a project nobody wanted // twice. let id = memory_project_id(ctx.file.namespace(), slug); let mut patch = Map::new(); patch.insert("slug".to_string(), Value::from(slug)); patch.insert("name".to_string(), Value::from(name)); if let Some(born) = born.patch { for (key, value) in born { patch.insert(key, value); } } if let Some(repos) = repos { patch.insert( "repos".to_string(), Value::Array(repos.iter().cloned().map(Value::from).collect()), ); } insert_row(ctx, "cotton_memory_projects", &id, patch)?; ctx.commit()?; let row = rows( ctx, &Query::on("cotton_memory_projects") .columns(PROJECT_COLUMNS) .eq("id", id.clone()), )? .into_iter() .next() .ok_or_else(|| ToolFailure::new(format!("no project with id {id}")))?; let change = crate::mcp::handlers::tables::record_added(ctx, "project", &id)?; let mut out = Map::new(); out.insert("created".to_string(), Value::Bool(true)); out.insert("project".to_string(), Value::Object(project_out(&row))); out.insert("change".to_string(), change); Ok(Value::Object(out)) } // ── update_project ────────────────────────────────────────────────────────── pub fn update_project(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_update_project(args)?; let projects = memory_projects(ctx)?; // Unarchiving addresses a row the active-only resolver cannot see. let project = match args.status.as_deref() { Some("active") => projects .iter() .find(|project| text(project, "slug").as_deref() == Some(&args.slug)) .cloned() .map_or_else(|| project_by_slug(&projects, &args.slug).cloned(), Ok)?, _ => project_by_slug(&projects, &args.slug)?.clone(), }; let project_id = text(&project, "id").unwrap_or_default(); let before = repo_list(project.get("repos")); // Add/remove compare against the NORMALIZED reading of what is stored, so a // row written before normalization (or by hand) still answers to the repo // it actually names — and the merge heals it to the one spelling on the way // out. let removing = args.remove_repos.clone().unwrap_or_default(); let mut merged: Vec = before .iter() .map(|repo| normalize_repo_url(repo)) .filter(|repo| !repo.is_empty() && !removing.contains(repo)) .collect(); for repo in args.add_repos.clone().unwrap_or_default() { if !merged.contains(&repo) { merged.push(repo); } } let repos = args.repos.clone().unwrap_or(merged); // The description IS the project's summary (R80), so it is not written by a // patch line of this file's own: ONE pure decision decides whether a summary // write happens at all, and the app's writer asks the same one (R91). The // cap, the blank refusal, what a clear does to the provenance and — the part // that bites — WHEN THE STAMP MOVES all live there. let description = summary_text(args.description.as_deref()); // The stamp this call would leave, named once so the answer below can read // it without asserting the shape of a patch this same function built. let stamped_by = ctx.agent.to_string(); let stamped_at = now_iso(ctx); let decision = description.as_ref().map(|text| { summary_patch_for( &StoredSummary { text: crate::mcp::handlers::common::text(&project, "description"), by: crate::mcp::handlers::common::text(&project, "summary_by"), updated_at: crate::mcp::handlers::common::text(&project, "summary_updated_at"), }, SummaryKind::Project, text.as_deref(), &stamped_by, &stamped_at, ) }); // The refusal FIRST: on a refusal `patch` is null too, so reading only // `patch` would take a rejection for "nothing to do". if let Some(refusal) = decision.as_ref().and_then(|d| d.refusal) { return Err(ToolFailure::new(refusal.say(&crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id)))); } // The BRAND KIT (v27). Not prose and not a summary, so it never goes near // `summary_patch_for` — it follows `name` / `status` / `repos`: a same-value // comparison, and a patch line only on a real change, so a resend of the // kit somebody is already looking at writes nothing and re-dates nothing. // // The value goes through `parse_project_brand` — the SAME validator the // app's `projectsService.updateBrand` asks — because a hex the phone // accepts and this refuses would be an edit that vanishes on sync. `null` // clears; so does a kit with nothing in it, "no brand kit" having ONE // representation. let brand: Option>> = match &args.brand { Clearable::Unchanged => None, Clearable::Cleared => Some(None), Clearable::Set(value) => { let parsed = parse_project_brand(value).map_err(ToolFailure::new)?; Some((!brand_is_empty(&parsed)).then_some(parsed)) } }; let stored_brand = read_project_brand(project.get("brand")); let brand_changed = match &brand { None => false, Some(next) => next.clone().map(Value::Object) != stored_brand.clone().map(Value::Object), }; let mut patch = Map::new(); if brand_changed { patch.insert( "brand".to_string(), brand.clone().flatten().map_or(Value::Null, Value::Object), ); } if let Some(name) = args .name .as_deref() .filter(|name| Some(*name) != text(&project, "name").as_deref()) { patch.insert("name".to_string(), Value::from(name)); } let wrote_summary = decision.as_ref().is_some_and(|d| d.patch.is_some()); if let Some(summary_patch) = decision.and_then(|d| d.patch) { for (key, value) in summary_patch { patch.insert(key, value); } } if let Some(status) = args .status .as_deref() .filter(|status| Some(*status) != text(&project, "status").as_deref()) { patch.insert("status".to_string(), Value::from(status)); } if repos != before { patch.insert( "repos".to_string(), Value::Array(repos.iter().cloned().map(Value::from).collect()), ); } let mut answer = Map::new(); answer.insert("slug".to_string(), Value::from(args.slug.clone())); answer.insert( "name".to_string(), Value::from( args.name .clone() .or_else(|| text(&project, "name")) .unwrap_or_default(), ), ); match &description { Some(Some(prose)) => { answer.insert("description".to_string(), Value::from(prose.clone())); } Some(None) => {} None => { if let Some(stored) = text(&project, "description").filter(|d| !d.is_empty()) { answer.insert("description".to_string(), Value::from(stored)); } } } // The provenance the row will carry: this call's when it wrote the prose, // the row's own when it did not — and neither when the summary is gone. if wrote_summary { if matches!(&description, Some(Some(_))) { answer.insert("summaryBy".to_string(), Value::from(stamped_by.clone())); answer.insert( "summaryUpdatedAt".to_string(), Value::from(stamped_at.clone()), ); } } else { if let Some(by) = text(&project, "summary_by").filter(|by| !by.is_empty()) { answer.insert("summaryBy".to_string(), Value::from(by)); } if let Some(at) = text(&project, "summary_updated_at").filter(|at| !at.is_empty()) { answer.insert("summaryUpdatedAt".to_string(), Value::from(at)); } } answer.insert( "repos".to_string(), Value::Array(repos.iter().cloned().map(Value::from).collect()), ); answer.insert( "status".to_string(), Value::from( args.status .clone() .or_else(|| text(&project, "status")) .unwrap_or_default(), ), ); // The kit as the row will read AFTER this call: the new one when it wrote, // the stored one when it did not, and the key absent when there is none. let after_brand = match &brand { None => stored_brand, Some(next) => next.clone(), }; if let Some(after_brand) = after_brand { answer.insert("brand".to_string(), Value::Object(after_brand)); } if patch.is_empty() { let mut out = Map::new(); out.insert("updated".to_string(), Value::Bool(false)); out.insert("project".to_string(), Value::Object(answer)); out.insert( "note".to_string(), Value::from("nothing changed — the project already reads exactly this way"), ); return Ok(Value::Object(out)); } update_row(ctx, "cotton_memory_projects", &project_id, patch)?; ctx.commit()?; let mut out = Map::new(); out.insert("updated".to_string(), Value::Bool(true)); out.insert("project".to_string(), Value::Object(answer)); Ok(Value::Object(out)) } // ── link_to_project ───────────────────────────────────────────────────────── pub fn link_to_project(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_link_to_project(args)?; let projects = memory_projects(ctx)?; let project = project_by_slug(&projects, &args.project)?.clone(); let project_id = text(&project, "id").unwrap_or_default(); let project_slug = text(&project, "slug").unwrap_or_default(); // Every target must exist BEFORE anything writes — a link to a record that // is not there would be a dangling membership born on purpose. let refs: Vec = args .records .iter() .map(|record| KindRef { kind: record.kind, id: record.id.clone(), }) .collect(); let mut row_by_key = read_linked_rows(&ctx.read, &refs)?; // An ARCHIVED memory is not "missing" — it is dropped, and giving it a home // is what brings it back (D3). `read_linked_rows` filters it out through // the kind's `status = 'active'` reading, so it is read again here, any // status. let mut archived_memories: Vec = Vec::new(); for record in &args.records { if record.kind != ProjectLinkKind::Memory || row_by_key.contains_key(&format!("memory:{}", record.id)) { continue; } let found = rows( ctx, &Query::on("cotton_memories") .columns(&["id", "slug", "title", "status", "updated_at"]) .eq("id", record.id.clone()), )? .into_iter() .next(); if let Some(row) = found { row_by_key.insert(format!("memory:{}", record.id), row); archived_memories.push(record.id.clone()); } } let missing: Vec = args .records .iter() .filter(|record| !row_by_key.contains_key(&format!("{}:{}", record.kind, record.id))) .map(|record| format!("{} with id {}", record.kind, record.id)) .collect(); if !missing.is_empty() { return Err(ToolFailure::new(format!( "no {} — nothing was linked; check the ids and call again", missing.join(", ") ))); } // The mirror guard. Some kinds state their project TWICE — once in a column // of their own row, once as a link — and for those the COLUMN is // authoritative: a record whose column says `pyro` cannot also be filed as // `atlas`, because the link row would then say something the column // contradicts and the two would disagree for ever. Naming the SAME project // is not a conflict — it is the mirror converging, and it falls through to // the ordinary upsert below. // // WHICH kinds those are is core's list, not a name written here: the guard // covered `journal` alone until a store arrived with a `project_id` of its // own, and a second hardcoded kind is how the third one gets forgotten. let mut contradicting: Vec = Vec::new(); for record in &args.records { let Some(column) = mirrored_project_column(record.kind) else { continue; }; let Some(row) = row_by_key.get(&format!("{}:{}", record.kind, record.id)) else { continue; }; let Some(own) = text(row, column).filter(|own| *own != project_id) else { continue; }; let slug = projects .iter() .find(|candidate| text(candidate, "id").as_deref() == Some(&own)) .and_then(|candidate| text(candidate, "slug")) .unwrap_or_else(|| "another project".to_string()); // The kind's own sentence (a journal page is the one mirrored kind), // because "the record contradicts its column" tells an assistant that // cannot SEE the column nothing it can act on. contradicting.push(format!("{} is {slug}'s journal page for its day", record.id)); } if !contradicting.is_empty() { return Err(ToolFailure::new(format!( "{} — a record whose own project is set cannot be filed under a second one; nothing \ was linked", contradicting.join("; ") ))); } let existing = links_of(&ctx.read, std::slice::from_ref(&project_id))?; let by_natural_key: BTreeMap = existing .into_iter() .map(|link| (format!("{}:{}", link.record_kind, link.record_id), link)) .collect(); let mut results: Vec = Vec::new(); for record in &args.records { let key = format!("{}:{}", record.kind, record.id); let row = row_by_key .get(&key) .cloned() .expect("every target was checked above"); let title = title_of(record.kind, &row); if let Some(already) = by_natural_key.get(&key) { // THREE states, not two (R38). A call that does not mention `note` // leaves the note alone; only an explicit `null` clears it, and a // string replaces it. The two-state reading — absent means null — // meant an assistant re-linking a record it had already linked // ERASED the note the owner had typed on it through the sheet, // which is the one part of a membership nobody can reconstruct. let next_note = match &record.note { Clearable::Unchanged => already.note.clone(), Clearable::Cleared => None, Clearable::Set(note) => Some(note.clone()), }; let same_note = next_note == already.note; // A re-link that names `pinned` moves the pin on the membership // that is already there — the same write `memory_update` makes, // reached from the sheet that ticks the project. let next_pinned = record.pinned.unwrap_or(already.pinned); let same_pin = next_pinned == already.pinned; if !same_note || !same_pin { let mut patch = Map::new(); if !same_note { patch.insert( "note".to_string(), next_note.clone().map_or(Value::Null, Value::from), ); } if !same_pin { patch.insert("pinned".to_string(), Value::Bool(next_pinned)); } update_row(ctx, "cotton_project_links", &already.id, patch)?; ctx.commit()?; } let mut said: Vec<&str> = Vec::new(); if !same_note { said.push("note updated"); } if !same_pin { said.push(if next_pinned { "pinned" } else { "unpinned" }); } let mut result = Map::new(); result.insert("kind".to_string(), Value::from(record.kind.as_str())); result.insert("id".to_string(), Value::from(record.id.clone())); result.insert("title".to_string(), Value::from(title)); result.insert("linked".to_string(), Value::Bool(false)); result.insert( "note".to_string(), Value::from(if said.is_empty() { "already linked".to_string() } else { format!("already linked — {}", said.join(", ")) }), ); results.push(Value::Object(result)); continue; } let id = project_link_id(&project_id, record.kind.as_str(), &record.id); let stamp = now_iso(ctx); let mut patch = Map::new(); patch.insert("project_id".to_string(), Value::from(project_id.clone())); patch.insert("record_kind".to_string(), Value::from(record.kind.as_str())); patch.insert("record_id".to_string(), Value::from(record.id.clone())); patch.insert( "note".to_string(), match &record.note { Clearable::Set(note) => Value::from(note.clone()), _ => Value::Null, }, ); patch.insert("applied_by".to_string(), Value::from("agent")); // A memory joins at the tail of the project's unpinned band — the // position `remember` gives it; the store's CHECK wants a position on // every memory link. `pinned` comes with the record when the caller // said so (the entry's own page re-links a project it had pinned) and // is false otherwise. Every other kind leaves the arrangement NULL. if record.kind == ProjectLinkKind::Memory { let position = next_memory_position_in(ctx, &project_id)?; patch.insert( "pinned".to_string(), Value::Bool(record.pinned.unwrap_or(false)), ); patch.insert( "position".to_string(), crate::mcp::handlers::common::js_number(position), ); } patch.insert("created_at".to_string(), Value::from(stamp.clone())); patch.insert("updated_at".to_string(), Value::from(stamp)); ctx.writer()?.upsert("cotton_project_links", &id, patch); ctx.commit()?; let restored = record.kind == ProjectLinkKind::Memory && archived_memories.contains(&record.id) && restore_if_archived(ctx, &record.id)?; if restored { ctx.commit()?; } let mut result = Map::new(); result.insert("kind".to_string(), Value::from(record.kind.as_str())); result.insert("id".to_string(), Value::from(record.id.clone())); result.insert("title".to_string(), Value::from(title)); result.insert("linked".to_string(), Value::Bool(true)); if restored { result.insert("restored".to_string(), Value::Bool(true)); result.insert( "note".to_string(), Value::from("was archived — linking it here brought it back"), ); } results.push(Value::Object(result)); } let mut out = Map::new(); out.insert("project".to_string(), Value::from(project_slug)); out.insert("records".to_string(), Value::Array(results)); Ok(Value::Object(out)) } // ── unlink_from_project ───────────────────────────────────────────────────── pub fn unlink_from_project(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_unlink_from_project(args)?; let projects = memory_projects(ctx)?; let project = project_by_slug(&projects, &args.project)?.clone(); let project_id = text(&project, "id").unwrap_or_default(); let project_slug = text(&project, "slug").unwrap_or_default(); // The delete answers no rows, so membership is read first — which also // makes re-running this a clean no-op rather than an error. let existing = links_of(&ctx.read, std::slice::from_ref(&project_id))?; let by_natural_key: BTreeMap = existing .into_iter() .map(|link| (format!("{}:{}", link.record_kind, link.record_id), link)) .collect(); // The mirror guard's other half (§3.1): a LIVE project page's own link row // is not a membership somebody chose, it is the mirror of the column, so // removing it would leave the page in the project with nothing reading it. // Taking the entry off the project is `archive_note` first. // // An ARCHIVED mirror is allowed through, and that is the whole exit. // Archiving clears neither the link row nor `project_id`, so a guard that // refused unconditionally would leave an archived page pinned to its // project for ever with no act left that could detach it. let journal_refs: Vec = args .records .iter() .filter(|record| record.kind == ProjectLinkKind::Journal) .map(|record| KindRef { kind: record.kind, id: record.id.clone(), }) .collect(); if !journal_refs.is_empty() { let row_by_key = read_linked_rows(&ctx.read, &journal_refs)?; let live: Vec = journal_refs .iter() .filter(|record| { row_by_key .get(&format!("journal:{}", record.id)) .is_some_and(|row| { text(row, "project_id").as_deref() == Some(&project_id) && matches!(row.get("archived_at"), None | Some(Value::Null)) }) }) .map(|record| record.id.clone()) .collect(); if !live.is_empty() { return Err(ToolFailure::new(format!( "{} — the page is {project_slug}'s journal for the day, so it cannot be unlinked \ while it is live; archive_note takes the entry off the project, and unlinking an \ archived page then removes the link too. Nothing was unlinked.", live.join(", ") ))); } } // AN ENTRY ALWAYS HAS A PROJECT, and losing its last one is not a decision // to retire it. This call used to archive such an entry in the same write, // with an agent's comment for a reason — and on 21 Sep 2026 that retired // twenty of the owner's own rules, six of them still live, on nothing but a // drop tapped on a project's list. Memory is his words and the keep is his, // so an unlink that would leave an entry briefing nowhere is REFUSED and // says the two ways on: another project, or `memory_archive`, which is his // own act and keeps the links so approve restores the homes. // // Whole-call, like the journal guard above: a batch that would orphan one // entry unlinks nothing, so a caller never has to work out which half of // its own request landed. let memory_ids: Vec = args .records .iter() .filter(|record| record.kind == ProjectLinkKind::Memory) .filter(|record| by_natural_key.contains_key(&format!("memory:{}", record.id))) .map(|record| record.id.clone()) .collect(); if !memory_ids.is_empty() { let orphaned = memories_orphaned_by(ctx, &memory_ids, &project_id)?; if !orphaned.is_empty() { let named = orphaned .iter() .map(|(id, slug)| format!("[{slug}] ({id})")) .collect::>() .join(", "); let (subject, object) = if orphaned.len() == 1 { ("this entry is", "it") } else { ("each of these entries is", "them") }; return Err(ToolFailure::new(format!( "{named} — {project_slug} is the only project {subject} in, and an entry with no \ project briefs nowhere. Memory is the owner's own words and an unlink is \ bookkeeping, so this one is refused rather than retiring anything: \ link_to_project {{ project, records: [{{ kind: \"memory\", id }}] }} gives \ {object} another home and the unlink then goes through, or memory_archive \ retires {object} explicitly — it keeps the links, so approving puts {object} \ back where {object} briefed. Nothing was unlinked." ))); } } let mut results: Vec = Vec::new(); for record in &args.records { let mut result = Map::new(); result.insert("kind".to_string(), Value::from(record.kind.as_str())); result.insert("id".to_string(), Value::from(record.id.clone())); let Some(link) = by_natural_key.get(&format!("{}:{}", record.kind, record.id)) else { result.insert("unlinked".to_string(), Value::Bool(false)); result.insert("note".to_string(), Value::from("was not linked")); results.push(Value::Object(result)); continue; }; ctx.writer()?.retract("cotton_project_links", &link.id, Retract::Relation); ctx.commit()?; // Nothing else happens to the record — the membership goes and the // record stands. A memory entry that would be left with no project // never reaches here: the guard above refused the whole call. result.insert("unlinked".to_string(), Value::Bool(true)); results.push(Value::Object(result)); } let mut out = Map::new(); out.insert("project".to_string(), Value::from(project_slug)); out.insert("records".to_string(), Value::Array(results)); Ok(Value::Object(out)) }