//! The server, as a handler can see it — in memory, and recording. //! //! Every capability on [`ToolServices`] is a bridge from a tool call to //! something OUTSIDE the person's file: the owner's phone, an object store, the //! server's own `registry.db`, the embedder, the //! documents pipeline, the vault. The real ones live in //! `cotton-server` and cannot be linked here — that is the whole of design P3. //! //! So each is filled with the smallest honest thing: an in-memory map, and a //! LEDGER of what it was asked. A suite then asserts on the ask ("the owner was //! announced to once, with this dedupe key") rather than on a socket, which is //! what the server's own suites were asserting through two more layers anyway. //! //! ABSENT IS A STATE. [`FakeServices::none`] is a server configured without any //! of it, and the tools that need a rail refuse BY NAME there — a behaviour //! with its own cases in several suites, so the double has to be able to be //! missing as well as present. #![allow(dead_code)] use cotton_core::constants::LineDirection; use cotton_tools::mcp::handlers::money::statement_visual_check::VisualStatementHeader; use std::collections::BTreeMap; use std::sync::{Arc, Mutex, MutexGuard}; use cotton_tools::mcp::dispatch::ToolServices; use cotton_tools::mcp::handlers::documents::rail::ScriptedDocuments; use cotton_tools::mcp::handlers::money::statement_visual_check::{ StatementFigures, StatementVisualVerifier, VisualStatementLine, VisualStatementReading, }; use cotton_tools::rails::{DevToolsRail, SealedSecret, VaultRail}; use serde_json::{json, Value}; // ── the owner's phone ─────────────────────────────────────────────────────── /// What `notify_owner` was asked to announce, in order. #[derive(Debug, Default)] pub struct FakeNotify { sent: Mutex>, /// When set, every announcement fails with this sentence — an outage is a /// state a tool has to answer for, not a reason to lose the record. failure: Mutex>, } impl FakeNotify { pub fn new() -> Arc { Arc::new(FakeNotify::default()) } /// Every payload, in the order it was announced. pub fn sent(&self) -> Vec { self.sent .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .clone() } pub fn count(&self) -> usize { self.sent().len() } /// Make the rail fail — the outage branch. pub fn fail_with(&self, sentence: &str) { *self .failure .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sentence.to_string()); } fn announce(&self, payload: &Value) -> Result { if let Some(sentence) = self .failure .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .clone() { return Err(sentence); } self.sent .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .push(payload.clone()); Ok(json!({ "outcome": "sent" })) } } // ── the object store ──────────────────────────────────────────────────────── /// An object store that is a map, and a ledger of what was asked of it. /// /// The four media rails and the two signers all read this one object, so a /// suite that uploads through `presign_put` and then heads the key sees what a /// real store would show it. #[derive(Debug, Default)] pub struct FakeMedia { inner: Mutex, } #[derive(Debug, Default)] struct MediaState { objects: BTreeMap>, /// `("head", key)`, `("get", key)`, `("delete", "a, b")`, `("presign", key)`. calls: Vec<(String, String)>, presigns: Vec, } /// One url this store was asked to mint, with everything the caller stated /// about it. /// /// [`FakeMedia::calls`] records that a presign happened and against which key; /// a suite about an UPLOAD needs more than that — that the url is a `PUT`, that /// the content type travelled, that the byte size the caller declared is the /// one the url is good for — so those are kept here beside it rather than /// squeezed into the call ledger's pair of strings. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Presign { /// `"PUT"` for an upload url, `"GET"` for a fetch one. pub method: String, pub key: String, pub ttl_seconds: u64, /// Stated only for an upload — a fetch url carries the object's own type. pub content_type: Option, pub byte_size: Option, } impl FakeMedia { pub fn new() -> Arc { Arc::new(FakeMedia::default()) } /// Put bytes at a key, as an upload would have. pub fn put(&self, key: &str, bytes: Vec) { self.lock().objects.insert(key.to_string(), bytes); } /// Take an object back out — a row that outlived its bytes, which is the /// offline-first state every bytes tool has to answer for. pub fn remove(&self, key: &str) { self.lock().objects.remove(key); } pub fn has(&self, key: &str) -> bool { self.lock().objects.contains_key(key) } pub fn get(&self, key: &str) -> Option> { self.lock().objects.get(key).cloned() } /// Every key the store holds, sorted. pub fn keys(&self) -> Vec { self.lock().objects.keys().cloned().collect() } /// Every call this store was asked to make, in order. pub fn calls(&self) -> Vec<(String, String)> { self.lock().calls.clone() } /// Every key a signed link was minted for — GET and PUT alike, in order. /// /// "No link was minted" is an assertion several suites make: bytes that /// travelled through the protocol must not ALSO have been handed out as a /// URL, and an upload slot must be signed exactly once. pub fn presigns(&self) -> Vec { self.calls() .into_iter() .filter(|(what, _)| what == "presign" || what == "presign_put") .map(|(_, key)| key) .collect() } /// The same mintings, whole — for a suite that asserts about an UPLOAD /// rather than about whether one happened: the method, the content type /// that travelled and the byte size the caller declared. pub fn presign_details(&self) -> Vec { self.lock().presigns.clone() } fn lock(&self) -> MutexGuard<'_, MediaState> { self.inner .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) } fn record(&self, what: &str, detail: String) { self.lock().calls.push((what.to_string(), detail)); } } // ── the server's own database ─────────────────────────────────────────────── /// `registry.db`, in memory — the owner's relay name and the scopes this server /// hosts. #[derive(Debug, Default)] pub struct FakeRegistry { inner: Mutex, } #[derive(Debug, Default)] struct RegistryState { owner_phones: BTreeMap, hosted: Vec<(String, String)>, } impl FakeRegistry { pub fn new() -> Arc { Arc::new(FakeRegistry::default()) } /// The relay name this workspace's owner is reachable at — what /// `send_message` cannot produce a conversation key without. pub fn set_owner_phone(&self, workspace_id: &str, phone: &str) { self.lock() .owner_phones .insert(workspace_id.to_string(), phone.to_string()); } /// Say that this server HOSTS this scope for this workspace. pub fn host_scope(&self, workspace_id: &str, scope: &str) { self.lock() .hosted .push((workspace_id.to_string(), scope.to_string())); } fn lock(&self) -> MutexGuard<'_, RegistryState> { self.inner .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) } } // ── the vault ─────────────────────────────────────────────────────────────── /// A vault that is not one: it stamps the row id and the payload so a suite can /// prove the column was written THROUGH the rail, and can open what it sealed, /// without this crate linking the real scheme. /// /// The real one is `cotton_server::vault`, AES-256-GCM under a per-workspace /// master key that only the owner's own devices can unwrap. #[derive(Debug, Default)] pub struct FakeVault; impl FakeVault { pub fn new() -> Arc { Arc::new(FakeVault) } /// The version this fake seals at — named so a suite can assert the column /// rather than re-deriving the number. pub const VERSION: u32 = 1; /// What [`FakeVault::seal`] writes for this row and payload, so a suite can /// assert the stored column without re-deriving the shape. pub fn sealed(secret_id: &str, payload: &str) -> String { format!("fake-seal:{secret_id}:{payload}") } } impl VaultRail for FakeVault { fn seal(&self, secret_id: &str, payload: &[u8]) -> Option { Some(SealedSecret { value_enc: FakeVault::sealed(secret_id, &String::from_utf8_lossy(payload)), vmk_version: FakeVault::VERSION, }) } fn open(&self, secret_id: &str, vmk_version: u32, sealed: &str) -> Option> { if vmk_version != FakeVault::VERSION { return None; } // The row id is the associated data: a payload sealed for one row does // not open as another's, here either. sealed .strip_prefix(&format!("fake-seal:{secret_id}:")) .map(|payload| payload.as_bytes().to_vec()) } } // ── the chat relay's doorbell ─────────────────────────────────────────────── /// "And the sweep was woken" — a count, because that is the whole observable. #[derive(Debug, Default)] pub struct FakeWake { rung: Mutex, } impl FakeWake { pub fn new() -> Arc { Arc::new(FakeWake::default()) } pub fn rings(&self) -> usize { *self .rung .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) } } // ── the meaning lane ──────────────────────────────────────────────────────── /// One embedded query, and what it was asked to embed. #[derive(Debug, Default)] pub struct FakeEmbedder { asked: Mutex>, answer: Mutex, String>>>, } impl FakeEmbedder { pub fn new() -> Arc { Arc::new(FakeEmbedder::default()) } /// Every query string this lane was handed, in order. pub fn asked(&self) -> Vec { self.asked .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .clone() } /// The quantised vector the next call answers with. pub fn answer_with(&self, vector: Vec) { *self .answer .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Ok(vector)); } /// The provider's own refusal — `unreachable`, which a degraded search must /// say out loud rather than answering a silently shorter list. pub fn refuse_with(&self, sentence: &str) { *self .answer .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Err(sentence.to_string())); } } // ── the developer tools ───────────────────────────────────────────────────── /// A server with `COTTON_DEV_TOOLS` on: the rail is the switch and nothing /// more. #[derive(Debug, Default)] pub struct FakeDevTools; impl FakeDevTools { pub fn new() -> Arc { Arc::new(FakeDevTools) } } impl DevToolsRail for FakeDevTools {} // ── the bag ───────────────────────────────────────────────────────────────── /// Every double, and the [`ToolServices`] built over them. /// /// The doubles are held separately from the services so a suite can assert on /// what was asked after the call: `services.notify.sent()`, `media.keys()`, /// `registry.shares()`. pub struct FakeServices { pub notify: Arc, pub media: Arc, pub registry: Arc, pub documents: Arc, pub vault: Arc, pub wake: Arc, pub embedder: Arc, /// The developer tools' rail. Present as a DOUBLE always and wired into /// [`FakeServices::services`] only by [`FakeServices::with_dev_tools`], /// because the switch is off on every ordinary server and a harness whose /// default had it on would assert nothing about that. pub dev_tools: Arc, pub statement_visual: Arc, /// What the handlers actually see. pub services: ToolServices, } /// The synthetic page renderer is present explicitly so successful harness /// reads exercise the visual gate rather than bypassing it. #[derive(Debug, Default)] pub struct FakeStatementVisual { fixtures: Mutex>, recordings: Mutex>, } impl FakeStatementVisual { pub fn new() -> Arc { Arc::new(FakeStatementVisual::default()) } /// Bind a fixture's original bytes to the statement identity the trusted /// renderer receives, as the production adapter binds media bytes. pub fn recording_for(&self, statement_id: &str, figures: StatementFigures) { self.recordings.lock().unwrap().insert(statement_id.into(), figures); } pub fn fixture_for(&self, statement_id: &str, bytes: &'static [u8]) { self.recordings.lock().unwrap().remove(statement_id); self.fixtures .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .insert(statement_id.to_string(), bytes); } } impl StatementVisualVerifier for FakeStatementVisual { fn rendered_reading( &self, _workspace_id: &str, statement_id: &str, _candidate: &StatementFigures, ) -> Result { if let Some(figures) = self.recordings.lock().unwrap().get(statement_id).cloned() { return Ok(VisualStatementReading { has_text_layer: true, font_glyph_reading: Some(figures.clone()), figures }); } // The harness's default paper is the known clean Meridian fixture, // never whatever a submitter or model claims its figures were. let held = self.fixtures.lock().unwrap(); let default = include_bytes!("../fixtures/statement_visual_clean.pdf").as_slice(); let bytes = held.get(statement_id).unwrap_or(&default); { let clean = include_bytes!("../fixtures/statement_visual_clean.pdf").as_slice(); let decoy = include_bytes!("../fixtures/statement_visual_decoy.pdf").as_slice(); if *bytes != clean && *bytes != decoy { return Err("unknown rendered fixture".into()); } // Independent OCR and font-decoded fixtures. Poppler rendering and // Tesseract on the PDF prove the hidden amount is absent in the // page image; these known readings keep CI platform-independent. let figures = StatementFigures { header: VisualStatementHeader { page: 1, period_start: "2026-03-01".into(), period_end: "2026-03-31".into(), opening_balance_minor: Some(12_045_000), closing_balance_minor: Some(10_520_000) }, lines: [(1,"2026-03-01",12_045_000,LineDirection::In,12_045_000), (1,"2026-03-03",245_000,LineDirection::Out,11_800_000), (1,"2026-03-07",4_500_000,LineDirection::In,16_300_000), (1,"2026-03-12",1_280_000,LineDirection::Out,15_020_000), (2,"2026-03-19",100_000,LineDirection::Out,14_920_000), (2,"2026-03-26",4_400_000,LineDirection::Out,10_520_000)] .into_iter().map(|(page,date,amount,direction,balance)| VisualStatementLine { page, posted_on: date.into(), amount_minor: amount, direction, balance_after_minor: Some(balance), ignored: date == "2026-03-01" }).collect(), }; let mut glyphs = figures.clone(); if *bytes == decoy { let mut hidden = glyphs.lines[4].clone(); hidden.amount_minor = 999_999; glyphs.lines.push(hidden); } return Ok(VisualStatementReading { has_text_layer: true, font_glyph_reading: Some(glyphs), figures }); } } } impl std::fmt::Debug for FakeServices { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("FakeServices") .field("services", &self.services) .finish() } } /// The public origin the fake server answers with — a share link's home, and /// the address a feedback registration REFUSES to mint a credential without. pub const FAKE_PUBLIC_URL: &str = "https://test.cottondb.com"; impl FakeServices { /// A server with every capability present — the shape a hosted server with /// an object store, a push rail and a registry has. pub fn new() -> FakeServices { let notify = FakeNotify::new(); let media = FakeMedia::new(); let registry = FakeRegistry::new(); let documents = ScriptedDocuments::new(); let vault = FakeVault::new(); let wake = FakeWake::new(); let embedder = FakeEmbedder::new(); let dev_tools = FakeDevTools::new(); let statement_visual = FakeStatementVisual::new(); let services = ToolServices { backup_now: None, tool_signer: None, notify: Some({ let rail = Arc::clone(¬ify); Arc::new(move |payload: &Value| rail.announce(payload)) }), media_available: true, media_head: Some({ let store = Arc::clone(&media); Arc::new(move |key: &str| { store.record("head", key.to_string()); Ok(store.has(key)) }) }), media_get: Some({ let store = Arc::clone(&media); Arc::new(move |key: &str| { store.record("get", key.to_string()); Ok(store.get(key)) }) }), media_put: Some({ let store = Arc::clone(&media); Arc::new(move |key: &str, bytes: &[u8], _content_type: &str| { store.record("put", key.to_string()); store.put(key, bytes.to_vec()); Ok(()) }) }), presign_put: Some({ let store = Arc::clone(&media); Arc::new( move |key: &str, ttl: u64, content_type: &str, byte_size: u64| { store.record("presign_put", key.to_string()); store.lock().presigns.push(Presign { method: "PUT".to_string(), key: key.to_string(), ttl_seconds: ttl, content_type: Some(content_type.to_string()), byte_size: Some(byte_size), }); Ok(( format!("{FAKE_PUBLIC_URL}/objects/{key}?put&exp={ttl}"), vec![ ("content-type".to_string(), content_type.to_string()), ("content-length".to_string(), byte_size.to_string()), ], )) }, ) }), presign: Some({ let store = Arc::clone(&media); Arc::new(move |key: &str, ttl: u64| { store.record("presign", key.to_string()); store.lock().presigns.push(Presign { method: "GET".to_string(), key: key.to_string(), ttl_seconds: ttl, content_type: None, byte_size: None, }); Ok(format!("{FAKE_PUBLIC_URL}/objects/{key}?exp={ttl}")) }) }), documents: Some(Arc::clone(&documents) as Arc), embed_query: Some({ let embedder = Arc::clone(&embedder); Arc::new(move |text: &str| { embedder .asked .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .push(text.to_string()); embedder .answer .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .clone() .unwrap_or_else(|| Ok(vec![0u8; 32])) }) }), public_url: Some(FAKE_PUBLIC_URL.to_string()), statement_visual: Some( Arc::clone(&statement_visual) as Arc ), vault: Some(Arc::clone(&vault) as Arc), // OFF, like every real server that has not been told otherwise. dev_tools: None, this_file: None, kit_source: None, record_moves: None, owner_memory: None, stored_photos: None, }; FakeServices { notify, media, registry, documents, vault, wake, embedder, dev_tools, statement_visual, services, } } /// Turn the developer tools ON — what `COTTON_DEV_TOOLS=1` does to a real /// server, and the only way a `dev_` tool runs in a suite. pub fn with_dev_tools(&mut self) { self.services.dev_tools = Some(Arc::clone(&self.dev_tools) as Arc); } /// A server configured with NONE of it — the state every "refuses by name" /// case is asserted against. The doubles still exist, so a suite can prove /// nothing was asked of them. pub fn none() -> FakeServices { let mut bag = FakeServices::new(); bag.services = ToolServices::none(); bag } /// A server whose push rail is DOWN, and nothing else missing — the state /// a tool that announces best-effort has to answer for without losing the /// row it already wrote. pub fn without_notify(&mut self) { self.services.notify = None; } /// The same, but keeping the registry — a server with no object store still /// has its own database beside the person's file. pub fn without_media(&mut self) { self.services.media_available = false; self.services.media_head = None; self.services.media_get = None; self.services.presign = None; self.services.presign_put = None; self.services.documents = None; } } impl Default for FakeServices { fn default() -> FakeServices { FakeServices::new() } }