//! Search must reach a person's tables as well as engine records: otherwise an//! imported tool's records disappear from both Records and an assistant's search.mod support;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Value};use support::harness::Harness;use support::mcp::{call_tool, call_tool_raw, mint_token};fn definition(id: &str) -> Value { json!({"id":id,"name":"Search fixture","plural":"Search fixtures","picture":null,"builtin":false,"engine":null,"columns":[{"key":"name","type":"text"}, {"key":"body","type":"longtext"},{"key":"code","type":"choice","choices":["needle"]}],"title":"name","date":null,"project":null,"order":null,"slip":{"title":"name","subtitle":"body","trailing":null,"photo":null,"toggle":null},"tile":{"face":"slip-list"},"page":[{"heading":null,"columns":["name","body","code"]}],"instructions":""})}/// One value as a made table's column holds it.fn cell(value: &Value) -> SqlValue {match value {Value::Bool(yes) => SqlValue::Integer(i64::from(*yes)),Value::Number(n) => n.as_i64().map_or_else(|| SqlValue::Real(n.as_f64().unwrap_or(0.0)), SqlValue::Integer),Value::String(text) => SqlValue::Text(text.clone()), _ => SqlValue::Null, }}/// A record of made table `table`: a row of its own table, `cotton_<table>`,/// one column a key. A key the table has no column for is not stored.fn record(h: &Harness, id: &str, table: &str, data: Value, deleted: bool, workspace: Option<&str>) { cotton_store::schema::package_shape::step_file(&h.db).expect("the made tables");let store = format!("cotton_{table}");let held: Vec<String> = h .all("SELECT name FROM pragma_table_info(?)", &[SqlValue::Text(store.clone())]) .iter() .filter_map(|row| row["name"].as_str().map(str::to_string)) .collect(); assert!(!held.is_empty(), "{store} is no table of this file");letmut columns = vec!["id", "workspace_id", "created_at", "updated_at", "deleted_at"].into_iter().map(str::to_string).collect::<Vec<_>>();letmut params = vec![SqlValue::Text(id.into()),SqlValue::Text(workspace.unwrap_or(&h.workspace_id).into()),SqlValue::Text("2026-10-01".into()),SqlValue::Text("2026-10-01".into()),if deleted { SqlValue::Text("2026-10-01".into()) } else { SqlValue::Null }, ];for (key, value) in data.as_object().expect("an object") {if held.contains(key) { columns.push(format!("\"{key}\"")); params.push(cell(value)); } }let marks = vec!["?"; columns.len()].join(","); h.run(&format!("INSERT INTO {store} ({}) VALUES ({marks})", columns.join(",")), ¶ms);}fn setup() -> (Harness, String) {letmut h = Harness::new();let token = mint_token(&mut h, &["read", "write"], "Search test"); h.run("INSERT INTO cotton_table_definitions (id,workspace_id,definition,builtin,created_at,updated_at) VALUES ('fixture',?,?,0,'2026-10-01','2026-10-01')",&[SqlValue::Text(h.workspace_id.clone()),SqlValue::Text(definition("fixture").to_string())]);let tool = json!({"id":"fixture_tool","name":"Fixture tool","picture":"fixture","tables":["fixture"],"instructions":"","automations":[],"author":{"device":"invented","name":"Invented author"},"signature":null}); h.run("INSERT INTO cotton_tool_definitions (id,workspace_id,definition,created_at,updated_at) VALUES ('fixture_tool',?,?,'2026-10-01','2026-10-01')", &[SqlValue::Text(h.workspace_id.clone()),SqlValue::Text(tool.to_string())]);// Orphaned definitions remain in the same synced table as live ones. h.run("INSERT INTO cotton_table_definitions (id,workspace_id,definition,builtin,created_at,updated_at) VALUES ('imported',?,?,0,'2026-10-01','2026-10-01')",&[SqlValue::Text(h.workspace_id.clone()),SqlValue::Text(definition("imported").to_string())]); (h, token)}/// RULE: Search finds title and text matches in defined, imported, orphaned and built-in tables, with the address, readable table name, orphan status, ranked title and matched snippet.#[test]fn searches_defined_imported_and_builtin_tables_with_addresses_and_ranked_snippets() {let (h, token) = setup(); record( &h,"body-hit","fixture", json!({"name":"Plain","body":"A needle in text"}),false,None, ); record( &h,"title-hit","fixture", json!({"name":"Needle","body":"Something else"}),false,None, ); record( &h,"orphan-hit","imported", json!({"name":"Recovered needle"}),false,None, );// A built-in's record is never a made table's row: a todo is found// through its own engine only (below), never as "generic-builtin". record( &h,"nontext","fixture", json!({"name":"Plain","code":"needle","hidden":"needle"}),false,None, ); record( &h,"removed","fixture", json!({"name":"needle"}),true,None, );let todo = call_tool( &h, &token,"create_todo", json!({"title":"Needle from the engine"}), );let out = call_tool( &h, &token,"search_records", json!({"query":"needle","limit":1}), );let hits = out["records"].as_array().unwrap(); assert!(hits .iter() .any(|r| r["table"] == "fixture" && r["id"] == "title-hit" && r["title"] == "Needle")); assert!(hits .iter() .any(|r| r["table"] == "imported" && r["id"] == "orphan-hit")); assert!(hits .iter() .any(|r| r["table"] == "todo" && r["id"] == todo["id"])); assert_eq!(out["totals"]["fixture"], 2);let active = hits.iter().find(|r| r["table"] == "fixture").unwrap(); assert_eq!(active["table_name"], "Search fixture"); assert_eq!(active["orphaned"], false);let orphan = hits.iter().find(|r| r["table"] == "imported").unwrap(); assert_eq!(orphan["table_name"], "Search fixture"); assert_eq!(orphan["orphaned"], true);let all = call_tool(&h, &token, "search_records", json!({"query":"needle"})); assert!(all["records"] .as_array() .unwrap() .iter() .any(|r| r["id"] == "body-hit" && r["snippet"].as_str().unwrap().contains("needle"))); assert!(!all["records"] .as_array() .unwrap() .iter() .any(|r| r["id"] == "generic-builtin")); assert!(!all["records"] .as_array() .unwrap() .iter() .any(|r| r["id"] == "removed" || r["id"] == "nontext" || r["id"] == "shape"));let scoped = call_tool( &h, &token,"search_records", json!({"query":"needle","kinds":["todo"]}), ); assert!(scoped["records"] .as_array() .unwrap() .iter() .all(|r| r["table"] == "todo"));}/// RULE: A search treats percent and underscore as literal text and never reads another workspace's generic records.#[test]fn like_search_treats_wildcards_as_text_and_does_not_cross_workspaces() {let (h, token) = setup(); h.run("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES ('other','Other','fixture-owner','2026-10-01')",&[]); record( &h,"other-row","fixture", json!({"name":"100%_needle"}),false,Some("other"), ); record( &h,"literal","fixture", json!({"name":"100%_needle"}),false,None, ); record( &h,"wildcard","fixture", json!({"name":"100XXneedle"}),false,None, );let out = call_tool(&h, &token, "search_records", json!({"query":"100%_needle"}));let hits: Vec<_> = out["records"] .as_array() .unwrap() .iter() .filter(|r| r["table"] == "fixture") .collect(); assert_eq!(hits.len(), 1); assert_eq!(hits[0]["id"], "literal");}/// RULE: Search finds a sparse body match in a large made table and reports its matching total, rather than losing a record among unrelated rows.#[test]fn search_finds_the_body_match_in_a_large_table() {let (h, token) = setup(); cotton_store::schema::package_shape::step_file(&h.db).expect("the made tables"); h.run("WITH RECURSIVE n(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM n WHERE i<10000) INSERT INTO cotton_fixture (id,workspace_id,name,body,created_at,updated_at) SELECT 'bulk-'||i,?, 'Item '||i, CASE WHEN i=9999 THEN 'needle body' ELSE 'ordinary body' END, '2026-10-01','2026-10-01' FROM n",&[SqlValue::Text(h.workspace_id.clone())]);let out = call_tool(&h, &token, "search_records", json!({"query":"needle"})); assert_eq!(out["totals"]["fixture"], 1); assert!(out["records"] .as_array() .unwrap() .iter() .any(|r| r["id"] == "bulk-9999"));}/// RULE: Search includes a numeric title column as text, because a table may use any declared column as its title.#[test]fn a_numeric_title_is_searchable_without_searching_other_numeric_values() {let (h, token) = setup();letmut shape = definition("numbered"); shape["columns"][0]["type"] = json!("number"); h.run("INSERT INTO cotton_table_definitions (id,workspace_id,definition,builtin,created_at,updated_at) VALUES ('numbered',?,?,0,'2026-10-01','2026-10-01')", &[SqlValue::Text(h.workspace_id.clone()),SqlValue::Text(shape.to_string())]); record( &h,"number-title","numbered", json!({"name":745,"extra":900}),false,None, );let out = call_tool(&h, &token, "search_records", json!({"query":"745"})); assert!(out["records"] .as_array() .unwrap() .iter() .any(|r| r["table"] == "numbered" && r["title"] == "745" && r["snippet"] == "745"));let out = call_tool(&h, &token, "search_records", json!({"query":"900"})); assert!(!out["records"] .as_array() .unwrap() .iter() .any(|r| r["table"] == "numbered"));}/// RULE: Search never refuses over an unreadable definition and never hides one: it answers every readable record and names each table it could not read in `skipped`, with why; ordinary records named table_definition never poison definition reads.////// It refused the whole search until 12 Oct 2026 (architect: one stored/// definition this build cannot read must not take every other kind with it).#[test]fn unreadable_definitions_are_skipped_and_said_without_losing_readable_records() {let (h, token) = setup();for (id, shape) in [ ("future", {letmut d = definition("future"); d["columns"][0]["type"] = json!("future_type"); d }), ("broken", json!({})), ] {// A definition this build cannot read declares no table it can make,// so it holds no record to search: only the skip is said. h.run("INSERT INTO cotton_table_definitions (id,workspace_id,definition,created_at,updated_at) VALUES (?,?,?,'2026-10-01','2026-10-01')", &[SqlValue::Text(id.into()),SqlValue::Text(h.workspace_id.clone()),SqlValue::Text(shape.to_string())]); } record( &h,"readable","fixture", json!({"name":"needle"}),false,None, );let todo = call_tool(&h, &token, "create_todo", json!({"title":"needle todo"}));let note = call_tool( &h, &token,"create_note", json!({"title":"needle note","body":"needle"}), );let partial = call_tool(&h, &token, "search_records", json!({"query":"needle"}));let skipped: Vec<&str> = partial["skipped"] .as_array() .expect("a partial answer says what it left out") .iter() .filter_map(|skip| skip["table"].as_str()) .collect(); assert_eq!(skipped, ["broken", "future"], "{partial}"); h.run("DELETE FROM cotton_table_definitions WHERE id IN ('future', 'broken')", &[]);let whole = call_tool(&h, &token, "search_records", json!({"query":"needle"})); assert!(whole.get("skipped").is_none(), "{whole}");for result in [partial, whole] {let rows = result["records"].as_array().unwrap();for id in [json!("readable"), todo["id"].clone(), note["id"].clone()] { assert!(rows.iter().any(|r| r["id"] == id), "missing {id}: {result}"); } assert!(!rows .iter() .any(|r| r["table"] == "future" || r["table"] == "broken")); }}/// RULE: The kinds filter accepts a user table id and returns only that table's records, because Records can search a single imported or orphaned table.#[test]fn kinds_can_filter_one_user_table() {let (h, token) = setup(); record( &h,"fixture-hit","fixture", json!({"name":"needle"}),false,None, ); record( &h,"other-hit","imported", json!({"name":"needle"}),false,None, ); call_tool(&h, &token, "create_todo", json!({"title":"needle"}));let result = call_tool( &h, &token,"search_records", json!({"query":"needle","kinds":["fixture"]}), );let rows = result["records"].as_array().unwrap(); assert_eq!(rows.len(), 1); assert_eq!(rows[0]["id"], "fixture-hit");}/// What a built-in this build no longer ships leaves on a file seeded before/// it went (`order` left with Stores, 11 Oct 2026): its row, still saying it/// is a built-in kept by the `stores` engine.fn retired_order(h: &Harness) {let order = json!({"id":"order","name":"Order","plural":"Orders","picture":null,"builtin":true,"engine":"stores","columns":[{"key":"name","type":"text"}],"title":"name","date":null,"project":null,"order":null,"slip":{"title":"name","subtitle":null,"trailing":null,"photo":null,"toggle":null},"tile":{"face":"slip-list"},"page":[{"heading":null,"columns":["name"]}],"instructions":""}); h.run("INSERT INTO cotton_table_definitions (id,workspace_id,definition,builtin,created_at,updated_at) VALUES ('order',?,?,1,'2026-10-01','2026-10-01')", &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(order.to_string())]);}/// A stored definition no build can read: a made table whose row names/// another table.fn unreadable_ledger(h: &Harness) {let ledger = json!({"id":"other","name":"Ledger","plural":"Ledgers","picture":null,"builtin":false,"engine":null,"columns":[{"key":"name","type":"text"}],"title":"name","date":null,"project":null,"order":null,"slip":{"title":"name","subtitle":null,"trailing":null,"photo":null,"toggle":null},"tile":{"face":"slip-list"},"page":[{"heading":null,"columns":["name"]}],"instructions":""}); h.run("INSERT INTO cotton_table_definitions (id,workspace_id,definition,builtin,created_at,updated_at) VALUES ('ledger',?,?,0,'2026-10-01','2026-10-01')", &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(ledger.to_string())]);}/// RULE: A search across several kinds skips a table whose definition this build cannot read, says so in the answer's `skipped`, and answers every other kind; it never refuses the whole search — and a retired built-in's row is no table, so it is neither searched nor said.////// The architect, 12 Oct 2026 07:52 IST: search_records over the Cotton/// database with kinds ["note"] refused with 'table "order" says it is kept by/// an engine this build does not have'.#[test]fn a_search_skips_an_engine_less_table_and_answers_the_others() {let (h, token) = setup(); retired_order(&h); unreadable_ledger(&h); record(&h, "fixture-hit", "fixture", json!({"name":"Needle"}), false, None);let notes = call_tool_raw(&h, &token, "search_records", json!({"query":"needle","kinds":["note","fixture"]})); assert!(!notes.is_error, "{}", notes.text);let notes: Value = serde_json::from_str(¬es.text).unwrap(); assert!(notes["records"].as_array().unwrap().iter().any(|r| r["id"] == "fixture-hit"), "{notes}"); assert!(notes.get("skipped").is_none(), "a table not asked for is not said: {notes}");let everything = call_tool(&h, &token, "search_records", json!({"query":"needle"}));let records = everything["records"].as_array().unwrap(); assert!(records.iter().any(|r| r["id"] == "fixture-hit"), "{everything}");let skipped = everything["skipped"].as_array().expect("the answer says what it skipped"); assert_eq!(skipped.len(), 1, "the retired order is not said: {everything}"); assert_eq!(skipped[0]["table"], "ledger");}