//! `tools.export`, `tools.import`, `tools.list` and `tools.remove` through the//! C entry point the app calls, over a phone that has joined a synthetic file//! ([nothing-real-ever-goes-in-cotton-s-public-tree]). JSON in, one envelope//! out, on whichever build runs these: the host build (default features) and//! the phone's (`--no-default-features`) answer all four the same way.//!//! The package is invented here — one tool, `practice_log`, over one table,//! `rehearsal` — and encoded with the shipped codec, so these tests hold the//! METHODS, not the codec (that is `cotton-core`'s `package_tests.rs`) nor the//! handlers' every refusal (that is `cotton-tools/tests/mcp_tool_packages.rs`).use std::ffi::{CStr, CString};use std::io::{Cursor, Read, Write};use std::path::Path;use std::sync::Arc;use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};use base64::Engine;use cotton_core::definitions::package::{decode_package, encode_unsigned_package, ToolPackage};use cotton_core::definitions::{TableDefinition, ToolAuthor, ToolDefinition};use serde_json::{json, Value};usecrate::ffi::open_quietly;usecrate::{cotton_call, cotton_close, cotton_string_free};const TOOL_ID: &str = "practice_log";const TABLE_ID: &str = "rehearsal";/// The tool's instructions: `manifest.json`'s `instructions` and the package's/// `instructions.md`, which the codec holds equal.const INSTRUCTIONS: &str ="Log each rehearsal on the day it happened, with the piece and how long it ran.";/// The synthetic device seed the signing builds open with.const SEED: [u8; 32] = [42; 32];/// A phone container already holding the connection record and the seeded/// replica — what a launch after a join finds (`phrase_tests.rs`' twin).fn joined_container() -> tempfile::TempDir {let dir = tempfile::tempdir().expect("a temp container");let layout = cotton_client::layout::Layout::new(dir.path()); std::fs::create_dir_all(layout.client_dir()).expect("the client folder"); std::fs::write( layout.connection_json(), serde_json::to_vec_pretty(&json!({"mode": "remote","baseUrl": "https://server.invalid","workspaceId": crate::fixture::WORKSPACE,"ownerId": crate::fixture::OWNER,"connectedAt": "2026-10-01T10:00:00.000Z", })) .expect("json"), ) .expect("the connection record");let replica = layout.replica(crate::fixture::WORKSPACE); std::fs::create_dir_all(replica.parent().expect("a parent")).expect("the replica folder");// The pull after a join brings this device's own row: a write is asked by// the owner at the row its key holds.// These cases import and remove their own tools: a database nobody filled.let seeded = {let _bare = crate::fixture::bare();crate::fixture::seeded(&replica) };crate::fixture::device_row(&seeded, &signer_key()); drop(seeded); dir}/// `cotton_call`s, exactly as the app makes them, against ONE opened core: C/// strings in, an owned C string out, freed by the caller. `signing` opens the/// core with this device's Keychain seed (what gives it a signer, and the key/// its row in the file is held under); without it the core has no device key/// at all — it still READS, and every write it asks is refused.fn calls(container: &Path, signing: bool, calls: &[(&str, Value)]) -> Vec<Value> {letmut config = json!({ "containerPath": container.to_string_lossy(), "appVersion": "0.1.0" });if signing { config["deviceSecret"] = json!(URL_SAFE_NO_PAD.encode(SEED)); }let config = CString::new(config.to_string()).expect("no NUL");letmut error: *mut std::ffi::c_char = std::ptr::null_mut();let handle = unsafe { open_quietly(config.as_ptr(), &mut error) }; assert!(error.is_null() && !handle.is_null(), "the phone core opens");let answers = calls .iter() .map(|(method, request)| {let method = CString::new(*method).expect("no NUL");let request = CString::new(request.to_string()).expect("no NUL");let answer = unsafe { cotton_call(handle, method.as_ptr(), request.as_ptr()) }; assert!(!answer.is_null(), "this ABI never answers a null string");let text = unsafe { CStr::from_ptr(answer) }.to_string_lossy().to_string();unsafe { cotton_string_free(answer) }; serde_json::from_str(&text).expect("one JSON object") }) .collect();unsafe { cotton_close(handle) }; answers}/// The `data` of an `ok` envelope.fn data(envelope: &Value) -> &Value { assert_eq!(envelope["ok"], json!(true), "{envelope}"); &envelope["data"]}/// The refusal of a failed envelope: its code and its sentence.fn refusal(envelope: &Value) -> (&str, &str) { assert_eq!(envelope["ok"], json!(false), "{envelope}"); ( envelope["error"]["code"].as_str().expect("a code"), envelope["error"]["message"].as_str().expect("a message"), )}fn table() -> TableDefinition { serde_json::from_value(json!({"id": TABLE_ID, "name": "Rehearsal", "plural": "Rehearsals", "picture": null,"builtin": false, "engine": null,"columns": [ { "key": "piece", "type": "text", "required": true }, { "key": "day", "type": "date" }, { "key": "minutes", "type": "number" } ],"title": "piece", "date": "day", "project": null, "order": null,"slip": { "title": "piece", "subtitle": null, "trailing": "day", "photo": null, "toggle": null },"tile": { "face": "slip-list" },"page": [ { "heading": null, "columns": ["piece", "day", "minutes"] } ],"instructions": "One rehearsal: the piece, the day and the minutes." })) .expect("a table definition")}fn package() -> ToolPackage {ToolPackage { board: None, tool: ToolDefinition { views: Vec::new(), id: TOOL_ID.into(), name: "Practice log".into(), purpose: None, picture: None, card_stock: None, fan_tile: None, tables: vec![TABLE_ID.into()], search: Vec::new(), contributes: Vec::new(), instructions: INSTRUCTIONS.into(), automations: vec![], engines: Vec::new(), reserve: None, acts: vec![], server: None, lists: None, author: ToolAuthor { device: "unknown".into(), name: "Invented author".into(), }, signature: None, unknown: Default::default(), fallbacks: Vec::new(), unavailable: Vec::new(), }, tables: vec![table()], pictures: Default::default(), samples: Default::default(), }}/// The unsigned package's bytes, as `tools.import`'s request carries them.fn import_request() -> Value { json!({ "bytes": STANDARD.encode(encode_unsigned_package(&package()).expect("encodes")) })}fn signer_key() -> String { cotton_client::DeviceIdentity::from_secret(&SEED) .expect("a synthetic identity") .device_id()}/// Two invented packages: rehearsal rows link to a summary owned by a/// different tool. The summary package never carries the rehearsal table.fn rollup_packages() -> (Value, Value) {letmut source = package();letmut source_table = serde_json::to_value(&source.tables[0]).unwrap(); source_table["columns"].as_array_mut().unwrap().push(json!({"key": "summary", "name": "Summary", "type": "link", "link_to": "practice_summary" })); source.tables[0] = serde_json::from_value(source_table).unwrap();letmut summary = package(); summary.tool.id = "practice_summaries".into(); summary.tool.tables = vec!["practice_summary".into()];letmut summary_table = serde_json::to_value(&summary.tables[0]).unwrap(); summary_table["id"] = json!("practice_summary"); summary_table["columns"].as_array_mut().unwrap().extend([ json!({ "key": "sessions", "name": "Sessions", "type": "number","computed": { "rollup": { "table": TABLE_ID, "link": "summary", "op": "count" } } }), json!({ "key": "shortest", "name": "Shortest", "type": "number","computed": { "rollup": { "table": TABLE_ID, "link": "summary", "op": "min", "column": "minutes" } } }), ]); summary.tables[0] = serde_json::from_value(summary_table).unwrap();let request = |package: &ToolPackage| json!({ "bytes": STANDARD.encode(encode_unsigned_package(package).unwrap()) }); (request(&source), request(&summary))}/// RULE: Phone import validates cross-tool rollups against its own database, refuses an absent source by name, and allows removing an empty source while count stays zero and min stays empty with each absent column carrying its source table and the core's words.#[test]fn phone_cross_tool_rollups_validate_and_survive_source_removal() {let container = joined_container();let (source, summary) = rollup_packages();let answers = calls(container.path(), true, &[ ("tools.import", summary.clone()), ("tools.list", json!({})), ("tools.import", source.clone()), ("tools.import", summary), ("records.create", json!({ "table": "practice_summary", "data": { "piece": "Invented practice" } })), ]);let name = cotton_core::definitions::key_as_words(TABLE_ID); assert!(refusal(&answers[0]).1.contains(&name), "{}", answers[0]); assert_eq!(data(&answers[1])["tools"], json!([])); data(&answers[2]); data(&answers[3]);let id = data(&answers[4])["record"]["id"].as_str().expect("created summary id");let answers = calls(container.path(), true, &[ ("records.get", json!({ "table": "practice_summary", "id": id })), ("tools.remove", json!({ "tool_id": TOOL_ID })), ("records.get", json!({ "table": "practice_summary", "id": id })), ("tools.import", source), ("records.get", json!({ "table": "practice_summary", "id": id })), ]); assert!(data(&answers[0]).get("computed_unavailable").is_none()); data(&answers[1]);let removed = data(&answers[2]); assert_eq!(removed["data"]["sessions"], json!(0), "{removed}"); assert_eq!(removed["data"]["shortest"], Value::Null, "{removed}");let unavailable = &removed["computed_unavailable"];for column in ["sessions", "shortest"] {// The source is named; its words came from the `everything` definition, which no kit carries. assert_eq!(unavailable[column]["table"], json!(TABLE_ID), "{removed}"); } assert_eq!(unavailable.as_object().map(|columns| columns.len()), Some(2), "{removed}"); data(&answers[3]); assert!(data(&answers[4]).get("computed_unavailable").is_none());}/// RULE: tools.import takes a standard-base64 package and answers {tool_id, signature, sample_records}; bytes that are not base64 and a package carrying an engine are refused by name and write nothing.#[test]fn tools_import_answers_the_tool_and_its_label_and_refuses_unsafe_bytes() {let container = joined_container();// Build a valid ZIP carrying unsafe JSON. Export deliberately omits an// absent engine, so neither its spelling nor ZIP byte offsets are a rule.let bytes = encode_unsigned_package(&package()).expect("encodes");letmut archive = zip::ZipArchive::new(Cursor::new(bytes)).expect("an archive");letmut unsafe_archive = zip::ZipWriter::new(Cursor::new(Vec::new()));for index in0..archive.len() {letmut entry = archive.by_index(index).expect("an entry");letmut content = Vec::new(); entry.read_to_end(&mut content).expect("entry bytes");let name = entry.name().expect("an entry name").into_owned();if name == format!("tables/{TABLE_ID}.json") {letmut definition: Value = serde_json::from_slice(&content).expect("a definition"); definition["engine"] = json!(true); content = serde_json::to_vec(&definition).expect("unsafe definition JSON"); }let options = zip::write::SimpleFileOptions::default(); unsafe_archive.start_file(name, options).expect("an entry"); unsafe_archive.write_all(&content).expect("entry bytes"); }let engine_bytes = unsafe_archive.finish().expect("a valid ZIP").into_inner();let answers = calls( container.path(),true, &[ ("tools.import", json!({ "bytes": "not base64 !!" })), ("tools.import", json!({ "bytes": STANDARD.encode(engine_bytes) })), ("tools.list", json!({})), ("tools.import", import_request()), ], );let (code, message) = refusal(&answers[0]); assert_eq!(code, "tool_package_refused"); assert!(!message.is_empty());let (code, message) = refusal(&answers[1]); assert_eq!(code, "tool_package_refused"); assert!(message.contains("engine"), "{message}");// Nothing was written by either refusal. assert_eq!( *data(&answers[2]), json!({ "tools": [], "table_definitions": [] }) ); assert_eq!( *data(&answers[3]), json!({ "tool_id": TOOL_ID, "signature": "unsigned", "sample_records": 0 }) );}/// RULE: tools.list answers {tools, table_definitions} — each tool's definition with its signature, each user table with its orphaned mark — and refuses a request that is not an object.#[test]fn tools_list_answers_the_imported_tool_and_its_tables() {let container = joined_container();let answers = calls( container.path(),true, &[ ("tools.import", import_request()), ("tools.list", json!({})), ("tools.list", json!(["not", "an", "object"])), ], ); data(&answers[0]);let listed = data(&answers[1]);let tools = listed["tools"].as_array().expect("tools"); assert_eq!(tools.len(), 1, "{listed}"); assert_eq!(tools[0]["signature"], json!("unsigned")); assert_eq!( tools[0]["definition"], serde_json::to_value(&package().tool).expect("json"),"the stored manifest is the package's, whole" );let tables = listed["table_definitions"].as_array().expect("tables"); assert_eq!(tables.len(), 1, "{listed}"); assert_eq!(tables[0]["definition"]["id"], json!(TABLE_ID)); assert_eq!(tables[0]["orphaned"], json!(false));let (code, _) = refusal(&answers[2]); assert_eq!(code, "bad_request");}/// RULE: tools.export answers {tool_id, bytes} signed by this device's own key; an unknown tool id is refused, and a core opened with no device key refuses with the named no-signing-key sentence.#[test]fn tools_export_signs_with_this_device_and_refuses_without_a_key() {let signing = joined_container();let answers = calls( signing.path(),true, &[ ("tools.import", import_request()), ("tools.export", json!({ "tool_id": TOOL_ID })), ("tools.export", json!({ "tool_id": "no_such_tool" })), ], ); data(&answers[0]);let exported = data(&answers[1]); assert_eq!(exported["tool_id"], json!(TOOL_ID));let bytes = STANDARD .decode(exported["bytes"].as_str().expect("bytes")) .expect("standard base64");let decoded = decode_package(&bytes).expect("a valid signed package");let key = signer_key(); assert_eq!(decoded.signature, cotton_core::definitions::package::Signature::SignedBy { key: key.clone() }); assert_eq!(decoded.package.tool.author.device, key); assert_eq!(decoded.package.tool.instructions, INSTRUCTIONS); assert_eq!(decoded.package.tables, vec![table()]);let (code, message) = refusal(&answers[2]); assert_eq!(code, "tool_package_refused");// The engine names the tool by id; the person reads plain words (R6). assert_eq!(message, cotton_core::failure::NOT_DONE, "{message}");// The exported bytes import on a second device as signed by the first.let other = joined_container();// A core with a key imports — a write is asked by the owner at its row.let answers = calls( other.path(),true, &[("tools.import", json!({ "bytes": exported["bytes"] }))], ); assert_eq!( *data(&answers[0]), json!({ "tool_id": TOOL_ID, "signature": "signed", "by": key, "sample_records": 0 }) );// And a core opened with NO device key over the same file: export is a// read, so it runs, and is refused BY NAME.let answers = calls( other.path(),false, &[("tools.export", json!({ "tool_id": TOOL_ID }))], );let (code, message) = refusal(&answers[0]); assert_eq!(code, "tool_package_refused"); assert!(message.contains("no signing key"), "{message}");}/// RULE: tools.remove answers {tool_id, orphaned_tables}, keeps the table definitions as orphaned shapes, and refuses a tool that is not installed.#[test]fn tools_remove_orphans_the_tables_and_refuses_a_missing_tool() {let container = joined_container();let answers = calls( container.path(),true, &[ ("tools.remove", json!({ "tool_id": TOOL_ID })), ("tools.import", import_request()), ("tools.remove", json!({ "tool_id": TOOL_ID })), ("tools.list", json!({})), ], );let (code, message) = refusal(&answers[0]); assert_eq!(code, "tool_package_refused");// The engine names the tool by id; the person reads plain words (R6). assert_eq!(message, cotton_core::failure::NOT_DONE, "{message}"); data(&answers[1]); assert_eq!( *data(&answers[2]), json!({ "tool_id": TOOL_ID, "orphaned_tables": [TABLE_ID] }) );let listed = data(&answers[3]); assert_eq!(listed["tools"], json!([])); assert_eq!(listed["table_definitions"][0]["definition"]["id"], json!(TABLE_ID)); assert_eq!(listed["table_definitions"][0]["orphaned"], json!(true));}/// What an assistant's `list_tools` answers over `replica`: the MCP door/// (`dispatch::call_tool` over `Ctx::new` with a token's read scope), its/// answer serialised to the text a `tools/call` carries and read back.fn list_tools_through_mcp(replica: &Path) -> Value {let db = cotton_store::driver::Driver::open(replica).expect("the replica opens");let scopes = vec!["read".to_string()];let services = cotton_tools::mcp::dispatch::ToolServices::none();let audit = |_: &str, _: &str| {};letmut ctx = cotton_tools::mcp::dispatch::Ctx::new( &db,crate::fixture::identity(),crate::fixture::OWNER,"Claude","token-1", &scopes,// A fixed instant, never the wall clock: `list_tools` reads no time,// and a test that did would not drift with the day it runs. chrono::TimeZone::with_ymd_and_hms(&chrono::Utc, 2026, 10, 1, 12, 0, 0) .single() .expect("a valid instant"),Arc::new(cotton_tools::random::SystemRandom),None, &services, &audit, );let answer = cotton_tools::mcp::dispatch::call_tool(&mut ctx, "list_tools", &serde_json::Map::new()) .unwrap_or_else(|failure| panic!("list_tools refused: {}", failure.message())); serde_json::from_str(&answer.to_string()).expect("tools/call text")}/// RULE: An imported tool's instructions are what tools.list and definitions.tools answer, and what an assistant's list_tools reads over the same file.////// The assistant-facing readers of a tool's instructions today are `list_tools`/// (MCP) and the app's `tools.list` / `definitions.tools`. No MCP prompt, no/// server `instructions` and no `get_project` section reads a tool definition/// yet; when one does, it belongs in this test.#[test]fn imported_instructions_reach_the_app_and_the_assistants_door() {let container = joined_container();let answers = calls( container.path(),true, &[ ("tools.import", import_request()), ("tools.list", json!({})), ("definitions.tools", json!({})), ], ); data(&answers[0]);let listed = data(&answers[1]); assert_eq!(listed["tools"][0]["definition"]["instructions"], json!(INSTRUCTIONS));let definitions = data(&answers[2]); assert_eq!(definitions["refused"], json!([]), "{definitions}"); assert_eq!(definitions["definitions"][0]["id"], json!(TOOL_ID)); assert_eq!(definitions["definitions"][0]["instructions"], json!(INSTRUCTIONS));// ONE implementation: the app's answer is the assistant's tool's, whole.let replica = cotton_client::layout::Layout::new(container.path()) .replica(crate::fixture::WORKSPACE); assert_eq!(list_tools_through_mcp(&replica), *listed);}/// RULE: With no installed package, tools.list answers exactly the current empty tool and table collections, with no retired compatibility fields.#[test]fn tools_list_answers_the_current_empty_collections() {let container = joined_container();let answers = calls(container.path(), false, &[("tools.list", json!({}))]); assert_eq!(*data(&answers[0]), json!({ "tools": [], "table_definitions": [] }));}extern"C"fn collect_moves(ctx: *mut std::ffi::c_void, line: *const std::ffi::c_char) {let seen = unsafe { &*(ctx as *const std::sync::Mutex<Vec<String>>) };let text = unsafe { CStr::from_ptr(line) }.to_string_lossy().to_string(); seen.lock().expect("the record").push(text);}/// What the bus said since it was last read: subscribing replays its buffer.fn said(handle: &crate::handle::CottonHandle) -> Vec<Value> {let seen = Box::new(std::sync::Mutex::new(Vec::<String>::new()));let client = handle.client();let bus = client.events_for_tests(); bus.subscribe(&*seen as *const _ as *mut std::ffi::c_void, Some(collect_moves)); bus.subscribe(std::ptr::null_mut(), None);let lines = seen.lock().expect("the record").clone(); lines.iter().map(|line| serde_json::from_str(line).expect("json")).collect()}/// RULE: A read over a table whose background move is not done — the computed index the open left stale, rebuilt after it on `cotton-index` — answers typed `could_not_read` with `why: moving`, the table it asked and the database it read (no sentence of its own, no schema number, never `unreadable`, which offers Try again); the move says it is done in a `data` event (origin `moved`) naming the table, and the same read then answers its rows — so a tile or list stalled on it draws itself on that signal, with no reload, no pull and no timer (passivemove rule 3).#[test]fn a_read_over_a_table_mid_move_says_moving_and_answers_rows_once_the_move_is_done() {let container = joined_container();let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: container.path().to_string_lossy().to_string(), previous_container_path: None, }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(URL_SAFE_NO_PAD.encode(SEED)), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: None, }) .expect("an open core");let dispatch = |method: &str, request: Value| crate::methods::dispatch(&handle, method, &request);// The summary lists in its computed column's order, so its list reads the// computed index before its page is cut.let (source, _) = rollup_packages();letmut summary = package(); summary.tool.id = "practice_summaries".into(); summary.tool.tables = vec!["practice_summary".into()];letmut summary_table = serde_json::to_value(&summary.tables[0]).unwrap(); summary_table["id"] = json!("practice_summary"); summary_table["sort"] = json!({ "column": "sessions" }); summary_table["columns"].as_array_mut().unwrap().push(json!({ "key": "sessions", "name": "Sessions", "type": "number","computed": { "rollup": { "table": TABLE_ID, "link": "summary", "op": "count" } } })); summary.tables[0] = serde_json::from_value(summary_table).unwrap(); dispatch("tools.import", source).expect("the source tool"); dispatch("tools.import", json!({ "bytes": STANDARD.encode(encode_unsigned_package(&summary).unwrap()) })).expect("the summary tool");let id = dispatch("records.create", json!({ "table": "practice_summary", "data": { "piece": "Invented practice" } })) .expect("a summary")["record"]["id"].as_str().expect("its id").to_string();let listed = |answer: &Value| answer["records"].as_array().map(|rows| rows.iter().any(|row| row["id"] == id.as_str()));// Another build's stamp: the index is mid-move until the background pass.let client = handle.client(); client.settle_moves_for_tests(); client.with_writer(|file| cotton_store::derived::mark_rebuilt(file.driver, "0:sha256:another-build").map_err(|error| error.to_string())) .expect("stamped");let _ = said(&handle);let moving = dispatch("records.list", json!({ "table": "practice_summary" })).expect_err("mid-move"); assert_eq!(moving.code, crate::methods::COULD_NOT_READ, "{moving:?}"); assert_eq!(moving.details["why"], crate::methods::MOVING, "{moving:?}"); assert_eq!(moving.details["table"], "practice_summary", "{moving:?}"); assert_eq!(moving.details["database"], crate::fixture::WORKSPACE, "{moving:?}"); assert!(said(&handle).iter().all(|event| event["payload"]["origin"] != crate::shell::client::MOVES_DONE_ORIGIN), "nothing said done yet"); assert!(client.bring_moves_done_for_tests().expect("the move"), "the background move rebuilds the index");let done = said(&handle); assert!( done.iter().any(|event| event["kind"] == "data" && event["payload"]["origin"] == crate::shell::client::MOVES_DONE_ORIGIN && event["payload"]["workspaceId"] == crate::fixture::WORKSPACE && event["payload"]["tables"].as_array().is_some_and(|tables| tables.contains(&json!("cotton_practice_summary")))),"the move says it is done, naming the table: {done:?}" );let rows = dispatch("records.list", json!({ "table": "practice_summary" })).expect("rows once the move is done"); assert_eq!(listed(&rows), Some(true), "{rows}");}/// RULE: A 345 local-founded copy that backed up is Remote on its next launch./// 346/347 must read its catalogue without kit-keep, preserving every todo cell./// The simulator's tools.list failed after dropping Bin's old Restore command:/// its parts.acts.more still named restore_database, refusing every tool.#[test]fn signed_in_345_copy_keeps_its_catalogue_and_rows_on_upgrade() {use cotton_store::driver::Driver;use rusqlite::types::ValueasSqlValue;let container = joined_container();let added = calls(container.path(), true, &[("tools.add", json!({"tool_id":"todos"}))]); data(&added[0]);let layout = cotton_client::layout::Layout::new(container.path());let replica = layout.replica(crate::fixture::WORKSPACE);let db = Driver::open(&replica).unwrap(); db.run("INSERT INTO cotton_todos (id,workspace_id,title,due_at,created_at,updated_at) VALUES ('retained',?,'Synthetic 345 retained todo','2026-11-02','2026-11-02','2026-11-02')", &[SqlValue::Text(crate::fixture::WORKSPACE.into())]).unwrap();let bin = include_str!("fixtures/345-bin.json");let copy = include_str!("fixtures/345-copy.json");for (id, definition) in [("bin", bin), ("copy", copy)] { db.run("INSERT OR REPLACE INTO cotton_table_definitions (id,workspace_id,definition,builtin,builtin_hash,builtin_stamp,created_at,updated_at) VALUES (?,?,?,1,'sha256:076577209388e25fa6250e251560db7b5861599776fcc5c314c1ae1c9a44f49b',1793544198,'2026-11-02','2026-11-02')", &[SqlValue::Text(id.into()),SqlValue::Text(crate::fixture::WORKSPACE.into()),SqlValue::Text(definition.into())]).unwrap(); }let before = db.all("SELECT * FROM cotton_todos ORDER BY id", &[]).unwrap(); drop(db);// Reopen twice with no served-definition replacement, as on a 304.// Stored definitions remain authoritative and no local keep is run.for _ in0..2 {let answers = calls(container.path(), false, &[("tools.list",json!({})), ("definitions.catalogue",json!({}))]); assert!(data(&answers[0])["tools"].as_array().unwrap().iter().any(|tool| tool["definition"]["id"] == "todos")); data(&answers[1]);let db = Driver::open(&replica).unwrap(); assert_eq!(db.all("SELECT * FROM cotton_todos ORDER BY id", &[]).unwrap(), before);for (id, definition) in [("bin", bin), ("copy", copy)] { assert_eq!(db.get("SELECT definition FROM cotton_table_definitions WHERE id=?", &[SqlValue::Text(id.into())]).unwrap().unwrap().text("definition"),Some(definition),"reading never rewrites the object's definitions"); } assert!(db.get("SELECT name FROM sqlite_master WHERE name='_kit_keep'", &[]).unwrap().is_none(),"a served copy does not run local kit-keep"); }}