//! The MCP tool pairs, held to one written answer on both sides. //! //! Cotton serves the same tools twice: from these Rust handlers (the phone's) //! and from the Worker's TypeScript (`apps/business/src/mcp/tools`). Each file //! in `tests/goldens/` is a list of cases — a synthetic seed, a run of tool //! calls, and what each call answered — and BOTH suites read the same file: //! this one, and `apps/business/test/goldens.test.ts`. A case under `cases` //! answers the same on both sides; a case under `differs` is a known //! difference between the two, written down with each side's answer //! (`rust`, `worker`) so neither drifts unseen while it waits to be settled. //! //! A step's args may carry an earlier answer's value: a string that is //! exactly `{{n.path}}` becomes the value at that dotted path of step `n`'s //! answer, as the tool gave it (before normalising) — `{{0.record.id}}`. //! //! A step is `{ tool, args, expect }`, or `{ tool, args, rust, worker }` in a //! `differs` case; an expectation is `{ "answer": }` or //! `{ "refusal": "" }`. The calls are made by a read-and-write //! assistant connection (not the owner). //! //! Both sides start in the zone Asia/Kolkata. A seed row is `{ kind, id, data, at? }`, a row of the kit's table `kind` //! written straight into the file (here as a device's op, on the Worker //! through the admin import) at `at` (default 2026-01-01T00:00:00.000Z). //! //! THE NORMALISATION, applied to every answer before it is compared (the //! TypeScript applies the same, see `normalised` there): //! //! 1. Every UUID in any string (lowercase 8-4-4-4-12 hex) that the case did //! not write itself — in its seed's ids or literally in a step's args — //! becomes ``, ``, … numbered by first appearance through the //! case, walking each answer depth first in its own key order. //! 2. Every RFC 3339 instant in any string becomes ``. //! 3. Today's date (the harness clock's, UTC, `YYYY-MM-DD`) in any string //! becomes ``: the phone's harness runs on a fixed clock, the Worker //! on the real one. //! 4. The value of a key named in [`VOLATILE_KEYS`] becomes `""`. //! 5. The Worker's undo envelope — the `change_id` and `undoable` (and, with //! them, `changes`) its change log adds at the top of a write's answer //! (`apps/business/src/changes.ts`) — is left out on both sides, because //! the phone answers no write with it: a step marked `"envelope": true` //! keeps it, and the one such case is under `differs`. //! //! Re-recording: `COTTON_GOLDENS_PRINT=1` prints each step's normalised answer //! (`GOLDENfilecasestepjson`) instead of asserting, and //! `COTTON_GOLDENS_FILE=sessions.json` runs that one file alone. mod support; use std::collections::{BTreeSet, HashMap}; use regex::Regex; use serde::Deserialize; use serde_json::{json, Map, Value}; use support::harness::{Harness, HARNESS_NOW}; use support::mcp::{call_tool_raw, mint_token}; /// Keys whose values move from run to run on either side. const VOLATILE_KEYS: &[&str] = &["change_id"]; const SEED_AT: &str = "2026-01-01T00:00:00.000Z"; const GOLDENS: &[(&str, &str)] = &[ ("briefing.json", include_str!("goldens/briefing.json")), ( "memory_projects.json", include_str!("goldens/memory_projects.json"), ), ( "merge_people.json", include_str!("goldens/merge_people.json"), ), ("sessions.json", include_str!("goldens/sessions.json")), ( "todos_secrets.json", include_str!("goldens/todos_secrets.json"), ), ("values.json", include_str!("goldens/values.json")), ]; #[derive(Deserialize)] struct Golden { #[serde(default)] cases: Vec, #[serde(default)] differs: Vec, } #[derive(Deserialize)] struct Case { name: String, #[serde(default)] seed: Vec, steps: Vec, } #[derive(Deserialize)] struct SeedRow { kind: String, id: String, data: Map, at: Option, } #[derive(Deserialize)] struct Step { tool: String, #[serde(default)] args: Value, expect: Option, rust: Option, #[serde(default)] envelope: bool, } /// Rule 5: the answer without the Worker's undo envelope. fn without_envelope(mut answer: Value) -> Value { if let Some(map) = answer.as_object_mut() { if map.contains_key("change_id") { map.shift_remove("changes"); } map.shift_remove("change_id"); map.shift_remove("undoable"); } answer } fn uuid_re() -> Regex { Regex::new(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") .expect("the uuid pattern") } fn instant_re() -> Regex { Regex::new(r"\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})") .expect("the instant pattern") } fn ref_re() -> Regex { Regex::new(r"^\{\{(\d+)\.([^}]+)\}\}$").expect("the reference pattern") } /// The case's id map: the ids it wrote itself, and each new id's token. struct Ids { own: BTreeSet, tokens: HashMap, } impl Ids { fn new(case: &Case) -> Ids { let mut own: BTreeSet = case.seed.iter().map(|row| row.id.clone()).collect(); let uuid = uuid_re(); for step in &case.steps { for found in uuid.find_iter(&step.args.to_string()) { own.insert(found.as_str().to_string()); } } Ids { own, tokens: HashMap::new(), } } fn token(&mut self, id: &str) -> String { if self.own.contains(id) { return id.to_string(); } if let Some(token) = self.tokens.get(id) { return token.clone(); } let token = format!("", self.tokens.len() + 1); self.tokens.insert(id.to_string(), token.clone()); token } } fn normalise_text(text: &str, ids: &mut Ids) -> String { let uuid = uuid_re(); let mut out = String::new(); let mut last = 0; for found in uuid.find_iter(text) { out.push_str(&text[last..found.start()]); out.push_str(&ids.token(found.as_str())); last = found.end(); } out.push_str(&text[last..]); let out = instant_re().replace_all(&out, "").into_owned(); out.replace(&HARNESS_NOW[..10], "") } fn normalise(value: &Value, ids: &mut Ids) -> Value { match value { Value::String(text) => Value::String(normalise_text(text, ids)), Value::Array(items) => { Value::Array(items.iter().map(|item| normalise(item, ids)).collect()) } Value::Object(map) => Value::Object( map.iter() .map(|(key, item)| { let item = if VOLATILE_KEYS.contains(&key.as_str()) { json!("") } else { normalise(item, ids) }; (key.clone(), item) }) .collect(), ), other => other.clone(), } } /// A step's args with each `{{n.path}}` replaced by that earlier answer's value. fn resolved(args: &Value, answers: &[Value]) -> Value { match args { Value::String(text) => match ref_re().captures(text) { Some(c) => { let step: usize = c[1].parse().expect("a step number"); let mut at = answers.get(step).unwrap_or(&Value::Null); for key in c[2].split('.') { at = match key.parse::() { Ok(n) => at.get(n), Err(_) => at.get(key), } .unwrap_or(&Value::Null); } at.clone() } None => args.clone(), }, Value::Array(items) => { Value::Array(items.iter().map(|item| resolved(item, answers)).collect()) } Value::Object(map) => Value::Object( map.iter() .map(|(k, v)| (k.clone(), resolved(v, answers))) .collect(), ), other => other.clone(), } } /// The kit table's file in this store, and the key a seed's column is kept under. fn table_of(kind: &str) -> &'static str { match kind { "project" => "cotton_memory_projects", "memory" => "cotton_memories", "project_link" => "cotton_project_links", "note" => "cotton_notes", "person" => "cotton_people", other => panic!("a golden seeds no {other} rows"), } } fn column_of(kind: &str, key: &str) -> String { match (kind, key) { ("project_link", "project") => "project_id".to_string(), ("note", "project") => "project_id".to_string(), _ => key.to_string(), } } fn seed(h: &Harness, rows: &[SeedRow]) { let ops: Vec = rows .iter() .enumerate() .map(|(n, row)| { let at = row.at.clone().unwrap_or_else(|| SEED_AT.to_string()); let mut patch = Map::new(); patch.insert("id".to_string(), json!(row.id)); patch.insert("workspace_id".to_string(), json!(h.workspace_id)); for (key, value) in &row.data { patch.insert(column_of(&row.kind, key), value.clone()); } patch.entry("created_at").or_insert_with(|| json!(at)); patch.entry("updated_at").or_insert_with(|| json!(at)); json!({ "opId": format!("01JGOLDEN{:017}", n), "deviceId": "device:golden", "kind": "upsert", "table": table_of(&row.kind), "rowId": row.id, "patch": patch, "hlc": format!("1700000000{:03}:0000:device:golden", n), "schemaVersion": cotton_store::schema::ddl::SCHEMA_VERSION, }) }) .collect(); if !ops.is_empty() { h.seed(&ops); } } /// The Worker's personal object keeps its zone on the database /// (`apps/business/test/personal.ts`: Asia/Kolkata); the phone reads the /// workspace's zone from its news settings, so every case starts there too. fn same_zone(h: &Harness) { h.seed(&[json!({ "opId": "01JGOLDENZONE000000000000", "deviceId": "device:golden", "kind": "upsert", "table": "cotton_news_settings", "rowId": h.workspace_id, "patch": { "workspace_id": h.workspace_id, "timezone": "Asia/Kolkata", "created_at": SEED_AT, "updated_at": SEED_AT }, "hlc": "1699999999999:0000:device:golden", "schemaVersion": cotton_store::schema::ddl::SCHEMA_VERSION, })]); } fn run_case(file: &str, case: &Case, print: bool) -> Vec { let mut h = Harness::new_as_first(); let secret = mint_token(&mut h, &["read", "write"], "Claude"); same_zone(&h); seed(&h, &case.seed); let mut ids = Ids::new(case); let mut failures = Vec::new(); let mut answers: Vec = Vec::new(); for (n, step) in case.steps.iter().enumerate() { let answer = call_tool_raw(&h, &secret, &step.tool, resolved(&step.args, &answers)); let got = if answer.is_error { answers.push(Value::Null); json!({ "refusal": normalise_text(&answer.text, &mut ids) }) } else { let parsed: Value = serde_json::from_str(&answer.text).unwrap_or(Value::String(answer.text.clone())); let shown = if step.envelope { parsed.clone() } else { without_envelope(parsed.clone()) }; let got = json!({ "answer": normalise(&shown, &mut ids) }); answers.push(parsed); got }; if print { println!("GOLDEN\t{file}\t{}\t{n}\t{got}", case.name); continue; } let want = step .expect .as_ref() .or(step.rust.as_ref()) .unwrap_or_else(|| panic!("{file} {} step {n} expects nothing", case.name)); if &got != want { failures.push(format!( "{file} · {} · step {n} ({}):\n want {}\n got {}", case.name, step.tool, want, got )); } } failures } /// RULE: A tool both the phone and the Worker serve answers each golden case as written, and a known difference between the two is written down with both answers. #[test] fn every_golden_case_answers_as_written() { let print = std::env::var_os("COTTON_GOLDENS_PRINT").is_some(); let only = std::env::var("COTTON_GOLDENS_FILE").ok(); let mut failures = Vec::new(); for (file, raw) in GOLDENS .iter() .filter(|(file, _)| only.as_deref().is_none_or(|only| only == *file)) { let golden: Golden = serde_json::from_str(raw).unwrap_or_else(|e| panic!("{file} parses: {e}")); assert!( !golden.cases.is_empty() || !golden.differs.is_empty(), "{file} holds no case" ); for case in golden.cases.iter().chain(&golden.differs) { failures.extend(run_case(file, case, print)); } } assert!( failures.is_empty(), "{} golden step(s) answered otherwise:\n{}", failures.len(), failures.join("\n") ); } /// Every file in `tests/goldens/` is read here: the TypeScript reads the folder /// by glob, so a file this list missed would be held on one side only. #[test] fn every_golden_file_is_read_by_this_suite() { let dir = cotton_store::manifest_dir().join("tests").join("goldens"); let mut on_disk: Vec = std::fs::read_dir(&dir) .expect("the goldens folder") .map(|entry| { entry .expect("an entry") .file_name() .to_string_lossy() .into_owned() }) .filter(|name| name.ends_with(".json")) .collect(); on_disk.sort(); let read: Vec = GOLDENS .iter() .map(|(file, _)| (*file).to_string()) .collect(); assert_eq!(on_disk, read); }