//! THE HARNESS — a real file, a real fold, a real handler table.//!//! ============================================================================//! ITS SHAPE, so every suite builds on the same thing://!//! let mut h = Harness::new(); // a provisioned file//! let secret = mint_token(&mut h, &["read", "write"], "Claude");//! let answer = call_tool(&h, &secret, "create_todo", json!({ "title": "…" }));//!//! h.workspace_id the provisioned workspace, and `h.owner_id` its owner//! h.clock a `FixedClock` starting at 2026-09-08T10:00:00Z//! h.services the `FakeServices` bag — `h.services.notify.sent()`, …//! h.with(|db| …) the driver itself, for the rows only SQL can seed//! h.seed(ops) ops folded the way a device's push folds them//! h.ops_since(n) what a device would pull back//!//! Nothing here mocks SQLite — the whole point of the store is that the file is//! the truth, and a suite that mocks it proves nothing about the file. Nothing//! here speaks HTTP either: that is the server's, and the suites that are ABOUT//! it stayed there (see `support/mod.rs`).//!//! WHAT DOES NOT COME ACROSS from `cotton-server`'s harness, and why://! everything that is a SERVER. There is no registry database, no axum router,//! no device signing and no token store — a connection here is a name and a set//! of scopes, because that is all a HANDLER ever sees of one. Minting is//! `POST /v1/mcp-tokens`'s job and its suite stayed with it.//! ============================================================================#![allow(dead_code)]use std::cell::RefCell;use std::collections::HashMap;use std::sync::Arc;use cotton_store::driver::Driver;use cotton_store::file_identity::{read_file_identity, FileIdentity};use cotton_store::fold::fold_ops;use cotton_store::meta::Meta;use cotton_store::protocol::types::CottonOp;use cotton_tools::clock::FixedClock;use cotton_tools::random::{Random, SystemRandom};use rusqlite::types::ValueasSqlValue;use serde_json::{Map, Value};usesuper::fakes::FakeServices;/// When a harness's clock starts — the same instant `cotton-server`'s harness/// uses, so a ported suite's fixed dates still line up.pubconst HARNESS_NOW: &str = "2026-09-08T10:00:00.000Z";pubuse cotton_tools::test_fixtures::{ author_fact, reconcile, reconcile_all, reconcile_pulled, written_table,};/// The device id the harness's own seeds are written under. A suite that folds/// ops as a second device picks its own.pubconst SEED_DEVICE_ID: &str = "device:harness";/// One connection, as a HANDLER sees one: a name, an id and a set of scopes.////// There is no secret here in any real sense — the string [`crate::support::mcp::mint_token`]/// hands back is a lookup key. What a token IS, how it is minted and how it is/// authenticated is the transport's, and its suites stayed in `cotton-server`.#[derive(Debug, Clone)]pubstructConnection {pub id: String,pub name: String,pub scopes: Vec<String>,}/// One audit line a tool asked for. `Ctx::audit` is a closure the CALLER/// supplies — the server writes a `cotton_mcp_audit` row and the phone writes/// nothing — so what a suite can assert here is the ask.#[derive(Debug, Clone, PartialEq, Eq)]pubstructAuditLine {pub tool: String,pub summary: String,}pubstructHarness {/// The person's file.pub db: Driver,/// Which file `db` is, read off it the way every open file reads it.pub file: FileIdentity,pub workspace_id: String,pub owner_id: String,pub clock: FixedClock,pub services: FakeServices,pub random: Arc<dynRandom>, connections: RefCell<HashMap<String, Connection>>, audit: RefCell<Vec<AuditLine>>,}impl std::fmt::DebugforHarness {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Harness") .field("workspace_id", &self.workspace_id) .field("owner_id", &self.owner_id) .finish() }}implHarness {/// A provisioned file with every server capability present.pubfn new() -> Harness {Harness::with_services(FakeServices::new()) }/// A provisioned file on a server configured WITHOUT any capability — what/// every "refuses by name" case is asserted against.pubfn without_services() -> Harness {Harness::with_services(FakeServices::none()) }pubfn with_services(services: FakeServices) -> Harness {Self::with_services_in(services, "workspace") }/// A provisioned file holding the kit's tools: a synthetic household gets/// its tools by import, through the one helper both lanes share/// (`cotton_tools::kit::import_kit_into`), because no tool is built in/// (72nd amendment, 21 Oct 2026).////// The kitted file is built ONCE per test binary and workspace and copied/// for every test after (`cotton_store::test_template`): importing the/// kit costs 12 s a test on this repo's Mac and up to 85 s on the CI/// runner, where it pushed a guards shard past fifteen minutes (run 5971).pubfn with_services_in(services: FakeServices, workspace_label: &str) -> Harness {let ids = (synthetic_uuid(workspace_label), synthetic_uuid("owner"));Self::kitted(services, ids) }/// A fresh kitted file under the ids a process's first [`Harness::new`]/// has, so it is a copy of the one shared kitted file and never a build of/// its own: for a test that makes harness after harness in one process/// (each golden case), never two alive at once. [`Harness::new`] gives/// every later harness new ids, and new ids are a new kitted file to/// build (a few seconds each, fsync-bound): thirty cases timed out.pubfn new_as_first() -> Harness {Self::kitted(FakeServices::new(), (synthetic_uuid_at("workspace", 0), synthetic_uuid_at("owner", 1))) }fn kitted(services: FakeServices, (workspace_id, owner_id): (String, String)) -> Harness {super::published::served();// Every process that folds installs the derive pass at start, as the// server does (`startup_schema`). A harness copied from the cached// kitted file commits nothing through the writer before a test's own// raw writes, so without it those left the computed index stale and// a list over a computed column refused ("This list is being worked// out") — every warm run of mcp_archived_records' builtin sweep. cotton_tools::derive::install();let db = cotton_store::test_template::cached_in_memory_for_test( &format!("kit-{}", fixture_family(&workspace_id, &owner_id)), &fixture_version(), &Self::meta(&workspace_id, &owner_id), |db| {Self::found(db, &workspace_id, &owner_id);let now = chrono::DateTime::parse_from_rfc3339(HARNESS_NOW).expect("the harness's instant").with_timezone(&chrono::Utc);// What creation writes (the shell), then the kit, as a Personal that imported it. cotton_tools::presentation::write_shell(db, now, Arc::new(SystemRandom), cotton_store::mint::Held::Served).expect("the shell writes"); cotton_tools::kit::import_kit_into(db, now, Arc::new(SystemRandom)).expect("the kit imports");Ok(()) }, ) .expect("the kitted file");Self::over(db, workspace_id, owner_id, services) }/// A provisioned file holding no tool at all — what a database nobody/// imported a tool into is.pubfn bare() -> Harness {Self::bare_in(FakeServices::new(), "workspace") }fn bare_in(services: FakeServices, workspace_label: &str) -> Harness {// The app reads Cotton's published databases; so does every harness.super::published::served(); cotton_tools::derive::install();let workspace_id = synthetic_uuid(workspace_label);let owner_id = synthetic_uuid("owner");let db = cotton_store::test_template::create_workspace_in_memory_for_test(&Self::meta(&workspace_id, &owner_id)) .expect("a fresh file");Self::found(&db, &workspace_id, &owner_id);Self::over(db, workspace_id, owner_id, services) }fn meta(workspace_id: &str, owner_id: &str) -> Meta {Meta { workspace_id: workspace_id.to_string(), owner_id: owner_id.to_string(), device_id: SEED_DEVICE_ID.to_string(), last_server_seq: 0, last_hlc: None, } }/// The workspace row a new file is founded with.fn found(db: &Driver, workspace_id: &str, owner_id: &str) {// Every domain table keys back to `cotton_workspaces`, so a file with// only `_meta` fails a foreign key on the first write into it. The// file is the owner's own (Mine), whose namespace is its id. db.run("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at, kind, namespace, \ _hlc) VALUES (?, ?, ?, ?, 'personal', ?, '')", &[SqlValue::Text(workspace_id.to_string()),SqlValue::Text("Cotton".to_string()),SqlValue::Text(owner_id.to_string()),SqlValue::Text(HARNESS_NOW.to_string()),SqlValue::Text(workspace_id.to_string()), ], ) .expect("the workspace row every domain row keys back to"); reconcile(db, "cotton_workspaces"); }fn over(db: Driver, workspace_id: String, owner_id: String, services: FakeServices) -> Harness {let file = read_file_identity(&db) .expect("the file reads") .expect("the file is seeded");Harness { db, file, workspace_id, owner_id, clock: FixedClock::default_start(), services, random: Arc::new(SystemRandom), connections: RefCell::new(HashMap::new()), audit: RefCell::new(Vec::new()), } }/// A harness over a file already on disk — a COPY of a seeded household,/// for a timing run; its first workspace is the one read.pubfn open_copy(path: &str) -> Harness {let db = Driver::open(path).expect("the copied file opens");let row = db .all("SELECT id, owner_user_id FROM cotton_workspaces ORDER BY created_at LIMIT 1", &[], ) .expect("the workspace") .into_iter() .next() .expect("a workspace");let workspace_id = row.text("id").expect("an id").to_string();let owner_id = row.text("owner_user_id").expect("an owner").to_string();let file = read_file_identity(&db) .expect("the file reads") .expect("the file is seeded");Harness { db, file, workspace_id, owner_id, clock: FixedClock::default_start(), services: FakeServices::new(), random: Arc::new(SystemRandom), connections: RefCell::new(HashMap::new()), audit: RefCell::new(Vec::new()), } }/// The driver itself — for the rows no MCP verb writes.////// The shape `h.deps.files.open(&h.workspace_id).with(|db| …)` had on the/// server, minus the two layers that were about finding the file.////// Whatever the closure wrote past the receipts — a raw `INSERT` or/// `UPDATE` — is given them after ([`reconcile`], every table).pubfn with<T>(&self, f: implFnOnce(&Driver) -> T) -> T {let out = f(&self.db);for spec in cotton_store::schema::table_specs::TABLE_SPECS { reconcile(&self.db, spec.name); } out }/// One statement, and a panic naming it when it does not land. A row it/// writes is then given the receipt the fold reads it from/// ([`reconcile`]).pubfn run(&self, sql: &str, params: &[SqlValue]) {self.db .run(sql, params) .unwrap_or_else(|error| panic!("the write did not land ({error}): {sql}"));ifletSome(table) = written_table(sql) { reconcile(&self.db, &table); } }/// [`Harness::run`] for a row mint now refuses, written as a file that held/// it before the rule would hold it: its receipt arrives as the serving/// Mac's answer ([`reconcile_pulled`]), so a case proves the wall/// downstream of that rule.pubfn run_held(&self, sql: &str, params: &[SqlValue]) {self.db .run(sql, params) .unwrap_or_else(|error| panic!("the write did not land ({error}): {sql}"));ifletSome(table) = written_table(sql) { reconcile_pulled(&self.db, &table); } }/// Every row a query answers, as JSON objects — the shape most ported/// assertions read.pubfn all(&self, sql: &str, params: &[SqlValue]) -> Vec<Map<String, Value>> {self.db .all(sql, params) .unwrap_or_else(|error| panic!("the read did not run ({error}): {sql}")) .into_iter() .map(|row| { row.columns() .iter() .map(|(name, value)| (name.clone(), sql_to_json(value))) .collect() }) .collect() }/// The first row a query answers, or `None`.pubfn one(&self, sql: &str, params: &[SqlValue]) -> Option<Map<String, Value>> {self.all(sql, params).into_iter().next() }/// `SELECT COUNT(*)`, as a number.pubfn count(&self, sql: &str, params: &[SqlValue]) -> i64 {self.one(sql, params) .and_then(|row| row.values().next().and_then(Value::as_i64)) .unwrap_or(0) }/// Fold ops into the file the way a device's push does.////// The server's suites seeded through `POST /v1/sync/push`; the fold under/// that route is `cotton_store::fold::fold_ops`, and it is what a suite/// about a TOOL actually needed of it. A rejection is a hard failure here/// for the same reason the push assertion was: a seed that half-landed/// makes every assertion after it a lie.////// A PEER'S ops land only once the file knows the peer: a file holding its/// own author's fact (any file that has written once, slice 2c) parks every/// receipt whose author has no `cotton_authors` row as `waiting`. So each/// seeding author this file has no fact for gets one folded at the head of/// the same batch — first stamped at its earliest op's millisecond, counter/// 0 — and a seed op left waiting is a hard failure, never a row that/// silently did not land.pubfn seed(&self, ops: &[Value]) {letmut parsed: Vec<CottonOp> = Vec::new();for (author, first_stamp) inself.unknown_authors(ops) { parsed.push(author_fact(&self.workspace_id, &author, &first_stamp)); }// Each seed DESCRIBES a write — `opId`, `deviceId`, `kind`, `table`,// `rowId`, `patch`, `hlc` — and its receipt is made here the way a// device makes one: an upsert of a row neither the file nor an earlier// seed of the batch holds is a create (`mint::changes_of`).let text = |op: &Value, key: &str| { op[key] .as_str() .unwrap_or_else(|| panic!("the seed op names no {key}: {op}")) .to_string() };let local: Vec<cotton_store::outbox::LocalChange> = ops .iter() .map(|op| cotton_store::outbox::LocalChange { delete: Default::default(), kind: match op["kind"].as_str() {Some("delete") => cotton_store::protocol::types::OpKind::Delete, _ => cotton_store::protocol::types::OpKind::Upsert, }, table: text(op, "table"), row_id: text(op, "rowId"), patch: op["patch"].as_object().cloned(), }) .collect();let changes = cotton_store::mint::changes_of(&self.db, &local);for (op, change) in ops.iter().zip(&changes) {let author = text(op, "deviceId");let actor = cotton_store::actor::Actor::device_job( cotton_store::actor::JobName::named("seed").expect("a job name"), ); parsed.push( cotton_store::wire::op_of_change( &self.db, change, &text(op, "hlc"), &author, &actor, text(op, "opId"), ) .unwrap_or_else(|error| panic!("the seed op has no receipt ({error}): {op}")), ); }let result = fold_ops(&self.db, &parsed).expect("the seed folds"); assert!( result.rejected.is_empty(),"the seed was rejected: {:?}", result.rejected ); assert!( result.waiting.is_empty(),"the seed was parked waiting for an author fact: {:?}", result.waiting ); }/// The FILE's author — `_meta.author_id`, the `device:<ulid>` minted on/// the file's first write. Every op a writer commits is stamped with it/// (slice 2c), never with `server:mcp` or the device a context was/// labelled with. Panics before the first write: there is none yet.pubfn file_author(&self) -> String {let author = cotton_store::mint::file_author(&self.db).expect("the file has an author"); assert!( author.starts_with("device:"),"the file's author is a device: {author}" ); author }/// Each author these ops carry that the file holds no `cotton_authors`/// fact for, in first-seen order, with the stamp its fact is first at:/// the earliest of its ops' milliseconds at counter 0.fn unknown_authors(&self, ops: &[Value]) -> Vec<(String, String)> {letmut earliest: Vec<(String, String)> = Vec::new();for op in ops {let author = op["deviceId"] .as_str() .unwrap_or_else(|| panic!("the seed op names no deviceId: {op}"));let hlc = op["hlc"] .as_str() .unwrap_or_else(|| panic!("the seed op carries no hlc: {op}"));let ms = hlc .get(..13) .filter(|digits| digits.bytes().all(|b| b.is_ascii_digit())) .unwrap_or_else(|| panic!("the seed op's hlc starts with no 13-digit ms: {op}")) .to_string();match earliest.iter_mut().find(|(known, _)| known == author) {Some((_, first)) => {if ms < *first { *first = ms; } }None => earliest.push((author.to_string(), ms)), } } earliest .into_iter() .filter(|(author, _)| {self.count("SELECT COUNT(*) FROM cotton_authors WHERE id = ?", &[SqlValue::Text(author.clone())], ) == 0 }) .map(|(author, ms)| {let stamp = format!("{ms}:0000:{author}"); (author, stamp) }) .collect() }/// What a device syncing from this file would receive, as op rows.////// THERE IS NO LOG. `_ops` stopped being written at version 8: the tables/// answer for an author, so "what this file would hand over" is an exchange/// from the cursor map [`Self::cursors`] took before the call. The rows/// carry the same keys the `_ops` read did — `op_id`, `device_id`, `kind`,/// `tbl`, `row_id`, `patch` (as its JSON text, the way the column held it)/// and `hlc` — minus `seq`, which named a server sequence that no longer/// exists.pubfn ops_since( &self, seen: &std::collections::BTreeMap<String, String>, ) -> Vec<Map<String, Value>> { cotton_store::exchange::answer(&self.db, seen, 5_000) .expect("the file answers a peer") .ops .into_iter() .map(|op| {letmut row = Map::new(); row.insert("op_id".to_string(), Value::String(op.op_id)); row.insert("device_id".to_string(), Value::String(op.device_id)); row.insert("kind".to_string(),Value::String(op.kind.as_str().to_string()), ); row.insert("tbl".to_string(), Value::String(op.table)); row.insert("row_id".to_string(), Value::String(op.row_id)); row.insert("patch".to_string(),match op.patch {Some(patch) => Value::String( serde_json::to_string(&patch).unwrap_or_else(|_| "{}".to_string()), ),None => Value::Null, }, ); row.insert("hlc".to_string(), Value::String(op.hlc)); row }) .collect() }/// Where every author in this file stands right now — the "before" of a/// before-and-after read, and what [`Self::ops_since`] takes.pubfn cursors(&self) -> std::collections::BTreeMap<String, String> { cotton_store::cursors::cursor_ceiling(&self.db).expect("the file answers for its authors") }/// Register a connection and hand back its lookup key.////// A `cotton_mcp_tokens` row goes in beside it. Not because a handler reads/// one — none does — but because the tools that stamp WHICH connection/// wrote a record (`cotton_documents.mcp_token_id` and its kin) key back to/// that table, and a foreign key does not care that this is a test. The/// table is seeded with plain SQL rather than through the writer, so/// nothing about it reaches a device.pubfn connect(&self, scopes: &[&str], name: &str) -> String {let id = synthetic_uuid("token");let secret = format!("ctn_test_{id}"); {use sha2::{Digest, Sha256};letmut hasher = Sha256::new(); hasher.update(secret.as_bytes());let token_hash = hex::encode(hasher.finalize());self.run("INSERT INTO cotton_mcp_tokens (id, owner_user_id, workspace_id, name, \ token_hash, scopes, created_at, _hlc) VALUES (?, ?, ?, ?, ?, ?, ?, '')", &[SqlValue::Text(id.clone()),SqlValue::Text(self.owner_id.clone()),SqlValue::Text(self.workspace_id.clone()),SqlValue::Text(name.to_string()),SqlValue::Text(token_hash),// JSON, because the COLUMN is (`table_specs`: `scopes` is// `Codec::Json`) — a comma-joined string here was a fixture// no peer could ever read, and the reconstruction that// answers a sync says so out loud.SqlValue::Text( serde_json::to_string(scopes).unwrap_or_else(|_| "[]".to_string()), ),SqlValue::Text(HARNESS_NOW.to_string()), ], ); }self.connections.borrow_mut().insert( secret.clone(),Connection { id, name: name.to_string(), scopes: scopes.iter().map(|scope| (*scope).to_string()).collect(), }, ); secret }/// The connection behind a key, or a panic naming the key — a suite calling/// with a string it never minted is a typo, not a refusal to assert on.pubfn connection(&self, secret: &str) -> Connection {self.connections .borrow() .get(secret) .cloned() .unwrap_or_else(|| panic!("no connection was minted for {secret}")) }/// Every extra audit line the tools asked for, in order.pubfn audit_lines(&self) -> Vec<AuditLine> {self.audit.borrow().clone() }pub(crate) fn record_audit(&self, tool: &str, summary: &str) {self.audit.borrow_mut().push(AuditLine { tool: tool.to_string(), summary: summary.to_string(), }); }}implDefaultforHarness {fn default() -> Harness {Harness::new() }}fn sql_to_json(value: &SqlValue) -> Value {match value {SqlValue::Null => Value::Null,SqlValue::Integer(int) => Value::from(*int),SqlValue::Real(real) => Value::from(*real),SqlValue::Text(text) => Value::from(text.clone()),SqlValue::Blob(_) => Value::from("<blob>"), }}/// Whose cached kitted file it is: the ids its rows carry. Those are/// [`synthetic_uuid`]'s, counted per process, so a test process's first/// harness always asks for the same file and a later one (or a thread's,/// under `cargo test`) for its own.////// NOT the test binary's: every one of this crate's 130 test binaries builds/// the same file, and nextest's hash partitions give each part one or two/// tests of each binary, so a file per binary was a kit import for nearly/// every test (126 binaries for 162 tests in part 1 of rust-main 7647, each/// test a minute on the loaded Linux box, 6 Nov 2026).fn fixture_family(workspace_id: &str, owner_id: &str) -> String { hashed(&(workspace_id, owner_id))}/// Which build of it — everything that shapes the file: the schema (the/// ladder's fingerprint, in the name `cotton_store::test_template` gives it),/// the kit's packages and shell by their bytes (`cotton_core::kit::fingerprint`),/// and the code that writes them ([`fixture_code`]). A change to any names a/// new file (coordinator, 24 Oct 2026: a changed kit must never reuse a stale/// fixture).fn fixture_version() -> String { hashed(&(cotton_core::kit::fingerprint(), fixture_code(), include_str!("harness.rs")))}/// The build of the code that writes the kitted file, the same for every test/// binary of one build: the `cotton-tools`, `cotton-store` and `cotton-core`/// libraries every one of them links, by the size and modification time of/// their rlibs beside this binary (cargo writes each again whenever it builds/// it, so any change to them or to what they depend on is a new time), and/// this harness's own source (the workspace row it founds), in the version/// above. A layout without those rlibs keys on this binary's own build, as/// the file did before it was shared.fn fixture_code() -> Vec<(String, u64, Option<u128>)> {let exe = std::env::current_exe().expect("the test binary");let stamp = |path: &std::path::Path| {let stat = std::fs::metadata(path).expect("a built file's metadata");let built = stat.modified().ok().and_then(|at| at.duration_since(std::time::UNIX_EPOCH).ok()).map(|at| at.as_nanos()); (stat.len(), built) };letmut libraries: Vec<(String, u64, Option<u128>)> = exe .parent() .and_then(|deps| std::fs::read_dir(deps).ok()) .into_iter() .flatten() .flatten() .filter_map(|entry| {let name = entry.file_name().to_string_lossy().into_owned();let ours = ["libcotton_tools-", "libcotton_store-", "libcotton_core-"].iter().any(|lib| name.starts_with(lib)); (ours && name.ends_with(".rlib")).then(|| {let (len, built) = stamp(&entry.path()); (name, len, built) }) }) .collect();if libraries.len() < 3 {let (len, built) = stamp(&exe);return vec![(exe.display().to_string(), len, built)]; } libraries.sort(); libraries}fn hashed(value: &impl std::hash::Hash) -> String {use std::hash::Hasher;letmut hasher = std::collections::hash_map::DefaultHasher::new(); value.hash(&mut hasher); format!("{:016x}", hasher.finish())}/// A uuid a suite can name — derived from a label and a per-process counter, so/// a failure is reproducible and two calls never collide.pubfn synthetic_uuid(label: &str) -> String {static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); synthetic_uuid_at(label, NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))}/// The `n`th [`synthetic_uuid`] a process hands out, whatever its label.pubfn synthetic_uuid_at(label: &str, n: u64) -> String {use sha2::{Digest, Sha256};letmut hasher = Sha256::new(); hasher.update(format!("cotton-tools-harness/{label}/{n}").as_bytes());let hex = hex::encode(hasher.finalize()); format!("{}-{}-4{}-8{}-{}", &hex[0..8], &hex[8..12], &hex[13..16], &hex[17..20], &hex[20..32] )}