Cotton code
181 lines · 6.7 KB · RustRaw
//! `update_summary` — the summary a person reads at the top of a record,//! written by the assistant they are talking to.//!//! ONE verb over three kinds rather than `update_person_summary` and two//! siblings: a model reading `update_summary({kind})` extrapolates the whole//! set, and three near-identical tools is three descriptions to keep in//! agreement. The kinds it does NOT take are refusals that NAME the verb that//! does, because a tool that answers "no" without saying where to go is a//! hallucinated call in the next turn.//!//! The `summaryOut` half of the TypeScript file lives in//! [`crate::mcp::handlers::common::summary_out`] — every group that reads a//! summarised record needs it, and none of them owns it.use cotton_core::constants::SummaryKind;use cotton_core::rules::summaries::{summary_patch_for, summary_source, StoredSummary};use serde_json::{Map, Value};use crate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult};use crate::mcp::handlers::common::{    fail, maybe_row, now_iso, require_string, require_uuid, summary_out, text, update_row, Valid,};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::Query;pub fn handlers() -> HandlerGroup {    &[("update_summary", update_summary)]}/// The kinds this verb writes. `project` is `update_project`'s (R81);/// `document` is the document pipeline's (§D6). Both refusals name their owner.////// A strict subset of core's `SUMMARY_KINDS` — held by the `match` in/// [`kind_of`], which cannot compile against a name `SummaryKind` does not have.pub const UPDATE_SUMMARY_KINDS: &[&str] = &["person", "thread", "email_thread"];/// Where the kinds this verb refuses are written instead.fn summary_kind_elsewhere(kind: &str) -> Option<&'static str> {    match kind {        "project" => Some(            "a project's summary is its description — update_project { slug, description } writes \             it, and stamps you as its author",        ),        "document" => Some(            "a document's summary is written by Cotton's own document pipeline when it reads the \             file; update_document changes the title and the facts, never the summary",        ),        _ => None,    }}fn kind_of(raw: &str) -> Option<SummaryKind> {    match raw {        "person" => Some(SummaryKind::Person),        "thread" => Some(SummaryKind::Thread),        "email_thread" => Some(SummaryKind::EmailThread),        _ => None,    }}pub struct UpdateSummaryArgs {    pub kind: SummaryKind,    pub raw_kind: String,    pub id: String,    /// `None` clears the summary and its provenance.    pub summary: Option<String>,}pub fn validate_update_summary(args: &Map<String, Value>) -> Valid<UpdateSummaryArgs> {    let raw_kind = require_string(args, "kind");    let kind = raw_kind        .as_deref()        .filter(|kind| UPDATE_SUMMARY_KINDS.contains(kind))        .and_then(kind_of);    let Some(kind) = kind else {        let elsewhere = raw_kind.as_deref().and_then(summary_kind_elsewhere);        return fail(elsewhere.map_or_else(            || format!("kind must be one of: {}", UPDATE_SUMMARY_KINDS.join(", ")),            str::to_string,        ));    };    let id = require_uuid(args, "id")?;    // Required, and three-valued only between a string and null: "leave it    // alone" is not a call anyone needs to make.    let summary = match args.get("summary") {        Some(Value::Null) => None,        // Trimmed, not emptied: a blank string is REFUSED by the writer with        // the sentence that points at null, never quietly read as a clear.        Some(Value::String(raw)) => Some(raw.trim().to_string()),        _ => {            return fail("summary is required — the paragraph, or null to clear it");        }    };    Ok(UpdateSummaryArgs {        kind,        raw_kind: raw_kind.unwrap_or_default(),        id,        summary,    })}pub fn update_summary(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_update_summary(args)?;    let source = summary_source(args.kind);    let columns = [        "id",        source.column,        source.provenance.by,        source.provenance.updated_at,    ];    // The stored row, not just its id: the decision below needs the prose that    // is there before it can say whether this write is a change (R67/R91). One    // answer for "absent" and "not this workspace" — and it comes BEFORE the    // refusal, as core's own writer does it: you cannot write to a record that    // is not there, whatever the prose says.    let stored = maybe_row(        ctx,        &Query::on(source.table)            .columns(&columns)            .eq("id", args.id.clone()),    )?    .ok_or_else(|| ToolFailure::new(format!("no such {} in this workspace", args.raw_kind)))?;    // ONE decision, shared with the app's writer (R91) — the cap, the blank    // refusal, what a clear does to the provenance, and above all WHEN THE    // STAMP MOVES.    let decision = summary_patch_for(        &StoredSummary {            text: text(&stored, source.column),            by: text(&stored, source.provenance.by),            updated_at: text(&stored, source.provenance.updated_at),        },        args.kind,        args.summary.as_deref(),        ctx.agent,        &now_iso(ctx),    );    // The refusal FIRST: on a refusal `patch` is null too, so a caller reading    // only `patch` would take a rejection for "nothing to do".    if let Some(refusal) = decision.refusal {        return Err(ToolFailure::new(refusal.say(&crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id))));    }    let wrote = decision.patch.is_some();    if let Some(patch) = decision.patch {        update_row(ctx, source.table, &args.id, patch)?;        ctx.commit()?;    }    // Read it back rather than echoing the argument: the answer states what the    // OWNER will read, staleness cue included. On a no-op there is nothing new    // to read, so the row already in hand is it.    let row = if wrote {        maybe_row(            ctx,            &Query::on(source.table)                .columns(&columns)                .eq("id", args.id.clone()),        )?        .unwrap_or_default()    } else {        stored    };    let summary = summary_out(ctx, args.kind, &args.id, &row)?;    let mut out = Map::new();    out.insert("updated".to_string(), Value::Bool(wrote));    out.insert("kind".to_string(), Value::from(args.raw_kind));    out.insert("id".to_string(), Value::from(args.id));    if let Some(summary) = summary {        out.insert("summary".to_string(), summary);    }    if !wrote {        out.insert(            "note".to_string(),            Value::from("nothing changed — the summary already reads exactly this way"),        );    }    Ok(Value::Object(out))}