//! Invented records only. Every case uses the real dispatcher and receipt fold. mod support; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use support::harness::{synthetic_uuid, Harness}; use support::mcp::call_tool_as_owner; fn owner(h: &Harness, tool: &str, mut args: Value) -> Value { if matches!(tool, "create_record" | "get_record_by_table" | "list_records" | "delete_record" | "update_record") { args["today"] = json!("2026-09-08"); } let out = call_tool_as_owner(h, "device:binverbs", tool, args.clone()); assert!(!out.is_error, "{tool} {args}: {}", out.text); out.json() } fn snapshot(h: &Harness, table: &str, id: &str) -> Value { let mut row = h.one(&format!("SELECT * FROM {table} WHERE id = ?"), &[SqlValue::Text(id.to_owned())]).unwrap(); // The row's receipt stamp changes when its bin marker changes; its // contents (including created/edited time and all engine fields) do not. row.remove("_hlc"); Value::Object(row) } fn make_fixture(h: &Harness, table: &str, storage: &str, mut data: Value) -> String { if matches!(table, "person_handle" | "person_language") { let parent = owner(h, "create_record", json!({"table":"person", "data":{"full_name":"Invented kite maker"}})); data["person_id"] = parent["record"]["id"].clone(); } if table == "project" { owner(h, "create_project", data.clone()); return h.one("SELECT id FROM cotton_memory_projects WHERE workspace_id=? AND slug=?", &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(data["slug"].as_str().unwrap().to_owned())]).unwrap()["id"].as_str().unwrap().to_owned(); } if table == "comment" { let parent = owner(h, "create_record", json!({"table":"note", "data":{"title":"Invented kite measurements"}})); data["record_id"] = parent["record"]["id"].clone(); } if matches!(table, "thought" | "comment" | "album" | "money_account" | "todo_recurrence" | "toolkit" | "session" | "transaction" | "document" | "meeting" | "photo" | "video" | "secret") { // These engines capture a record outside create_record. Seed the // same real row; the first dispatcher read reconciles it into signed // receipts before any Bin write is made. let id = if table == "toolkit" { "invented-kite-tools".to_owned() } else if matches!(table, "photo" | "video") { format!("{table}:{}", "a".repeat(64)) } else { synthetic_uuid(&format!("binverbs:{table}")) }; if matches!(table, "photo" | "video") { data["key"] = json!(format!("{}/media/invented-kite-{table}", h.workspace_id)); } if table == "document" { data["storage_path"] = json!(format!("{}/{id}/original.pdf", h.workspace_id)); } let data = data.as_object_mut().unwrap(); data.insert("id".into(), json!(id)); data.insert("workspace_id".into(), json!(h.workspace_id)); data.insert("created_at".into(), json!("2026-09-01T10:00:00.000Z")); data.insert("updated_at".into(), json!("2026-09-02T10:00:00.000Z")); let columns: Vec<_> = data.keys().map(|key| format!("\"{key}\"")).collect(); let parameters: Vec = data.values().map(|value| match value { Value::String(word) => SqlValue::Text(word.clone()), Value::Bool(yes) => SqlValue::Integer(i64::from(*yes)), Value::Number(number) => number.as_i64().map_or_else(|| SqlValue::Real(number.as_f64().unwrap()), SqlValue::Integer), Value::Null => SqlValue::Null, other => SqlValue::Text(other.to_string()), }).collect(); h.run(&format!("INSERT INTO {storage} ({}) VALUES ({})", columns.join(","), vec!["?"; columns.len()].join(",")), ¶meters); owner(h, "get_record_by_table", json!({"table":table,"id":id})); return id; } owner(h, "create_record", json!({"table":table,"data":data}))["record"]["id"].as_str().unwrap().to_owned() } /// RULE: Putting a record in the Bin changes only its marker and receipt stamp; Restore must preserve every stored field and original receipt, including its edit time, so going away cannot rewrite its contents or reorder live work. #[test] fn putting_away_a_record_does_not_edit_its_contents() { let cases = [ ("photo", "cotton_photos", json!({"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","key":"media/invented-kite-photo","content_type":"image/jpeg","size_bytes":1,"taken_at":"2026-09-01T10:00:00.000Z","favourite":false,"subtypes":[],"labels":[],"caption":"Invented kite frame"})), ("video", "cotton_videos", json!({"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","key":"media/invented-kite-video","content_type":"video/mp4","size_bytes":1,"taken_at":"2026-09-01T10:00:00.000Z","favourite":false,"subtypes":[],"labels":[],"caption":"Invented kite flight","duration_ms":1000})), ("secret", "cotton_secrets", json!({"kind":"login","name":"Invented kite account","vmk_version":0,"value_enc":"synthetic-sealed-fixture","service":"example.invalid","hint":"kite"})), ("note", "cotton_notes", json!({"title":"Invented kite notes","body":"Keep the long string"})), ]; for (table, storage, data) in cases { let definitions = cotton_core::definitions::builtin_table_definitions(); let definition = definitions.iter().find(|definition| definition.id == table).unwrap(); let delete = definition.command("delete").unwrap_or_else(|| panic!("{table}: no Delete act")); assert!(delete.is_generic_delete(table) && delete.asks_first(), "{table}: Delete must be the held generic verb"); assert_eq!(delete.does, Some(cotton_core::definitions::CommandDoes::Destroys), "{table}: Delete must wear rose"); if let Some(parts) = &definition.parts { assert_eq!(parts.acts.away.as_deref(), Some("delete"), "{table}: Delete must be held as the away act"); } for tool in ["list_bin", "restore_from_bin", "empty_bin"] { let schema: Value = serde_json::from_str(cotton_tools::mcp::protocol::tool_by_name(tool).unwrap().input_schema).unwrap(); assert!(schema["properties"]["kind"]["enum"].as_array().unwrap().contains(&json!(table)), "{table}: {tool} does not admit this Bin kind"); } let h = Harness::new(); let id = make_fixture(&h, table, storage, data); let id = id.as_str(); let before = snapshot(&h, storage, id); let receipts = h.all("SELECT op_id, bytes FROM _writes WHERE tbl = ? AND row_id = ? ORDER BY op_id", &[SqlValue::Text(storage.to_owned()), SqlValue::Text(id.to_owned())]); assert!(!receipts.is_empty(), "{table}: fixture has no receipt history to preserve"); let premature = call_tool_as_owner(&h, "device:binverbs", "delete_record", json!({"table":"bin", "id":id})); assert!(premature.is_error, "{table}: a live row was erased through the Bin"); h.clock.advance(chrono::Duration::hours(1)); owner(&h, "delete_record", json!({"table":table, "id":id})); let bin = owner(&h, "list_records", json!({"table":"bin"})); assert!(bin["records"].as_array().unwrap().iter().any(|row| row["id"] == id && row["data"]["table"] == table), "{table}: missing from Bin: {bin}"); let list = owner(&h, "list_records", json!({"table":table})); assert!(!list["records"].as_array().unwrap().iter().any(|row| row["id"] == id), "{table}: still listed live"); assert!(owner(&h, "get_record_by_table", json!({"table":table, "id":id}))["deleted_at"].is_string(), "{table}: its Bin page does not answer its contents"); h.clock.advance(chrono::Duration::hours(1)); owner(&h, "update_record", json!({"table":"bin", "id":id, "patch":{"state":"restored"}})); assert_eq!(snapshot(&h, storage, id), before, "{table}: Restore changed a stored column"); for receipt in receipts { assert_eq!(h.one("SELECT op_id, bytes FROM _writes WHERE op_id = ?", &[SqlValue::Text(receipt["op_id"].as_str().unwrap().to_owned())]).unwrap(), receipt, "{table}: an original receipt changed or vanished"); } owner(&h, "delete_record", json!({"table":table, "id":id})); let twice = call_tool_as_owner(&h, "device:binverbs", "delete_record", json!({"table":table, "id":id})); assert!(twice.is_error, "{table}: delete outside the Bin must not erase a binned row"); assert!(h.one(&format!("SELECT id FROM {storage} WHERE id = ?"), &[SqlValue::Text(id.to_owned())]).is_some(), "{table}: second Delete erased the record"); owner(&h, "delete_record", json!({"table":"bin", "id":id})); assert!(h.one(&format!("SELECT id FROM {storage} WHERE id = ?"), &[SqlValue::Text(id.to_owned())]).is_none(), "{table}: Delete forever kept the row"); assert_eq!(h.count("SELECT count(*) AS c FROM _tombstones WHERE tbl = ? AND row_id = ?", &[SqlValue::Text(storage.to_owned()), SqlValue::Text(id.to_owned())]), 1, "{table}: Delete forever left no tombstone"); } }