Cotton code
2471 lines · 83.5 KB · RustRaw
//! Memory over the tools: the four agent verbs (`brief` · `recall` ·//! `remember` · `log_session`) plus `list_sessions`, the one-release aliases,//! and the audit trail.//!//! `log_session` and `list_sessions` are covered next door, in//! `tests/mcp_records_2_sessions.rs`. Since the memory-home change a memory belongs to its//! PROJECTS through `cotton_project_links`, with the arrangement on the link.//!//! Driven through `dispatch::call_tool` over a fake `ToolServices` against a//! real file rather than the `/v1/mcp` endpoint: what lands must be a write//! every device can find, so the assertions read the table and the stamp on the//! row — which IS the log since version 8. The//! six cases whose subject is the TRANSPORT — `tools/list`, `initialize` and//! the `cotton_mcp_audit` row the route writes — stayed in `cotton-server`.mod support;use std::sync::atomic::{AtomicU64, Ordering};use cotton_store::protocol::derived_id::project_link_id;use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_tools::mcp::protocol::tool_by_name;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use support::harness::{synthetic_uuid, Harness};use support::mcp::{call_tool, call_tool_raw, mint_token};/// When every seeded row says it was written.const AT: &str = "2026-08-22T10:00:00.000Z";/// The home project every case seeds: memory belongs to projects, so a test/// that would once have written a "global" entry writes it here.const HOME: &str = "p-home";const HOME_SLUG: &str = "home";const OTHER: &str = "p-other";const OTHER_SLUG: &str = "other";/// The retired-field refusals, said from the rule that owns them rather than/// retyped.use cotton_core::rules::memory_retired_fields::RetiredField;// ── the fixture ─────────────────────────────────────────────────────────────/// An op the way a device would mint one. The ids are DERIVED from a/// per-process counter, never random.fn op(table: &str, row_id: &str, patch: Value) -> Value {    static NEXT: AtomicU64 = AtomicU64::new(0);    let n = NEXT.fetch_add(1, Ordering::Relaxed);    json!({        "opId": format!("01J{:023}", n),        "deviceId": "device:seed",        "kind": "upsert",        "table": table,        "rowId": row_id,        "patch": patch,        "hlc": format!("1700000000{:03}:0000:device:seed", n),        "schemaVersion": SCHEMA_VERSION,    })}/// Fold ops into the file the way a device's push folds them. The server's own/// suite pushed them through `/v1/sync/push`; the fold under that route is what/// a suite about a TOOL actually needed of it.fn seed(h: &Harness, ops: Vec<Value>) {    h.seed(&ops);}fn project_op(h: &Harness, id: &str, slug: &str, repos: &[&str]) -> Value {    let name = {        let mut chars = slug.chars();        match chars.next() {            Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),            None => String::new(),        }    };    op(        "cotton_memory_projects",        id,        json!({            "id": id,            "workspace_id": h.workspace_id,            "slug": slug,            "name": name,            "repos": repos,            "status": "active",            "created_at": AT,            "updated_at": AT,        }),    )}/// One `cotton_memories` op. `over` is spread LAST, exactly as the/// TypeScript's is, so a case can override any default including the title.fn memory_op(h: &Harness, slug: &str, over: Value) -> (String, Value) {    let id = synthetic_uuid(slug);    let mut patch = json!({        "id": id,        "workspace_id": h.workspace_id,        "slug": slug,        "title": format!("The {slug} rule"),        "body": "",        "status": "active",        "machine": Value::Null,        "visibility": "private",        "origin_kind": "user",        "origin_label": Value::Null,        "source_external_id": Value::Null,        "archived_at": Value::Null,        "created_at": AT,        "updated_at": AT,    });    if let (Some(patch), Some(over)) = (patch.as_object_mut(), over.as_object()) {        for (key, value) in over {            patch.insert(key.clone(), value.clone());        }    }    let id = patch["id"].as_str().unwrap_or_default().to_string();    (id.clone(), op("cotton_memories", &id, patch))}/// How an entry sits in one project's list.#[derive(Debug, Clone, Copy, Default)]struct Home {    project: Option<&'static str>,    pinned: bool,    position: Option<f64>,}impl Home {    fn at(position: f64) -> Home {        Home {            position: Some(position),            ..Home::default()        }    }    fn pinned_at(position: f64) -> Home {        Home {            pinned: true,            position: Some(position),            ..Home::default()        }    }    fn in_project(project: &'static str) -> Home {        Home {            project: Some(project),            ..Home::default()        }    }}/// The link row that gives a memory a home. `position` defaults/// to 1000 for the same reason the TypeScript's seed does: the column has no/// default a list can live with, and a case asserting order must not pass for/// the wrong reason.fn link_op(h: &Harness, project_id: &str, memory_id: &str, home: Home) -> Value {    let id = project_link_id(project_id, "memory", memory_id);    op(        "cotton_project_links",        &id,        json!({            "id": id,            "workspace_id": h.workspace_id,            "project_id": project_id,            "record_kind": "memory",            "record_id": memory_id,            "note": Value::Null,            "applied_by": "user",            "pinned": home.pinned,            "position": home.position.unwrap_or(1000.0),            "created_at": AT,            "updated_at": AT,        }),    )}/// One entry with one home: the memory op and its link op.fn entry(h: &Harness, slug: &str, over: Value, home: Home) -> (String, Vec<Value>) {    let (id, memory) = memory_op(h, slug, over);    let link = link_op(h, home.project.unwrap_or(HOME), &id, home);    (id, vec![memory, link])}// ── reading the file back ───────────────────────────────────────────────────fn one(h: &Harness, sql: &str, params: Vec<SqlValue>) -> Option<cotton_store::driver::Row> {    h.with(|db| db.get(sql, &params)).expect("the read runs")}fn all(h: &Harness, sql: &str, params: Vec<SqlValue>) -> Vec<cotton_store::driver::Row> {    h.with(|db| db.all(sql, &params)).expect("the read runs")}fn memory_text(h: &Harness, slug: &str, column: &str) -> Option<String> {    one(        h,        &format!("SELECT {column} AS value FROM cotton_memories WHERE slug = ?"),        vec![SqlValue::Text(slug.to_string())],    )    .and_then(|row| row.text("value").map(str::to_string))}fn memory_exists(h: &Harness, slug: &str) -> bool {    one(        h,        "SELECT id AS value FROM cotton_memories WHERE slug = ?",        vec![SqlValue::Text(slug.to_string())],    )    .is_some()}fn memory_count(h: &Harness) -> i64 {    one(h, "SELECT count(*) AS n FROM cotton_memories", Vec::new())        .and_then(|row| row.int("n"))        .unwrap_or(0)}/// One column of the LINK joining this slug to this project.fn link_real(h: &Harness, slug: &str, project_id: &str, column: &str) -> Option<f64> {    one(        h,        &format!(            "SELECT l.\"{column}\" AS value FROM cotton_project_links l \             JOIN cotton_memories m ON m.id = l.record_id \             WHERE l.record_kind = 'memory' AND m.slug = ? AND l.project_id = ?"        ),        vec![            SqlValue::Text(slug.to_string()),            SqlValue::Text(project_id.to_string()),        ],    )    .and_then(|row| {        row.real("value")            .or_else(|| row.int("value").map(|n| n as f64))    })}fn link_int(h: &Harness, slug: &str, project_id: &str, column: &str) -> Option<i64> {    link_real(h, slug, project_id, column).map(|value| value as i64)}fn link_text(h: &Harness, slug: &str, project_id: &str, column: &str) -> Option<String> {    one(        h,        &format!(            "SELECT l.{column} AS value FROM cotton_project_links l \             JOIN cotton_memories m ON m.id = l.record_id \             WHERE l.record_kind = 'memory' AND m.slug = ? AND l.project_id = ?"        ),        vec![            SqlValue::Text(slug.to_string()),            SqlValue::Text(project_id.to_string()),        ],    )    .and_then(|row| row.text("value").map(str::to_string))}fn link_exists(h: &Harness, slug: &str, project_id: &str) -> bool {    link_text(h, slug, project_id, "id").is_some()}/// The tables a phone would be handed the MCP writer's writes in.////// There is no log: the tables answer for an author, so this is an exchange/// from empty cursors — everything this file holds — narrowed to the writes/// stamped by the FILE's author (`_meta.author_id`, which every writer stamps/// with since slice 2c; the seeds are folded under a peer's id and drop out).fn mcp_op_tables(h: &Harness) -> Vec<String> {    let author = h.file_author();    every_op(h)        .into_iter()        .filter(|op| op.device_id == author)        .map(|op| op.table)        .collect()}/// Every op this file would hand a peer starting from nothing, page by page:/// the kit and the shell a harness holds fill more than one page.fn every_op(h: &Harness) -> Vec<cotton_store::protocol::types::CottonOp> {    let mut seen = std::collections::BTreeMap::new();    let mut ops = Vec::new();    loop {        let page = cotton_store::exchange::answer(&h.db, &seen, 5_000).expect("the file answers a peer");        ops.extend(page.ops);        seen = page.cursors;        if !page.has_more {            return ops;        }    }}// ── the harness ─────────────────────────────────────────────────────────────struct Seeded {    h: Harness,    secret: String,}fn harness_with_token() -> Seeded {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    Seeded { h, secret }}/// A harness with the home project already there.fn home_harness() -> Seeded {    let s = harness_with_token();    seed(&s.h, vec![project_op(&s.h, HOME, HOME_SLUG, &[])]);    s}/// `remember` into the home project, unless the args say otherwise.fn remember(s: &Seeded, args: Value) -> support::mcp::ToolAnswer {    let mut merged = Map::new();    merged.insert("project".to_string(), Value::from(HOME_SLUG));    if let Some(args) = args.as_object() {        for (key, value) in args {            merged.insert(key.clone(), value.clone());        }    }    call_tool_raw(&s.h, &s.secret, "remember", Value::Object(merged))}fn slug_of(value: &Value) -> String {    value["slug"].as_str().expect("a slug").to_string()}fn slugs_of(value: &Value) -> Vec<String> {    value["memories"]        .as_array()        .expect("a memories array")        .iter()        .map(slug_of)        .collect()}/// One tool's input schema, read from the catalogue THIS crate owns — the very/// document `tools/list` renders, without the transport that renders it.fn tool_schema(name: &str) -> Value {    tool_by_name(name)        .unwrap_or_else(|| panic!("{name} is not in the catalogue"))        .input_schema_json()}// ── the retired taxonomy ────────────────────────────────────────────────────// Schema v14 dropped `kind` and `layer`. A client one release behind still// sends them, and the answer is a REFUSAL that teaches, not a quiet drop.#[test]fn refuses_a_stale_kind_or_layer_with_the_teaching_line_writing_nothing() {    let s = home_harness();    for stale in [        json!({ "layer": "state" }),        json!({ "kind": "business" }),        json!({ "kind": "technical" }),    ] {        let mut args = Map::new();        args.insert(            "title".to_string(),            Value::from("The rehearsal ran against a restored dump"),        );        args.insert("project".to_string(), Value::from(HOME_SLUG));        for (key, value) in stale.as_object().expect("an object") {            args.insert(key.clone(), value.clone());        }        let answer = call_tool_raw(&s.h, &s.secret, "remember", Value::Object(args));        assert!(answer.is_error, "{stale} was not refused");        assert_eq!(answer.text, RetiredField::Taxonomy.say(&[]));    }    assert_eq!(memory_count(&s.h), 0);}// The teaching the retired `kind: technical` refusal used to carry has to// survive somewhere a caller reads it, and this line is where it went.#[test]fn the_refusal_still_says_where_a_technical_fact_belongs() {    let lowered = RetiredField::Taxonomy.say(&[]).to_lowercase();    assert!(lowered.contains("technical"));    assert!(lowered.contains("repository"));}// The READ path had the same hole, and a half-applied rule is the one that// misleads: an assistant still calling `recall({ kind })` was handed EVERY// entry back with no word that its filter did nothing.#[test]fn refuses_a_stale_kind_or_layer_on_recall_too_rather_than_answering_unfiltered() {    let s = home_harness();    remember(        &s,        json!({ "title": "Calls stay unmetered in every plan." }),    );    for stale in [json!({ "kind": "about_me" }), json!({ "layer": "belief" })] {        let answer = call_tool_raw(&s.h, &s.secret, "recall", stale.clone());        assert!(answer.is_error, "{stale} was not refused");    }    // And the unfiltered read still works — the refusal is about the retired    // names, not about recall.    let answer = call_tool_raw(&s.h, &s.secret, "recall", json!({}));    assert!(!answer.is_error, "{}", answer.text);}// ── memory is flat, and belongs to projects ─────────────────────────────────#[test]fn remembers_a_sentence_with_no_kind_at_all() {    let s = home_harness();    let answer = remember(        &s,        json!({ "title": "Ship the pilot before the quarter turns." }),    );    assert!(!answer.is_error, "{}", answer.text);    let result = answer.json();    assert!(result["slug"].is_string());    assert!(result.get("kind").is_none());}#[test]fn recall_project_answers_in_that_projects_order_pinned_first_then_position() {    let s = home_harness();    let mut ops = Vec::new();    ops.extend(entry(&s.h, "third", json!({}), Home::at(3000.0)).1);    ops.extend(entry(&s.h, "first", json!({}), Home::at(1000.0)).1);    ops.extend(entry(&s.h, "pinned", json!({}), Home::pinned_at(9000.0)).1);    seed(&s.h, ops);    let result = call_tool(&s.h, &s.secret, "recall", json!({ "project": HOME_SLUG }));    assert_eq!(slugs_of(&result), vec!["pinned", "first", "third"]);    assert_eq!(        result["memories"][0]["projects"],        json!([{ "slug": HOME_SLUG, "pinned": true, "position": 9000 }])    );}// The same sentence, arranged differently in two projects: the order is the// link's, and one entry has one link per project.#[test]fn arranges_one_entry_differently_per_project() {    let s = home_harness();    let mut ops = vec![project_op(&s.h, OTHER, OTHER_SLUG, &[])];    let (a, a_ops) = entry(&s.h, "a", json!({}), Home::at(1000.0));    let (b, b_ops) = entry(&s.h, "b", json!({}), Home::at(2000.0));    ops.extend(a_ops);    ops.extend(b_ops);    ops.push(link_op(&s.h, OTHER, &a, Home::at(5000.0)));    ops.push(link_op(&s.h, OTHER, &b, Home::pinned_at(1000.0)));    seed(&s.h, ops);    let home = call_tool(&s.h, &s.secret, "recall", json!({ "project": HOME_SLUG }));    let other = call_tool(&s.h, &s.secret, "recall", json!({ "project": OTHER_SLUG }));    assert_eq!(slugs_of(&home), vec!["a", "b"]);    assert_eq!(slugs_of(&other), vec!["b", "a"]);    // And the entry carries both arrangements, by project.    assert_eq!(        other["memories"][0]["projects"],        json!([            { "slug": HOME_SLUG, "pinned": false, "position": 2000 },            { "slug": OTHER_SLUG, "pinned": true, "position": 1000 },        ])    );    assert_eq!(memory_count(&s.h), 2);}#[test]fn recall_has_no_kind_filter_to_pass_and_no_global_project_to_name() {    let s = home_harness();    let schema = tool_schema("recall");    assert!(schema["properties"].get("kind").is_none());    assert!(schema["properties"].get("layer").is_none());    assert!(!schema.to_string().contains("global"));    let answer = call_tool_raw(&s.h, &s.secret, "recall", json!({ "project": "global" }));    assert!(answer.is_error);    assert!(answer.text.contains(HOME_SLUG), "{}", answer.text);}#[test]fn remember_requires_the_sentence() {    let s = home_harness();    let schema = tool_schema("remember");    assert_eq!(schema["required"], json!(["title"]));    assert!(schema["properties"].get("kind").is_none());    assert!(schema["properties"].get("layer").is_none());    let untitled = call_tool_raw(&s.h, &s.secret, "remember", json!({ "project": HOME_SLUG }));    assert!(untitled.is_error);    assert!(untitled.text.contains("title is required"), "{}", untitled.text);    let both = call_tool_raw(        &s.h,        &s.secret,        "remember",        json!({ "title": "A fact", "project": HOME_SLUG, "owner": true }),    );    assert!(both.is_error);    assert!(both.text.contains("not both"), "{}", both.text);    assert_eq!(memory_count(&s.h), 0);}/// RULE: remember with no project, in the personal database, writes an Owner entry — reconciled against that database like any other — and the Owner section opens every brief, bound to a project or not.#[test]fn remember_with_no_project_writes_an_owner_entry_that_opens_every_brief() {    let s = home_harness();    seed(&s.h, entry(&s.h, "standing", json!({}), Home::at(1000.0)).1);    let sentence = "I work only from my phone, so anything I must see goes into Cotton.";    let added = call_tool(&s.h, &s.secret, "remember", json!({ "title": sentence }));    assert_eq!(added["action"], json!("add"), "{added}");    assert_eq!(added["owner"], json!(true), "{added}");    let again = call_tool(&s.h, &s.secret, "remember", json!({ "title": sentence, "owner": true }));    assert_eq!(again["action"], json!("noop"), "{again}");    assert_eq!(memory_count(&s.h), 2);    for args in [json!({ "project": HOME_SLUG }), json!({})] {        let markdown = call_tool(&s.h, &s.secret, "brief", args.clone())["briefing"]            .as_str()            .unwrap_or_default()            .to_string();        let owner = markdown.find("## Owner").unwrap_or_else(|| panic!("{args}: {markdown}"));        assert!(markdown[owner..].contains(sentence), "{markdown}");        if let Some(project) = markdown.find("## Project") {            assert!(owner < project, "{markdown}");            // Not in the project's own list: it briefs in no project.            assert!(!markdown[project..].contains(sentence), "{markdown}");        }    }}/// RULE: An Owner entry that would take the Owner section past its 300 tokens is refused with the numbers, and nothing is written.#[test]fn an_owner_entry_past_the_owner_cap_is_refused() {    let s = home_harness();    let topics = ["mornings", "travel", "money", "health", "family", "music"];    let mut refused = None;    for (n, topic) in topics.iter().enumerate() {        let title = format!(            "On {topic}: the owner said a long thing number {n} that runs on and on, because some rulings need the whole of their reasons spelled out in one sentence to be useful later, and this is one of those."        );        let answer = call_tool_raw(&s.h, &s.secret, "remember", json!({ "title": title, "force": true }));        if answer.is_error {            refused = Some((n, answer.text));            break;        }    }    let (written, text) = refused.expect("the cap refused one");    assert!(written > 0, "{text}");    assert!(text.contains("Owner section would be") && text.contains("300-token"), "{text}");    assert_eq!(memory_count(&s.h), written as i64);}/// RULE: memory_update edits the sentence, its source and its machine scope, and pins it per project — there is no dated flag to move.#[test]fn memory_update_moves_the_sentence_its_source_and_a_projects_pin() {    let s = home_harness();    let schema = tool_schema("memory_update");    assert!(schema["properties"].get("kind").is_none());    assert!(schema["properties"].get("layer").is_none());    // The whole editable surface, so a field that quietly reappears is caught by    // name. `moveToProject` left with the memory-home change — a home is a link, edited like    // any record's — and `dated` left with v34's own successor.    assert!(schema["properties"].get("dated").is_none());    let mut properties: Vec<&str> = schema["properties"]        .as_object()        .expect("an object")        .keys()        .map(String::as_str)        .collect();    properties.sort_unstable();    assert_eq!(        properties,        vec!["id", "machine", "pinned", "project", "slug", "source", "title"]    );    seed(&s.h, entry(&s.h, "a", json!({}), Home::at(1000.0)).1);    let moved = call_tool_raw(        &s.h,        &s.secret,        "memory_update",        json!({ "slug": "a", "moveToProject": HOME_SLUG }),    );    assert!(moved.is_error);    assert!(moved.text.contains("link_to_project"), "{}", moved.text);}// Nothing in the suite expanded a memory through get_record, so a column that// no longer exists sat in the SELECT and only a live assistant would have// found it — as a 500.#[test]fn a_new_entry_lands_at_the_end_of_the_projects_list() {    let s = home_harness();    seed(&s.h, entry(&s.h, "existing", json!({}), Home::at(1000.0)).1);    let result = remember(&s, json!({ "title": "A second thing the owner said." })).json();    let slug = slug_of(&result);    assert!(link_real(&s.h, &slug, HOME, "position").unwrap_or_default() > 1000.0);    assert_eq!(link_int(&s.h, &slug, HOME, "pinned"), Some(0));}// ── remember — reconcile-on-write ───────────────────────────────────────────/// RULE: An entry an assistant transcribed goes live straight away, and briefs unmarked — memory has no review state (owner, 25 Oct 2026, #77).#[test]fn adds_a_fact_with_no_candidates_it_lands_active_and_linked_to_its_project() {    let s = home_harness();    let ruling = remember(        &s,        json!({            "title": "Chefs run their own delivery",            "source": "https://github.com/example/repo/pull/1696",        }),    )    .json();    assert_eq!(ruling["action"], "add");    assert_eq!(ruling["status"], "active");    assert_eq!(ruling["project"], HOME_SLUG);    let ruling_slug = slug_of(&ruling);    assert_eq!(        memory_text(&s.h, &ruling_slug, "status").as_deref(),        Some("active")    );    assert_eq!(memory_text(&s.h, &ruling_slug, "body").as_deref(), Some(""));    assert_eq!(        memory_text(&s.h, &ruling_slug, "source").as_deref(),        Some("https://github.com/example/repo/pull/1696")    );    assert_eq!(link_int(&s.h, &ruling_slug, HOME, "pinned"), Some(0));    assert_eq!(        link_text(&s.h, &ruling_slug, HOME, "applied_by").as_deref(),        Some("agent")    );    let preference = remember(&s, json!({ "title": "Prefers prose over option menus" })).json();    assert_eq!(preference["action"], "add");    assert_eq!(preference["status"], "active");    let preference_slug = slug_of(&preference);    assert_eq!(        memory_text(&s.h, &preference_slug, "origin_kind").as_deref(),        Some("agent")    );    // And it briefs at once, as the sentence and nothing else.    let result = call_tool(&s.h, &s.secret, "brief", json!({ "project": HOME_SLUG }));    let briefing = result["briefing"].as_str().unwrap_or_default();    assert!(        briefing.contains("- [prefers-prose-over-option-menus] Prefers prose over option menus\n")            || briefing.ends_with("- [prefers-prose-over-option-menus] Prefers prose over option menus"),        "{briefing}"    );}#[test]fn refuses_a_body_the_sentence_is_the_memory() {    let s = home_harness();    let answer = remember(        &s,        json!({ "title": "Chefs run their own delivery", "body": "Since the relaunch." }),    );    assert!(answer.is_error);    assert_eq!(answer.text, RetiredField::Body.say(&[]));    assert_eq!(memory_count(&s.h), 0);}/// RULE: remember refuses a dated argument by name and tells the caller to put the expiry in the sentence instead.#[test]fn refuses_a_dated_argument_and_says_where_an_expiry_goes() {    let s = home_harness();    let refused = call_tool_raw(        &s.h,        &s.secret,        "remember",        json!({            "title": "A developer MCP lets agents run commands on any Mac",            "project": HOME_SLUG,            "dated": true,        }),    );    assert!(refused.is_error);    assert_eq!(refused.text, RetiredField::Dated.say(&[]));    assert!(refused.text.contains("valid until"), "{}", refused.text);    assert_eq!(memory_count(&s.h), 0);    // The same sentence, with the expiry where it belongs, lands.    let landed = remember(        &s,        json!({            "title": "A developer MCP lets agents run commands on any Mac — until the app goes public",        }),    )    .json();    assert!(memory_text(&s.h, &slug_of(&landed), "title")        .expect("the sentence")        .contains("until the app goes public"));}/// RULE: The dated argument is off the remember and recall surfaces entirely, and a recall that filters by it is refused rather than served unfiltered.#[test]fn the_dated_argument_is_off_every_memory_surface() {    let s = home_harness();    for tool in ["remember", "memory_update", "recall"] {        assert!(            tool_schema(tool)["properties"].get("dated").is_none(),            "{tool} still advertises dated"        );    }    let refused = call_tool_raw(&s.h, &s.secret, "recall", json!({ "dated": true }));    assert!(refused.is_error);}#[test]fn answers_noop_at_high_similarity_and_writes_nothing() {    let s = home_harness();    let first = remember(        &s,        json!({ "title": "Never cut a prod release without an explicit ask" }),    )    .json();    let again = remember(        &s,        json!({ "title": "Never cut a prod release without an explicit ask." }),    );    assert!(!again.is_error, "{}", again.text);    let again = again.json();    assert_eq!(again["action"], "noop");    assert_eq!(again["existing"]["slug"], first["slug"]);    assert_eq!(memory_count(&s.h), 1);}// One sentence lives once. The same thing said in the context of another// project is that project GAINING the entry — not a duplicate, not a no-op.#[test]fn links_the_existing_entry_when_the_same_sentence_arrives_for_another_project() {    let s = home_harness();    seed(&s.h, vec![project_op(&s.h, OTHER, OTHER_SLUG, &[])]);    let first = remember(&s, json!({ "title": "Ship the server first" })).json();    assert_eq!(first["action"], "add");    let first_slug = slug_of(&first);    let again = call_tool_raw(        &s.h,        &s.secret,        "remember",        json!({ "title": "Ship the server first.", "project": OTHER_SLUG, "pinned": true }),    );    assert!(!again.is_error, "{}", again.text);    let again = again.json();    assert_eq!(again["action"], "linked");    assert_eq!(again["slug"], first["slug"]);    assert_eq!(again["project"], OTHER_SLUG);    assert_eq!(memory_count(&s.h), 1);    // The new home has its own arrangement: pinned there, unpinned at home.    assert_eq!(link_int(&s.h, &first_slug, OTHER, "pinned"), Some(1));    assert_eq!(link_int(&s.h, &first_slug, HOME, "pinned"), Some(0));    let other = call_tool(&s.h, &s.secret, "recall", json!({ "project": OTHER_SLUG }));    assert_eq!(slugs_of(&other), vec![first_slug]);}#[test]fn asks_for_a_decision_in_the_band_and_writes_nothing_naming_each_candidates_projects() {    let s = home_harness();    let first = remember(        &s,        json!({ "title": "Never cut a prod release without an explicit ask" }),    )    .json();    let near = remember(        &s,        json!({            "title": "Never cut a prod release without the owner's explicit per-instance ask first",        }),    );    assert!(!near.is_error, "{}", near.text);    let near = near.json();    assert_eq!(near["needsDecision"], json!(true));    let candidates = near["candidates"].as_array().expect("candidates");    assert!(candidates.iter().any(|c| c["slug"] == first["slug"]));    assert_eq!(candidates[0]["projects"], json!([HOME_SLUG]));    assert!(candidates[0]["updatedAt"].is_string());    assert!(near["hint"].is_string());    assert_eq!(memory_count(&s.h), 1);}// Candidates are found across the WHOLE workspace, not per list: a sentence// already held in another project is exactly what a session about to// duplicate it needs to be shown.#[test]fn finds_candidates_in_other_projects() {    let s = home_harness();    seed(&s.h, vec![project_op(&s.h, OTHER, OTHER_SLUG, &[])]);    remember(        &s,        json!({ "title": "Never cut a prod release without an explicit ask" }),    );    let near = call_tool(        &s.h,        &s.secret,        "remember",        json!({            "title": "Never cut a prod release without the owner's explicit per-instance ask first",            "project": OTHER_SLUG,        }),    );    assert_eq!(near["needsDecision"], json!(true));    assert_eq!(near["candidates"][0]["projects"], json!([HOME_SLUG]));    assert_eq!(memory_count(&s.h), 1);}#[test]fn finds_a_candidate_by_shared_terms_even_when_the_wording_differs() {    let s = home_harness();    remember(        &s,        json!({ "title": "Litestream restores must be rehearsed monthly against the host" }),    );    let reworded = remember(        &s,        json!({ "title": "Rehearse the litestream restore on the host every month" }),    )    .json();    assert_eq!(reworded["needsDecision"], json!(true));}#[test]fn adds_on_decision_add_despite_candidates() {    let s = home_harness();    remember(        &s,        json!({ "title": "Never cut a prod release without an explicit ask" }),    );    let added = remember(        &s,        json!({            "title": "Never cut a prod release without the owner's explicit per-instance ask first",            "decision": { "action": "add" },        }),    )    .json();    assert_eq!(added["action"], "add");    assert_eq!(memory_count(&s.h), 2);}#[test]fn patches_the_target_on_decision_update_keeping_its_slug_and_recording_history() {    let s = home_harness();    let first = remember(        &s,        json!({ "title": "Never cut a prod release without an explicit ask" }),    )    .json();    let slug = slug_of(&first);    let updated = remember(        &s,        json!({            "title": "Never cut a prod release without an explicit per-instance ask",            "source": "https://github.com/example/repo/pull/2",            "decision": { "action": "update", "target": slug },        }),    )    .json();    assert_eq!(updated["action"], "update");    assert_eq!(updated["slug"], json!(slug));    assert_eq!(memory_count(&s.h), 1);    assert_eq!(        memory_text(&s.h, &slug, "title").as_deref(),        Some("Never cut a prod release without an explicit per-instance ask")    );    assert_eq!(memory_text(&s.h, &slug, "body").as_deref(), Some(""));    assert_eq!(        memory_text(&s.h, &slug, "source").as_deref(),        Some("https://github.com/example/repo/pull/2")    );    let versions = all(        &s.h,        "SELECT id FROM cotton_changes WHERE kind = 'memory' AND before IS NOT NULL",        Vec::new(),    );    assert!(!versions.is_empty());}/// RULE: Correcting a sentence through remember's update path leaves the entry's arrangement in every project exactly where it was.#[test]fn an_update_rewrites_the_sentence_and_leaves_the_arrangement_alone() {    let s = home_harness();    let first = remember(&s, json!({ "title": "The importer is node-only" })).json();    let slug = slug_of(&first);    let seat = link_real(&s.h, &slug, HOME, "position");    let pinned = link_int(&s.h, &slug, HOME, "pinned");    let updated = remember(        &s,        json!({            "title": "I keep the importer node-only — never import it from an app",            "decision": { "action": "update", "target": slug },        }),    )    .json();    assert_eq!(updated["action"], "update");    assert_eq!(updated["slug"], json!(slug));    assert!(memory_text(&s.h, &slug, "title")        .expect("the sentence")        .starts_with("I keep the importer node-only"));    assert_eq!(link_real(&s.h, &slug, HOME, "position"), seat);    assert_eq!(link_int(&s.h, &slug, HOME, "pinned"), pinned);}#[test]fn inserts_the_new_fact_and_closes_the_old_one_on_decision_supersede() {    let s = home_harness();    let first = remember(        &s,        json!({ "title": "Delivery is operated by the platform's own riders" }),    )    .json();    let old_slug = slug_of(&first);    let superseded = remember(        &s,        json!({            "title": "Delivery is run by each chef since the relaunch",            "decision": { "action": "supersede", "target": old_slug },        }),    )    .json();    assert_eq!(superseded["action"], "supersede");    assert_eq!(superseded["superseded"], json!(old_slug));    assert_eq!(superseded["project"], HOME_SLUG);    let fresh_slug = slug_of(&superseded);    assert_eq!(        memory_text(&s.h, &fresh_slug, "status").as_deref(),        Some("active")    );    assert!(link_exists(&s.h, &fresh_slug, HOME));    assert_eq!(        memory_text(&s.h, &old_slug, "status").as_deref(),        Some("archived")    );    assert_eq!(        memory_text(&s.h, &old_slug, "superseded_by"),        memory_text(&s.h, &fresh_slug, "id")    );    // Archiving keeps the links, so un-archiving restores the homes.    assert!(link_exists(&s.h, &old_slug, HOME));}#[test]fn refuses_an_unknown_decision_target() {    let s = home_harness();    let answer = remember(        &s,        json!({ "title": "A fact", "decision": { "action": "update", "target": "no-such-slug" } }),    );    assert!(answer.is_error);    assert_eq!(memory_count(&s.h), 0);}#[test]fn archived_rows_cannot_crowd_live_candidates_out_of_the_fts_window() {    let s = home_harness();    // Eight short archived titles outrank the wordier live one on bm25; the    // status filter must sit INSIDE the limited FTS query, or the live entry    // falls off the top-8 and the reconcile loop never sees it.    let mut ops = Vec::new();    for index in 0..8 {        ops.push(            memory_op(                &s.h,                &format!("old-{index}"),                json!({                    "title": format!("Litestream snapshot {index}"),                    "status": "archived",                    "archived_at": AT,                }),            )            .1,        );    }    ops.extend(        entry(            &s.h,            "live-policy",            json!({ "title": "Keep every litestream snapshot verified after the restore drill" }),            Home::default(),        )        .1,    );    seed(&s.h, ops);    let answer = remember(        &s,        json!({ "title": "Rotate litestream snapshot credentials monthly" }),    );    assert!(!answer.is_error, "{}", answer.text);    let answer = answer.json();    assert_eq!(answer["needsDecision"], json!(true));    let slugs: Vec<String> = answer["candidates"]        .as_array()        .expect("candidates")        .iter()        .map(slug_of)        .collect();    assert!(slugs.iter().any(|slug| slug == "live-policy"), "{slugs:?}");    assert!(!slugs.iter().any(|slug| slug == "old-0"), "{slugs:?}");    assert!(!memory_exists(        &s.h,        "rotate-litestream-snapshot-credentials-monthly"    ));}#[test]fn refuses_credentials_and_an_over_long_title() {    let s = home_harness();    let secretish = remember(        &s,        json!({ "title": "The token is ghp_abcdefghijklmnopqrstuvwxyz0123456789" }),    );    assert!(secretish.is_error, "{}", secretish.text);    let long = remember(&s, json!({ "title": "x".repeat(281) }));    assert!(long.is_error);    assert_eq!(memory_count(&s.h), 0);}// One slug per workspace: a slug brought by the caller that another project's// entry already holds is refused, never silently suffixed.#[test]fn refuses_a_slug_taken_anywhere_in_the_workspace() {    let s = home_harness();    let mut ops = vec![project_op(&s.h, OTHER, OTHER_SLUG, &[])];    ops.extend(entry(&s.h, "taken", json!({}), Home::default()).1);    seed(&s.h, ops);    let answer = call_tool_raw(        &s.h,        &s.secret,        "remember",        json!({            "title": "Something else entirely about the weather",            "project": OTHER_SLUG,            "slug": "taken",        }),    );    assert!(answer.is_error);    assert!(answer.text.contains("already exists"), "{}", answer.text);    assert_eq!(memory_count(&s.h), 1);}#[test]fn lands_every_write_as_an_op_the_phones_pull_the_entry_and_its_link() {    let s = home_harness();    remember(&s, json!({ "title": "A fact" }));    let tables = mcp_op_tables(&s.h);    assert!(tables.iter().any(|table| table == "cotton_memories"));    assert!(tables.iter().any(|table| table == "cotton_project_links"));}// ── recall ──────────────────────────────────────────────────────────────────fn seed_project(s: &Seeded) {    let mut ops = vec![project_op(        &s.h,        "p-tinmen",        "tinmen",        &["github.com/example/tinmen"],    )];    ops.extend(        entry(            &s.h,            "litestream-restore",            json!({                "title": "Rehearse the litestream restore monthly",                "body": "On the host.",                "origin_kind": "agent",                "origin_label": "Claude",            }),            Home::default(),        )        .1,    );    ops.extend(        entry(            &s.h,            "no-prod-release",            json!({ "title": "Never cut a prod release without the ask" }),            Home::default(),        )        .1,    );    ops.extend(        entry(            &s.h,            "wildcard",            json!({ "title": "Use the * wildcard carefully" }),            Home::default(),        )        .1,    );    ops.extend(        entry(            &s.h,            "on-tinmen",            json!({ "title": "Tinmen chefs run their own delivery" }),            Home::in_project("p-tinmen"),        )        .1,    );    ops.push(        memory_op(            &s.h,            "gone",            json!({                "title": "An archived fact about litestream",                "status": "archived",                "archived_at": AT,            }),        )        .1,    );    ops.extend(        entry(            &s.h,            "reads-no-prs",            json!({ "title": "Reads no PRs" }),            Home::default(),        )        .1,    );    seed(&s.h, ops);}#[test]fn returns_the_specs_shape_whose_words_where_since_when() {    let s = home_harness();    seed_project(&s);    let result = call_tool(&s.h, &s.secret, "recall", json!({ "q": "litestream" }));    let memories = result["memories"].as_array().expect("memories");    assert_eq!(memories.len(), 1);    let entry = memories[0].as_object().expect("an object");    assert!(entry["id"].is_string());    assert_eq!(entry["slug"], "litestream-restore");    assert_eq!(entry["title"], "Rehearse the litestream restore monthly");    // Where it briefs, and how it is arranged THERE.    assert_eq!(        entry["projects"],        json!([{ "slug": HOME_SLUG, "pinned": false, "position": 1000 }])    );    assert_eq!(entry["status"], "active");    assert_eq!(entry["originKind"], "agent");    assert_eq!(entry["originLabel"], "Claude");    assert_eq!(entry["machine"], Value::Null);    assert_eq!(entry["source"], Value::Null);    assert_eq!(entry["supersededBy"], Value::Null);    assert_eq!(entry["archivedAt"], Value::Null);    assert_eq!(entry["createdAt"], AT);    assert_eq!(entry["updatedAt"], AT);    // The whole shape, so a field silently added beside these is caught.    assert_eq!(        entry.keys().map(String::as_str).collect::<Vec<_>>(),        vec![            "id",            "slug",            "title",            "projects",            "status",            "originKind",            "originLabel",            "machine",            "source",            "supersededBy",            "archivedAt",            "createdAt",            "updatedAt",        ]    );    let with_body = call_tool_raw(        &s.h,        &s.secret,        "recall",        json!({ "q": "litestream", "withBody": true }),    );    assert!(with_body.is_error, "the retired withBody argument must be refused");}#[test]fn ranks_by_fts_and_falls_back_to_a_substring_when_the_query_has_no_tokens() {    let s = home_harness();    seed_project(&s);    let fts = call_tool(&s.h, &s.secret, "recall", json!({ "q": "release" }));    assert_eq!(slugs_of(&fts), vec!["no-prod-release"]);    let fallback = call_tool(&s.h, &s.secret, "recall", json!({ "q": "*" }));    assert_eq!(slugs_of(&fallback), vec!["wildcard"]);    // Searching inside a project keeps the project's scope in both lanes.    let scoped = call_tool(        &s.h,        &s.secret,        "recall",        json!({ "q": "litestream", "project": "tinmen" }),    );    assert_eq!(scoped["memories"], json!([]));    let scoped_fallback = call_tool(        &s.h,        &s.secret,        "recall",        json!({ "q": "*", "project": "tinmen" }),    );    assert_eq!(scoped_fallback["memories"], json!([]));}#[test]fn filters_by_status_and_project_there_is_no_category_left_to_filter_on() {    let s = home_harness();    seed_project(&s);    let archived = call_tool(&s.h, &s.secret, "recall", json!({ "status": "archived" }));    assert_eq!(slugs_of(&archived), vec!["gone"]);    assert_eq!(archived["memories"][0]["projects"], json!([]));    let all_statuses = call_tool(        &s.h,        &s.secret,        "recall",        json!({ "status": "all", "q": "litestream" }),    );    let mut slugs = slugs_of(&all_statuses);    slugs.sort();    assert_eq!(slugs, vec!["gone", "litestream-restore"]);    let on_project = call_tool(&s.h, &s.secret, "recall", json!({ "project": "tinmen" }));    assert_eq!(slugs_of(&on_project), vec!["on-tinmen"]);    assert_eq!(        on_project["memories"][0]["projects"],        json!([{ "slug": "tinmen", "pinned": false, "position": 1000 }])    );    // No project: EVERY active entry, newest first, wherever it briefs.    let everything = call_tool(&s.h, &s.secret, "recall", json!({}));    let slugs = slugs_of(&everything);    assert!(slugs.iter().any(|slug| slug == "on-tinmen"));    assert!(slugs.iter().any(|slug| slug == "reads-no-prs"));    assert!(!slugs.iter().any(|slug| slug == "gone"));}#[test]fn refuses_an_unknown_project_by_naming_the_known_ones() {    let s = home_harness();    seed_project(&s);    let answer = call_tool_raw(&s.h, &s.secret, "recall", json!({ "project": "nope" }));    assert!(answer.is_error);    assert!(answer.text.contains("tinmen"), "{}", answer.text);}// ── memory_reorder ──────────────────────────────────────────────────────────fn seed_abc(s: &Seeded) {    let mut ops = Vec::new();    ops.extend(entry(&s.h, "a", json!({}), Home::at(1000.0)).1);    ops.extend(entry(&s.h, "b", json!({}), Home::at(2000.0)).1);    ops.extend(entry(&s.h, "c", json!({}), Home::at(3000.0)).1);    seed(&s.h, ops);}fn recalled_home(s: &Seeded) -> Vec<String> {    slugs_of(&call_tool(        &s.h,        &s.secret,        "recall",        json!({ "project": HOME_SLUG }),    ))}#[test]fn after_puts_the_entry_between_that_neighbour_and_the_one_that_followed_it() {    let s = home_harness();    seed_abc(&s);    let answer = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "c", "after": "a", "project": HOME_SLUG }),    );    assert!(!answer.is_error, "{}", answer.text);    let result = answer.json();    let position = result["position"].as_f64().expect("a position");    assert!(position > 1000.0 && position < 2000.0, "{position}");    assert_eq!(result["project"], HOME_SLUG);    assert_eq!(recalled_home(&s), vec!["a", "c", "b"]);}#[test]fn before_puts_it_between_that_neighbour_and_the_one_that_preceded_it() {    let s = home_harness();    seed_abc(&s);    let moved = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "a", "before": "c", "project": HOME_SLUG }),    );    assert!(!moved.is_error, "{}", moved.text);    assert_eq!(recalled_home(&s), vec!["b", "a", "c"]);}#[test]fn moves_an_entry_to_the_head_when_neither_neighbour_is_named() {    let s = home_harness();    let mut ops = Vec::new();    ops.extend(entry(&s.h, "a", json!({}), Home::at(1000.0)).1);    ops.extend(entry(&s.h, "b", json!({}), Home::at(2000.0)).1);    seed(&s.h, ops);    let result = call_tool(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "b", "project": HOME_SLUG }),    );    assert!(result["position"].as_f64().expect("a position") < 1000.0);    assert_eq!(recalled_home(&s), vec!["b", "a"]);}#[test]fn moving_an_entry_to_where_it_already_is_leaves_the_order_alone() {    let s = home_harness();    let mut ops = Vec::new();    ops.extend(entry(&s.h, "a", json!({}), Home::at(1000.0)).1);    ops.extend(entry(&s.h, "b", json!({}), Home::at(2000.0)).1);    seed(&s.h, ops);    let moved = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "b", "after": "a", "project": HOME_SLUG }),    );    assert!(!moved.is_error, "{}", moved.text);    assert_eq!(recalled_home(&s), vec!["a", "b"]);}#[test]fn never_crosses_the_pinned_band() {    let s = home_harness();    let mut ops = Vec::new();    ops.extend(entry(&s.h, "pin", json!({}), Home::pinned_at(1000.0)).1);    ops.extend(entry(&s.h, "a", json!({}), Home::at(1000.0)).1);    ops.extend(entry(&s.h, "b", json!({}), Home::at(2000.0)).1);    seed(&s.h, ops);    // The head of the UNPINNED band — an assistant asking to jump a pinned    // entry is asking to pin, which is a different verb.    let moved = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "b", "project": HOME_SLUG }),    );    assert!(!moved.is_error, "{}", moved.text);    assert_eq!(recalled_home(&s), vec!["pin", "b", "a"]);}// One entry, two projects, two arrangements: moving it in one list leaves the// other list exactly as it was.#[test]fn moves_an_entry_within_one_projects_list_leaving_its_seat_in_another_project_alone() {    let s = home_harness();    let mut ops = vec![project_op(&s.h, OTHER, OTHER_SLUG, &[])];    let (a, a_ops) = entry(&s.h, "p-a", json!({}), Home::at(1000.0));    let (b, b_ops) = entry(&s.h, "p-b", json!({}), Home::at(2000.0));    ops.extend(a_ops);    ops.extend(b_ops);    ops.push(link_op(&s.h, OTHER, &a, Home::at(1000.0)));    ops.push(link_op(&s.h, OTHER, &b, Home::at(2000.0)));    seed(&s.h, ops);    let moved = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "p-b", "project": OTHER_SLUG, "before": "p-a" }),    );    assert!(!moved.is_error, "{}", moved.text);    let other = call_tool(&s.h, &s.secret, "recall", json!({ "project": OTHER_SLUG }));    assert_eq!(slugs_of(&other), vec!["p-b", "p-a"]);    assert_eq!(recalled_home(&s), vec!["p-a", "p-b"]);    assert_eq!(link_real(&s.h, "p-b", HOME, "position"), Some(2000.0));}// The band is the project's list, so a neighbour that is not linked there is// "not there" by the same measure a missing slug is.#[test]fn refuses_a_neighbour_from_another_projects_list_moving_nothing() {    let s = home_harness();    let mut ops = vec![project_op(&s.h, OTHER, OTHER_SLUG, &[])];    ops.extend(entry(&s.h, "home-one", json!({}), Home::at(1000.0)).1);    ops.extend(        entry(            &s.h,            "p-a",            json!({}),            Home {                project: Some(OTHER),                position: Some(1000.0),                pinned: false,            },        )        .1,    );    ops.extend(        entry(            &s.h,            "p-b",            json!({}),            Home {                project: Some(OTHER),                position: Some(2000.0),                pinned: false,            },        )        .1,    );    seed(&s.h, ops);    let crossed = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "p-a", "project": OTHER_SLUG, "after": "home-one" }),    );    assert!(crossed.is_error);    assert!(        crossed            .text            .contains("no memory entry with slug \"home-one\" in other's list"),        "{}",        crossed.text    );    // …and the other way round, so neither list can reach into the other.    let back = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "home-one", "after": "p-b", "project": HOME_SLUG }),    );    assert!(back.is_error);    // An entry that is not in the named project at all is refused by name.    let absent = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "home-one", "project": OTHER_SLUG }),    );    assert!(absent.is_error);    assert!(        absent.text.contains("not linked to other"),        "{}",        absent.text    );    assert_eq!(link_real(&s.h, "p-a", OTHER, "position"), Some(1000.0));    assert_eq!(link_real(&s.h, "home-one", HOME, "position"), Some(1000.0));}#[test]fn refuses_a_neighbour_that_is_not_there_rather_than_guessing_a_slot() {    let s = home_harness();    seed(&s.h, entry(&s.h, "a", json!({}), Home::at(1000.0)).1);    let answer = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "a", "after": "ghost", "project": HOME_SLUG }),    );    assert!(answer.is_error);    assert!(        answer.text.contains("no memory entry with slug"),        "{}",        answer.text    );    assert_eq!(link_real(&s.h, "a", HOME, "position"), Some(1000.0));}// An empty string is not a neighbour. A client that sends one alongside a// real neighbour is asking for one neighbour — not two, and not none.#[test]fn reads_an_empty_neighbour_as_absent_rather_than_as_a_second_request() {    let s = home_harness();    let mut ops = Vec::new();    ops.extend(entry(&s.h, "one", json!({}), Home::at(1000.0)).1);    ops.extend(entry(&s.h, "two", json!({}), Home::at(2000.0)).1);    ops.extend(entry(&s.h, "three", json!({}), Home::at(3000.0)).1);    seed(&s.h, ops);    let moved = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "three", "before": "   ", "after": "one", "project": HOME_SLUG }),    );    assert!(!moved.is_error, "{}", moved.text);    assert_eq!(link_real(&s.h, "three", HOME, "position"), Some(1500.0));}#[test]fn refuses_both_neighbours_at_once_that_is_two_different_requests() {    let s = home_harness();    seed_abc(&s);    let answer = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "c", "after": "a", "before": "b", "project": HOME_SLUG }),    );    assert!(answer.is_error);    assert!(        answer.text.contains("before or after, not both"),        "{}",        answer.text    );    assert_eq!(link_real(&s.h, "c", HOME, "position"), Some(3000.0));}// The order is the project's: a move that names no list is refused.#[test]fn refuses_a_move_with_no_project_the_order_is_the_projects() {    let s = home_harness();    let mut ops = Vec::new();    ops.extend(entry(&s.h, "a", json!({}), Home::at(1000.0)).1);    ops.extend(entry(&s.h, "b", json!({}), Home::at(2000.0)).1);    seed(&s.h, ops);    let answer = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "b", "after": "a" }),    );    assert!(answer.is_error);    assert!(        answer.text.contains("project is required"),        "{}",        answer.text    );    assert_eq!(link_real(&s.h, "b", HOME, "position"), Some(2000.0));}#[test]fn refuses_when_the_gap_is_exhausted_the_server_never_renumbers() {    let s = home_harness();    // Two adjacent doubles: there is no value strictly between them.    let mut ops = Vec::new();    ops.extend(entry(&s.h, "a", json!({}), Home::at(1.0)).1);    ops.extend(entry(&s.h, "b", json!({}), Home::at(1.0000000000000002)).1);    ops.extend(entry(&s.h, "c", json!({}), Home::at(5000.0)).1);    seed(&s.h, ops);    let answer = call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "c", "after": "a", "project": HOME_SLUG }),    );    assert!(answer.is_error);    assert!(        answer.text.contains("no room between them"),        "{}",        answer.text    );    assert_eq!(recalled_home(&s), vec!["a", "b", "c"]);}// Arranging a list leaves the sentence alone.#[test]fn reorder_leaves_the_sentence_alone() {    let s = home_harness();    let mut ops = Vec::new();    ops.extend(        entry(            &s.h,            "a",            json!({ "origin_kind": "agent", "origin_label": "Claude" }),            Home::at(1000.0),        )        .1,    );    ops.extend(entry(&s.h, "b", json!({}), Home::at(2000.0)).1);    seed(&s.h, ops);    call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "a", "after": "b", "project": HOME_SLUG }),    );    assert_eq!(        memory_text(&s.h, "a", "title").as_deref(),        Some("The a rule")    );}#[test]fn lands_the_move_as_an_op_on_the_link_which_the_phones_pull() {    let s = home_harness();    let mut ops = Vec::new();    ops.extend(entry(&s.h, "a", json!({}), Home::at(1000.0)).1);    ops.extend(entry(&s.h, "b", json!({}), Home::at(2000.0)).1);    seed(&s.h, ops);    call_tool_raw(        &s.h,        &s.secret,        "memory_reorder",        json!({ "slug": "b", "before": "a", "project": HOME_SLUG }),    );    let tables = mcp_op_tables(&s.h);    assert!(tables.iter().any(|table| table == "cotton_project_links"));    // Arranging is not history: the memory row itself is untouched.    assert!(!tables.iter().any(|table| table == "cotton_memories"));}// ── memory_update ───────────────────────────────────────────────────────────#[test]fn corrects_the_sentence_and_the_source() {    let s = home_harness();    seed(        &s.h,        entry(            &s.h,            "a-ruling",            json!({ "title": "Chefs run delivery" }),            Home::at(1000.0),        )        .1,    );    let answer = call_tool_raw(        &s.h,        &s.secret,        "memory_update",        json!({            "slug": "a-ruling",            "title": "I decided chefs run their own delivery",            "source": "session:claude-code:s1",        }),    );    assert!(!answer.is_error, "{}", answer.text);    let result = answer.json();    assert_eq!(result["updated"], json!(true));    assert_eq!(result["slug"], "a-ruling");    assert_eq!(        memory_text(&s.h, "a-ruling", "title").as_deref(),        Some("I decided chefs run their own delivery")    );    assert_eq!(        memory_text(&s.h, "a-ruling", "source").as_deref(),        Some("session:claude-code:s1")    );    // Correcting a sentence never rearranges the owner's list.    assert_eq!(link_real(&s.h, "a-ruling", HOME, "position"), Some(1000.0));    assert_eq!(link_int(&s.h, "a-ruling", HOME, "pinned"), Some(0));    // And the flag it used to carry is refused by name rather than dropped.    let dated = call_tool_raw(        &s.h,        &s.secret,        "memory_update",        json!({ "slug": "a-ruling", "dated": true }),    );    assert!(dated.is_error);    assert_eq!(dated.text, RetiredField::Dated.say(&[]));}// Pinning is the LINK's: one entry, pinned in one project and not in another.#[test]fn pins_and_unpins_the_entry_in_one_project() {    let s = home_harness();    let mut ops = vec![project_op(&s.h, OTHER, OTHER_SLUG, &[])];    let (a, a_ops) = entry(&s.h, "a", json!({}), Home::at(1000.0));    ops.extend(a_ops);    ops.push(link_op(&s.h, OTHER, &a, Home::at(1000.0)));    seed(&s.h, ops);    let pinned = call_tool_raw(        &s.h,        &s.secret,        "memory_update",        json!({ "slug": "a", "project": OTHER_SLUG, "pinned": true }),    );    assert!(!pinned.is_error, "{}", pinned.text);    assert_eq!(link_int(&s.h, "a", OTHER, "pinned"), Some(1));    assert_eq!(link_int(&s.h, "a", HOME, "pinned"), Some(0));    let unpinned = call_tool_raw(        &s.h,        &s.secret,        "memory_update",        json!({ "slug": "a", "project": OTHER_SLUG, "pinned": false }),    );    assert!(!unpinned.is_error, "{}", unpinned.text);    assert_eq!(link_int(&s.h, "a", OTHER, "pinned"), Some(0));    // No project: no list to pin it in.    let nowhere = call_tool_raw(        &s.h,        &s.secret,        "memory_update",        json!({ "slug": "a", "pinned": true }),    );    assert!(nowhere.is_error);    assert!(        nowhere.text.contains("pinned is per project"),        "{}",        nowhere.text    );    // A project the entry is not in: the refusal says how to put it there.    seed(&s.h, vec![project_op(&s.h, "p-third", "third", &[])]);    let absent = call_tool_raw(        &s.h,        &s.secret,        "memory_update",        json!({ "slug": "a", "project": "third", "pinned": true }),    );    assert!(absent.is_error);    assert!(absent.text.contains("link_to_project"), "{}", absent.text);}#[test]fn memory_update_refuses_a_body_with_the_teaching_text_touching_nothing() {    let s = home_harness();    seed(        &s.h,        entry(            &s.h,            "a-ruling",            json!({ "title": "Chefs run delivery" }),            Home::default(),        )        .1,    );    let before = memory_text(&s.h, "a-ruling", "updated_at");    let body = call_tool_raw(        &s.h,        &s.secret,        "memory_update",        json!({ "slug": "a-ruling", "body": "Depth." }),    );    assert!(body.is_error);    assert_eq!(body.text, RetiredField::Body.say(&[]));    assert_eq!(memory_text(&s.h, "a-ruling", "updated_at"), before);    assert_eq!(        memory_text(&s.h, "a-ruling", "title").as_deref(),        Some("Chefs run delivery")    );}// A call carrying a retired category is refused with the teaching line// whether or not it carries anything else — "send at least one field to// change" is a true sentence that answers the wrong question.#[test]fn refuses_a_call_carrying_a_retired_category_alone_or_alongside_a_real_edit() {    let s = home_harness();    seed(        &s.h,        entry(            &s.h,            "a-ruling",            json!({ "title": "Code is free" }),            Home::default(),        )        .1,    );    let before = memory_text(&s.h, "a-ruling", "updated_at");    for args in [        json!({ "layer": "belief" }),        json!({ "kind": "about_me" }),        json!({ "kind": "business", "title": "Code is free and unlimited" }),    ] {        let mut merged = Map::new();        merged.insert("slug".to_string(), Value::from("a-ruling"));        for (key, value) in args.as_object().expect("an object") {            merged.insert(key.clone(), value.clone());        }        let answer = call_tool_raw(&s.h, &s.secret, "memory_update", Value::Object(merged));        assert!(answer.is_error, "{args} was not refused");        assert_eq!(answer.text, RetiredField::Taxonomy.say(&[]));    }    assert_eq!(memory_text(&s.h, "a-ruling", "updated_at"), before);    assert_eq!(        memory_text(&s.h, "a-ruling", "title").as_deref(),        Some("Code is free")    );}// ── brief — the project's, not the world's ──────────────────────────────────#[test]fn renders_the_projects_entries_as_one_list_in_the_owners_order() {    let s = home_harness();    let mut ops = Vec::new();    ops.extend(entry(&s.h, "second", json!({}), Home::at(2000.0)).1);    ops.extend(entry(&s.h, "first", json!({}), Home::at(1000.0)).1);    seed(&s.h, ops);    let result = call_tool(&s.h, &s.secret, "brief", json!({ "project": HOME_SLUG }));    let markdown = result["briefing"].as_str().unwrap_or_default();    assert!(markdown.contains("## Project: Home"), "{markdown}");    assert!(!markdown.contains("## Standing"));    assert!(!markdown.contains("## Working with"));    // Present first: a missing entry would make the ordering line pass for    // the wrong reason.    for slug in ["[first]", "[second]"] {        assert!(markdown.contains(slug), "{markdown}");    }    assert!(        markdown.find("[first]") < markdown.find("[second]"),        "{markdown}"    );    assert_eq!(result["projects"], json!([HOME_SLUG]));}/// RULE: A project briefs its memory as one list in the owner's own order, with no sub-heading that sorts some entries into a separate temporal group.#[test]fn briefs_a_projects_entries_as_one_list_in_the_owners_order() {    let s = home_harness();    let mut ops = Vec::new();    ops.extend(entry(&s.h, "durable", json!({}), Home::at(1000.0)).1);    ops.extend(entry(&s.h, "current", json!({}), Home::at(2000.0)).1);    seed(&s.h, ops);    let result = call_tool(&s.h, &s.secret, "brief", json!({ "project": HOME_SLUG }));    let markdown = result["briefing"].as_str().unwrap_or_default();    for piece in ["[current]", "[durable]"] {        assert!(markdown.contains(piece), "{markdown}");    }    for absent in ["Now:", "## Now", "dated"] {        assert!(!markdown.contains(absent), "{absent}: {markdown}");    }    // The owner's own position decides the order, and nothing else.    assert!(        markdown.find("[durable]") < markdown.find("[current]"),        "{markdown}"    );}// ── brief — the procedures the project keeps ────────────────────────────────/// One note, and the link that files it under a project.////// A PROCEDURE IS A NOTE WHOSE FIRST LINE NAMES ITS TRIGGER — there is no/// marker column and none is wanted: the trigger sentence is what the brief/// prints, so a note that carries none has nothing to advertise.fn note_ops(h: &Harness, id: &str, title: &str, body: &str, project: &str) -> Vec<Value> {    let note = op(        "cotton_notes",        id,        json!({            "id": id,            "workspace_id": h.workspace_id,            "kind": "note",            "title": title,            "body": body,            "author_kind": "user",            "author_label": Value::Null,            "created_at": AT,            "updated_at": AT,        }),    );    let link_id = project_link_id(project, "note", id);    let link = op(        "cotton_project_links",        &link_id,        json!({            "id": link_id,            "workspace_id": h.workspace_id,            "project_id": project,            "record_kind": "note",            "record_id": id,            "note": "procedure",            "applied_by": "user",            "pinned": false,            "position": Value::Null,            "created_at": AT,            "updated_at": AT,        }),    );    vec![note, link]}/// The two procedures brief, the plain note does not, and the section says how/// to read one.#[test]fn briefs_the_projects_procedure_notes_and_leaves_a_plain_note_out() {    let s = home_harness();    let mut ops = entry(&s.h, "standing", json!({}), Home::at(1000.0)).1;    ops.extend(note_ops(        &s.h,        "note-ship",        "Ship a PR",        "Trigger: a PR is open and needs merging.\n\nRun the script.",        HOME,    ));    ops.extend(note_ops(        &s.h,        "note-run",        "Run the app",        "trigger: the app needs running on the simulator\n\nBuild it.",        HOME,    ));    ops.extend(note_ops(        &s.h,        "note-plain",        "A meeting I wrote down",        "We talked about the logo. Trigger: not on the first line.",        HOME,    ));    seed(&s.h, ops);    let result = call_tool(&s.h, &s.secret, "brief", json!({ "project": HOME_SLUG }));    let markdown = result["briefing"].as_str().unwrap_or_default();    assert!(markdown.contains("## Procedures"), "{markdown}");    for piece in [        "- the app needs running on the simulator · note note-run",        "- a PR is open and needs merging. · note note-ship",        "get_record { kind: \"note\", id }",    ] {        assert!(markdown.contains(piece), "{markdown}");    }    assert!(!markdown.contains("A meeting I wrote down"), "{markdown}");    // Exactly two lines in the section, and nothing of the bodies.    assert_eq!(markdown.matches(" · note ").count(), 2, "{markdown}");    assert!(!markdown.contains("Run the script."), "{markdown}");}/// Title order, so the section reads the same way every time whatever order the/// store returned the links in.#[test]fn sorts_the_procedures_by_title() {    let s = home_harness();    let mut ops = entry(&s.h, "standing", json!({}), Home::at(1000.0)).1;    for (id, title) in [        ("note-z", "Zip it"),        ("note-a", "Ask a question"),        ("note-m", "Make a thing"),    ] {        ops.extend(note_ops(            &s.h,            id,            title,            &format!("Trigger: somebody wants to {title}."),            HOME,        ));    }    seed(&s.h, ops);    let markdown = call_tool(&s.h, &s.secret, "brief", json!({ "project": HOME_SLUG }))["briefing"]        .as_str()        .unwrap_or_default()        .to_string();    let at = |title: &str| markdown.find(title).unwrap_or(usize::MAX);    assert!(at("Ask a question") < at("Make a thing"), "{markdown}");    assert!(at("Make a thing") < at("Zip it"), "{markdown}");}/// A procedure belongs to the project it is linked to, like every other member:/// another project's procedure never briefs here.#[test]fn leaves_another_projects_procedures_out() {    let s = home_harness();    let mut ops = vec![project_op(&s.h, OTHER, OTHER_SLUG, &[])];    ops.extend(entry(&s.h, "standing", json!({}), Home::at(1000.0)).1);    ops.extend(note_ops(        &s.h,        "note-elsewhere",        "Somebody elses procedure",        "Trigger: it belongs to the other project.",        OTHER,    ));    seed(&s.h, ops);    let markdown = call_tool(&s.h, &s.secret, "brief", json!({ "project": HOME_SLUG }))["briefing"]        .as_str()        .unwrap_or_default()        .to_string();    assert!(!markdown.contains("## Procedures"), "{markdown}");}/// An archived note is off the project, so it is off the brief — the same rule/// every other archived record follows.#[test]fn leaves_an_archived_procedure_out() {    let s = home_harness();    let mut ops = entry(&s.h, "standing", json!({}), Home::at(1000.0)).1;    ops.extend(note_ops(        &s.h,        "note-gone",        "A retired procedure",        "Trigger: nobody runs this any more.",        HOME,    ));    ops.push(op(        "cotton_notes",        "note-gone",        json!({ "archived_at": "2026-09-01T00:00:00.000Z" }),    ));    seed(&s.h, ops);    let markdown = call_tool(&s.h, &s.secret, "brief", json!({ "project": HOME_SLUG }))["briefing"]        .as_str()        .unwrap_or_default()        .to_string();    assert!(!markdown.contains("## Procedures"), "{markdown}");}/// Over budget the procedure lines give way and the owner's own words stay./// Twenty procedures against the smallest budget the tool accepts (400), so/// the section alone is over it. The imported tools' instructions ride after/// the compiled memory and are priced first, so the kit's (a dozen tools/// since the media packages joined it) are given on top: the compiler is/// what gets the 400.#[test]fn drops_the_procedure_lines_before_a_memory_line_when_over_budget() {    let s = home_harness();    let mut ops = entry(&s.h, "standing", json!({}), Home::at(1000.0)).1;    for n in 0..20 {        ops.extend(note_ops(            &s.h,            &format!("note-{n:02}"),            &format!("Procedure number {n:02} with a name long enough to cost tokens"),            &format!(                "Trigger: the {n:02}th kind of task, described at the length a real trigger runs to."            ),            HOME,        ));    }    seed(&s.h, ops);    let budget = 400;    let result = call_tool(        &s.h,        &s.secret,        "brief",        json!({ "project": HOME_SLUG, "budgetTokens": budget }),    );    let markdown = result["briefing"].as_str().unwrap_or_default().to_string();    // The owner's own words are still there, and some procedure lines are not.    assert!(markdown.contains("[standing]"), "{markdown}");    assert!(        markdown.matches(" · note ").count() < 20,        "nothing was trimmed: {markdown}"    );    assert!(markdown.contains("procedure line"), "{markdown}");    assert!(        !markdown.contains("Budget trimmed 0 procedure"),        "{markdown}"    );}/// RULE: The whole brief fits its budget — nothing rides after the compiled memory — and at the owner's own budget every procedure keeps its note id./// On 12 Oct the cotton brief was 4,585 tokens against 4,000: a 640-token/// project summary rode outside the budget and 19 procedure ids were shed.#[test]fn the_whole_brief_fits_its_budget_and_keeps_every_procedure_id() {    let s = home_harness();    let mut ops = entry(&s.h, "standing", json!({}), Home::at(1000.0)).1;    ops.push(op(        "cotton_memory_projects",        HOME,        json!({ "description": "A long project summary that has grown over the weeks. ".repeat(48) }),    ));    for n in 0..39 {        ops.extend(note_ops(            &s.h,            &format!("{n:08}-0000-4000-8000-000000000000"),            &format!("Procedure number {n:02} with a plain name"),            &format!(                "Trigger: the {n:02}th kind of task — described at the length a real trigger runs to, with its examples and its exceptions spelled out. A second sentence adds the edge cases.\n\nThe body."            ),            HOME,        ));    }    seed(&s.h, ops);    let result = call_tool(&s.h, &s.secret, "brief", json!({ "project": HOME_SLUG }));    let markdown = result["briefing"].as_str().unwrap_or_default().to_string();    let budget = cotton_core::constants::MEMORY_BRIEFING_BUDGET_TOKENS as i64;    assert!(result["tokensEstimate"].as_i64().unwrap_or(i64::MAX) <= budget, "{markdown}");    assert_eq!(result["overBudget"], json!(false), "{markdown}");    assert!(!markdown.contains("## Project context"), "{markdown}");    assert!(markdown.contains("[standing]"), "{markdown}");    for n in 0..39 {        assert!(markdown.contains(&format!("note {n:08}-0000-4000-8000-000000000000")), "{n}: {markdown}");    }    assert!(!markdown.contains("A second sentence"), "{markdown}");}// A repo bound to no project gets told how to find one, never an empty// briefing and never somebody else's project.#[test]fn tells_a_session_in_an_unbound_repo_how_to_find_its_project() {    let s = home_harness();    seed(&s.h, entry(&s.h, "home-only", json!({}), Home::default()).1);    let answer = call_tool_raw(        &s.h,        &s.secret,        "brief",        json!({ "repoUrl": "git@github.com:example/unbound.git" }),    );    assert!(!answer.is_error, "{}", answer.text);    let result = answer.json();    let markdown = result["briefing"].as_str().unwrap_or_default();    assert!(        markdown.contains("No project is bound to this repo"),        "{markdown}"    );    assert!(markdown.contains("`list_projects`"), "{markdown}");    assert!(!markdown.contains("[home-only]"), "{markdown}");    assert_eq!(result["projects"], json!([]));    // No repo and no project says the same thing.    let bare = call_tool(&s.h, &s.secret, "brief", json!({}));    assert!(bare["briefing"]        .as_str()        .unwrap_or_default()        .contains("No project is bound to this repo"));}#[test]fn renders_the_project_recent_sessions_and_the_counts() {    let s = home_harness();    let mut ops = vec![project_op(        &s.h,        "p-tinmen",        "tinmen",        &["github.com/example/tinmen"],    )];    ops.extend(        entry(            &s.h,            "reads-no-prs",            json!({ "title": "Reads no PRs" }),            Home::default(),        )        .1,    );    ops.extend(        entry(            &s.h,            "fresh",            json!({                "title": "A fresh agent fact",                "origin_kind": "agent",                "origin_label": "Claude",            }),            Home {                project: Some("p-tinmen"),                position: Some(500.0),                pinned: false,            },        )        .1,    );    ops.extend(        entry(            &s.h,            "on-tinmen",            json!({ "title": "Chefs run their own delivery" }),            Home {                project: Some("p-tinmen"),                position: Some(1000.0),                pinned: false,            },        )        .1,    );    ops.extend(        entry(            &s.h,            "for-now",            json!({                "title": "The server deploys this week — valid until 1 Aug",            }),            Home {                project: Some("p-tinmen"),                position: Some(2000.0),                pinned: false,            },        )        .1,    );    seed(&s.h, ops);    call_tool(        &s.h,        &s.secret,        "log_session",        json!({            "tool": "claude-code",            "externalId": "s1",            "machine": "studio",            "lastActiveAt": "2026-08-24T01:00:00.000Z",            "repoUrl": "https://github.com/example/tinmen",            "summary": "Shipped the server.",        }),    );    let answer = call_tool_raw(        &s.h,        &s.secret,        "brief",        json!({ "repoUrl": "git@github.com:example/tinmen.git", "machine": "studio" }),    );    assert!(!answer.is_error, "{}", answer.text);    let result = answer.json();    let briefing = result["briefing"].as_str().unwrap_or_default();    assert!(briefing.contains("## Project: Tinmen"), "{briefing}");    assert!(        briefing.contains("- [fresh] A fresh agent fact\n"),        "{briefing}"    );    assert!(        briefing.contains("- [on-tinmen] Chefs run their own delivery"),        "{briefing}"    );    assert!(!briefing.contains("Now:"), "{briefing}");    // Another project's entry is not this session's business.    assert!(!briefing.contains("[reads-no-prs]"), "{briefing}");    assert!(!briefing.contains("## Standing"), "{briefing}");    // The brief is memory and nothing else: the logged session, the counts of    // what waits and the project's context are read by their own tools.    assert!(!briefing.contains("## Recent sessions"), "{briefing}");    assert!(!briefing.contains("Shipped the server."), "{briefing}");    assert!(!briefing.contains("## Needs attention"), "{briefing}");    assert!(!briefing.contains("## Project context"), "{briefing}");    // An entry whose expiry is in its own sentence is an ordinary line.    assert!(        briefing.contains("- [for-now] The server deploys this week — valid until 1 Aug"),        "{briefing}"    );    assert!(!briefing.contains("dated entry"), "{briefing}");    assert_eq!(result["projects"], json!(["tinmen"]));}#[test]fn never_briefs_an_entry_above_private() {    let s = home_harness();    let mut ops = Vec::new();    ops.extend(        entry(            &s.h,            "private-law",            json!({ "title": "Self-serve is law" }),            Home::default(),        )        .1,    );    // Writable today via the app's memory input; the standing rule says    // nothing above private renders in any briefing until the sharing design    // lands.    ops.extend(        entry(            &s.h,            "shared-note",            json!({ "title": "Shared with the whole team", "visibility": "shared" }),            Home::default(),        )        .1,    );    ops.extend(        entry(            &s.h,            "public-bio",            json!({ "title": "A public bio sentence", "visibility": "public" }),            Home {                pinned: true,                ..Home::default()            },        )        .1,    );    // Nor may a shared row inflate the attention line.    ops.extend(        entry(            &s.h,            "shared-fresh",            json!({                "title": "A shared agent fact",                "visibility": "shared",                "origin_kind": "agent",                "origin_label": "Claude",            }),            Home::default(),        )        .1,    );    seed(&s.h, ops);    let answer = call_tool_raw(&s.h, &s.secret, "brief", json!({ "project": HOME_SLUG }));    assert!(!answer.is_error, "{}", answer.text);    let briefing = answer.json();    let briefing = briefing["briefing"].as_str().unwrap_or_default();    assert!(        briefing.contains("- [private-law] Self-serve is law"),        "{briefing}"    );    assert!(        !briefing.contains("Shared with the whole team"),        "{briefing}"    );    assert!(!briefing.contains("A public bio sentence"), "{briefing}");    assert!(!briefing.contains("A shared agent fact"), "{briefing}");    assert!(!briefing.contains("Needs attention"), "{briefing}");}// ── technical entries go to the repository ──────────────────────────────────/// RULE: remember refuses a sentence that cites a pull request, a file path or a workflow name, writes nothing, and names the repository as the place for it.#[test]fn remember_refuses_a_technical_entry_and_names_the_repository() {    let s = home_harness();    for sentence in [        "The pre-push hook is a real gate for store changes. (Agent decision, 27 Sep 2026, #1035.)",        "The home remote is resolved by scripts/lib/host-remote.sh on every Mac.",        "verify-main.yml walks the phone app after each merge.",    ] {        let answer = remember(&s, json!({ "title": sentence }));        assert!(answer.is_error, "{sentence} was not refused");        assert!(answer.text.contains("repository"), "{}", answer.text);    }    assert_eq!(memory_count(&s.h), 0);}/// RULE: the owner's own sentence that merely mentions pull requests as a practice is still memory.#[test]fn remember_keeps_the_owners_words_about_pull_requests() {    let s = home_harness();    let answer = remember(        &s,        json!({ "title": "Write PR descriptions for the AI reviewer and the audit trail, not for me." }),    );    assert!(!answer.is_error, "{}", answer.text);    assert_eq!(memory_count(&s.h), 1);}/// RULE: a machine-scoped entry — a fact true of one computer — may name a path on that computer, but still never a pull request.#[test]fn a_machine_fact_may_name_a_path_but_not_a_pull_request() {    let s = home_harness();    let path = remember(        &s,        json!({ "title": "The CI credential sits at ~/.cotton-credentials/cotton/code-credential here.", "machine": "ci-box" }),    );    assert!(!path.is_error, "{}", path.text);    let pull = remember(        &s,        json!({ "title": "This box took the leased build slots in #1052.", "machine": "ci-box" }),    );    assert!(pull.is_error);    assert!(pull.text.contains("repository"));}/// RULE: memory_update refuses to rewrite an entry into a technical one.#[test]fn memory_update_refuses_a_technical_rewrite() {    let s = home_harness();    let added = remember(        &s,        json!({ "title": "Autonomy is the default working mode." }),    )    .json();    let answer = call_tool_raw(        &s.h,        &s.secret,        "memory_update",        json!({ "slug": slug_of(&added), "title": "Autonomy is the default working mode (#1001)." }),    );    assert!(answer.is_error);    assert!(answer.text.contains("repository"));}// ── the briefing limit is enforced at write time ────────────────────────────/// A long sentence of the owner's, distinct enough from its neighbours that/// the reconcile does not stop it, and plain enough that nothing reads it as a/// secret.fn long_sentence(i: usize) -> String {    let words = [        "gardens",        "rivers",        "mountains",        "letters",        "kitchens",        "harbours",        "orchards",        "lanterns",        "meadows",        "bridges",        "violins",        "tides",        "forests",        "markets",    ];    let mut out = format!("Standing view number {i}:");    let mut n = i;    while out.len() < 260 {        out.push(' ');        out.push_str(words[n % words.len()]);        n = n / 3 + 7 * (out.len() % 5) + i;    }    out.push('.');    out}/// RULE: an entry that would take a project's briefing over its 4,000-token limit is refused with the numbers, and nothing is written — a memory line is never left out silently.#[test]fn an_entry_that_would_overflow_the_briefing_is_refused_with_the_numbers() {    let s = home_harness();    let mut refused = None;    for i in 0..80 {        let before = memory_count(&s.h);        let answer = remember(            &s,            json!({ "title": long_sentence(i), "decision": { "action": "add" } }),        );        if answer.is_error {            assert_eq!(memory_count(&s.h), before, "a refused entry was written");            refused = Some(answer.text);            break;        }    }    let refusal = refused.expect("the briefing never reached its limit");    assert!(refusal.contains("over its 4000-token limit"), "{refusal}");    assert!(refusal.contains("memory_archive"), "{refusal}");    // Bringing it back under always passes: a correction that shortens an    // entry makes the briefing no longer.    let first = one(        &s.h,        "SELECT slug FROM cotton_memories ORDER BY created_at LIMIT 1",        Vec::new(),    )    .and_then(|row| row.text("slug").map(str::to_string))    .expect("an entry");    let shorter = call_tool_raw(        &s.h,        &s.secret,        "memory_update",        json!({ "slug": first, "title": "A shorter standing view." }),    );    assert!(!shorter.is_error, "{}", shorter.text);}// RULE: Current memory APIs refuse retired statuses and legacy body reads.#[test]fn retired_memory_arguments_are_refused() {    let s = home_harness();    for args in [json!({ "status": "proposed" }), json!({ "withBody": true })] {        assert!(call_tool_raw(&s.h, &s.secret, "recall", args).is_error);    }}// RULE: Recall reads only the current sentence, never the retired body payload.#[test]fn recall_does_not_read_retired_body_text() {    let s = home_harness();    seed(&s.h, entry(&s.h, "sentence-only", json!({        "title": "Current sentence", "body": "legacybodyonly *"    }), Home::default()).1);    for query in ["legacybodyonly", "*"] {        let answer = call_tool(&s.h, &s.secret, "recall", json!({ "q": query }));        assert!(answer["memories"].as_array().unwrap().is_empty());    }}