//! `attach_evidence` and `remove_evidence` — the one writer of proof.usecrate::mcp::writer::Retract;use serde_json::{json, Map, Value};usecrate::mcp::dispatch::{Ctx, ToolResult};usecrate::mcp::handlers::common::{ fail, flag, maybe_row, optional_string, require_string, require_uuid, text, Valid,};usecrate::mcp::handlers::money::book::{attach_evidence_row, EvidenceInput};usecrate::mcp::handlers::money::engine_shim::{ evidence_ref_table, external_ref, EVIDENCE_KINDS, EVIDENCE_KINDS_NEEDING_REF,};usecrate::mcp::protocol::ToolFailure;usecrate::mcp::read_db::Query;structAttachArgs { transaction_id: String, kind: String, ref_id: Option<String>, excerpt: String, source_label: Option<String>,}fn validate_attach_evidence(args: &Map<String, Value>) -> Valid<AttachArgs> {let transaction_id = require_uuid(args, "transactionId")?;let kind = require_string(args, "kind").unwrap_or_default();if !EVIDENCE_KINDS.contains(&kind.as_str()) {return fail(format!("kind must be one of: {}", EVIDENCE_KINDS.join(", ") )); }letSome(excerpt) = require_string(args, "excerpt") else {return fail("excerpt is required — the exact words the evidence carries are what the user reads \ next to the amount", ); };let ref_id = optional_string(args, "refId");ifletSome(value) = ref_id.as_ref() {if !crate::mcp::handlers::common::is_uuid(value) {return fail("refId must be a uuid"); } }if ref_id.is_none() && EVIDENCE_KINDS_NEEDING_REF.contains(&kind.as_str()) {return fail(format!("refId is required for {kind} evidence — external is the one kind that has no row to \ point at" )); }Ok(AttachArgs { transaction_id, kind, ref_id, excerpt, source_label: optional_string(args, "sourceLabel"), })}/// A money record in THIS workspace, or a refusal that names the id.fn assert_transaction(ctx: &Ctx<'_>, id: &str, kind: &str) -> Valid<()> {let found = maybe_row( ctx, &Query::on("cotton_money_transactions") .columns(&["id", "status", "moves_money"]) .eq("id", id.to_string()) .limit(1), )?;letSome(found) = found else {return fail(format!("no transaction with id {id}")); };if kind == "statement_line" && (text(&found, "status").as_deref() != Some("actual") || !flag(&found, "moves_money")) {return fail("A statement line can only prove an actual row that moves money."); }Ok(())}/// The ref this evidence is filed under — checked when it names a row, derived/// when it does not.////// A kind that points at something must point at something that is there. And/// `external`, which points at nothing, still needs a ref: the file's/// uniqueness rule for evidence skips nulls, so a null-ref row could be/// attached again on every retry — of a tool annotated idempotent. The hash is/// `match_external`'s own, so the two ways an external row arrives file it the/// same way rather than twice.fn evidence_ref_for(ctx: &Ctx<'_>, args: &AttachArgs) -> Valid<String> {let table = evidence_ref_table(&args.kind).ok_or_else(|| {ToolFailure::new(format!("EVIDENCE_REF_TABLE is missing {} — say which table its refId lives in, or null", args.kind )) })?;letSome(table) = table else {returnOk(args.ref_id.clone().unwrap_or_else(|| { external_ref( args.source_label.as_deref().unwrap_or(""), &[args.excerpt.trim()], ) })); };// The validator has already refused this kind without a refId, so a missing// one here is impossible rather than tolerated.letSome(ref_id) = args.ref_id.clone() else {return fail(format!("refId is required for {} evidence", args.kind)); };let found = maybe_row( ctx, &Query::on(table) .columns(&["id"]) .eq("id", ref_id.clone()) .limit(1), )?;if found.is_none() {return fail(format!("no {} with id {ref_id} in this database — evidence points at a row that exists, so \ find the id first rather than attaching a record to nothing", args.kind )); }Ok(ref_id)}pubfn attach_evidence(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_attach_evidence(args)?; assert_transaction(ctx, &args.transaction_id, &args.kind)?;let ref_id = evidence_ref_for(ctx, &args)?;let attached_by_label = Some(ctx.agent.to_string());let result = attach_evidence_row( ctx, &EvidenceInput { transaction_id: args.transaction_id.clone(), kind: args.kind.clone(), ref_id: Some(ref_id), excerpt: args.excerpt.clone(), source_label: args.source_label.clone(), attached_by: "assistant".to_string(), attached_by_label, }, )?; ctx.commit()?;Ok(json!({"attached": true,"id": result.id,"alreadyThere": !result.created, }))}/// Whether a person may remove this evidence from its movement: anything/// attached by the owner or an assistant for them — never a statement line's,/// which the statement's own reading attached (`import`) and which would/// only be attached again at the next reading. The one rule for the read's/// `can_delete` and the generic delete.pubfn a_person_may_remove(kind: &str, attached_by: &str) -> bool { kind != "statement_line" && attached_by != "import"}/// The generic delete's refusal of what [`a_person_may_remove`] keeps.pubconst STAYS_WITH_THE_MOVEMENT: &str = "This comes from the statement, so it stays with the movement.";/// `remove_evidence`: takes any evidence off its movement — a statement/// line's too, the assistants' documented repair path, which frees the line/// to be recorded again — through the same delete the generic verb runs, so/// it writes a change row and is undone like every other write.pubfn remove_evidence(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let id = require_uuid(args, "id")?;if maybe_row(ctx, &Query::on("cotton_money_evidence").columns(&["id"]).eq("id", id.clone()).limit(1))?.is_none() {returnErr(ToolFailure::new(format!("no evidence with id {id}"))); }crate::mcp::handlers::tables::remove_evidence_recorded(ctx, &id)}/// Take one piece of evidence off its movement: its row retracted, its/// movement's id answered.pubfn retract_evidence(ctx: &mutCtx<'_>, id: &str) -> Valid<String> {let found = maybe_row( ctx, &Query::on("cotton_money_evidence") .columns(&["id", "transaction_id"]) .eq("id", id.to_string()) .limit(1), )?;letSome(row) = found else {returnErr(ToolFailure::new(format!("no evidence with id {id}"))); };let transaction_id = text(&row, "transaction_id").unwrap_or_default(); ctx.writer()?.retract("cotton_money_evidence", id, Retract::Verb("remove_evidence")); ctx.commit()?;Ok(transaction_id)}