Cotton code
313 lines · 10.6 KB · RustRaw
//! The work app's own verbs: a session moved or renamed, and the generic edge.//!//! Called the way the app really calls one — `Ctx::phone`, through//! `dispatch::call_tool` — so what is under test is the answer the screen//! receives rather than a handler's return value. Moving a session moves its//! turns with it.//!//! Every fixture is synthetic ([nothing-real-ever-goes-in-cotton-s-public-tree]).mod support;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::{synthetic_uuid, Harness};use support::mcp::call_tool_as_owner;/// The device id the owner's app writes under.const DEVICE: &str = "device:00000000000000000000000000";fn call(h: &Harness, name: &str, args: Value) -> support::mcp::ToolAnswer {    call_tool_as_owner(h, DEVICE, name, args)}// ── sessions ────────────────────────────────────────────────────────────────fn a_session(h: &Harness, external: &str) -> String {    let id = synthetic_uuid(&format!("session-{external}"));    h.run(        "INSERT INTO cotton_sessions (id, workspace_id, tool, external_id, machine, started_at, \         last_active_at, created_at, updated_at) \         VALUES (?, ?, 'claude-code', ?, 'a-machine', '2026-09-01T09:00:00.000Z', \                 '2026-09-01T10:00:00.000Z', '2026-09-01T09:00:00.000Z', '2026-09-01T09:00:00.000Z')",        &[            SqlValue::Text(id.clone()),            SqlValue::Text(h.workspace_id.clone()),            SqlValue::Text(external.to_string()),        ],    );    id}fn a_turn(h: &Harness, session: &str, seq: i64) {    h.run(        "INSERT INTO cotton_prompts (id, workspace_id, session_id, seq, ts, role, text, \         created_at, updated_at) \         VALUES (?, ?, ?, ?, '2026-09-01T09:00:00.000Z', 'user', 'A turn nobody typed', \                 '2026-09-01T09:00:00.000Z', '2026-09-01T09:00:00.000Z')",        &[            SqlValue::Text(synthetic_uuid(&format!("prompt-{session}-{seq}"))),            SqlValue::Text(h.workspace_id.clone()),            SqlValue::Text(session.to_string()),            SqlValue::Integer(seq),        ],    );}#[test]fn moving_a_session_moves_its_turns_with_it() {    // THE RULE THIS CASE EXISTS FOR. A turn carries its own `project_id` so    // the project's reads do not join through the session; a move that left    // them behind would file the session in one place and the work it did in    // another, and the project page would be right about neither.    let h = Harness::new();    let project = synthetic_uuid("project");    h.run(        "INSERT INTO cotton_memory_projects (id, workspace_id, slug, name, status, created_at, updated_at) \         VALUES (?, ?, 'example', 'Example project', 'active', '2026-09-01T00:00:00.000Z', \                 '2026-09-01T00:00:00.000Z')",        &[            SqlValue::Text(project.clone()),            SqlValue::Text(h.workspace_id.clone()),        ],    );    // TWO SESSIONS, and the point of the second one is that a handler moving    // every turn in the file would pass over a fixture holding only the first.    let session = a_session(&h, "external-one");    let bystander = a_session(&h, "external-two");    for seq in 0..2 {        a_turn(&h, &session, seq);    }    a_turn(&h, &bystander, 0);    let answer = call(        &h,        "move_session",        json!({ "id": session, "projectId": project }),    )    .json();    assert_eq!(answer["turnsMoved"], json!(2));    assert_eq!(        h.count(            "SELECT COUNT(*) AS n FROM cotton_prompts WHERE project_id = ?",            &[SqlValue::Text(project.clone())],        ),        2,        "its own turns, and only its own"    );    assert_eq!(        h.count(            "SELECT COUNT(*) AS n FROM cotton_prompts WHERE session_id = ? AND project_id IS NULL",            &[SqlValue::Text(bystander.clone())],        ),        1,        "the other session's turn stays where it was"    );    // And out again — null is an instruction, not an absence.    call(        &h,        "move_session",        json!({ "id": session.clone(), "projectId": Value::Null }),    )    .json();    assert_eq!(        h.count(            "SELECT COUNT(*) AS n FROM cotton_prompts WHERE session_id = ? AND project_id IS NULL",            &[SqlValue::Text(session)],        ),        2    );}#[test]fn a_projects_conversation_is_never_moved() {    let h = Harness::new();    let session = a_session(&h, "external-conversation");    h.run(        "UPDATE cotton_sessions SET kind = 'conversation' WHERE id = ?",        &[SqlValue::Text(session.clone())],    );    let answer = call(        &h,        "move_session",        json!({ "id": session, "projectId": Value::Null }),    );    assert!(answer.is_error, "{}", answer.text);    assert!(answer.text.contains("conversation"), "{}", answer.text);}#[test]fn a_session_cannot_be_filed_under_a_project_this_database_does_not_have() {    let h = Harness::new();    let session = a_session(&h, "external-three");    let answer = call(        &h,        "move_session",        json!({ "id": session, "projectId": synthetic_uuid("nobody") }),    );    assert!(answer.is_error, "{}", answer.text);}#[test]fn the_owner_renames_a_session_and_the_name_is_what_the_row_says() {    let h = Harness::new();    let session = a_session(&h, "external-rename");    let answer = call(        &h,        "rename_session",        json!({ "id": session.clone(), "title": "  The sessions\n page,   whole " }),    )    .json();    // Runs of spaces and a line break are one space: a title is one line.    assert_eq!(answer["title"], json!("The sessions page, whole"));    assert_eq!(        h.count(            "SELECT COUNT(*) AS n FROM cotton_sessions WHERE id = ? AND title = 'The sessions page, whole'",            &[SqlValue::Text(session.clone())],        ),        1    );    // Renaming it to what it is already called changes nothing and succeeds.    let again = call(        &h,        "rename_session",        json!({ "id": session, "title": "The sessions page, whole" }),    );    assert!(!again.is_error, "{}", again.text);}#[test]fn a_rename_says_what_it_needs_rather_than_writing_nothing() {    let h = Harness::new();    let session = a_session(&h, "external-rename-two");    for (args, why) in [        (json!({ "id": session.clone(), "title": "   " }), "a blank title"),        (json!({ "id": session.clone() }), "no title"),        (            json!({ "id": session.clone(), "title": "x".repeat(141) }),            "a title past the column's 140",        ),        (            json!({ "id": synthetic_uuid("nobody"), "title": "A name" }),            "a session this database does not have",        ),    ] {        let answer = call(&h, "rename_session", args);        assert!(answer.is_error, "{why}: {}", answer.text);    }}// ── the generic edge ────────────────────────────────────────────────────────#[test]fn saying_the_same_edge_twice_is_saying_one_fact_once() {    // THE RULE THIS CASE EXISTS FOR. The row's id is DERIVED from the four    // columns the table's UNIQUE index already keys on, so every writer on every    // device converges on ONE row and a re-link after an unlink is that row    // returning rather than a sibling. And an edge already stated is handed back    // AS IT STANDS, keeping its original `created_at`: the fact has existed    // since the first time somebody said it. The callers that say the same thing    // twice are ordinary — the pending-link drain runs on mount AND on every    // inbox fold, and two of those overlap.    let h = Harness::new();    let note = synthetic_uuid("note");    let document = synthetic_uuid("document");    let first = call(        &h,        "create_link",        json!({            "fromKind": "note",            "fromId": note,            "toKind": "document",            "toId": document,        }),    )    .json();    assert_eq!(first["fromKind"], json!("note"));    assert_eq!(first["toKind"], json!("document"));    h.clock.advance(chrono::Duration::minutes(5));    let again = call(        &h,        "create_link",        json!({            "fromKind": "note",            "fromId": note,            "toKind": "document",            "toId": document,        }),    )    .json();    assert_eq!(again["id"], first["id"]);    assert_eq!(        again["createdAt"], first["createdAt"],        "the fact has existed since the first time somebody said it"    );    assert_eq!(h.count("SELECT COUNT(*) AS n FROM cotton_links", &[]), 1);    // DIRECTION MATTERS: an edge from a note to a document is not the edge back,    // and the derived id says so.    let back = call(        &h,        "create_link",        json!({            "fromKind": "document",            "fromId": document,            "toKind": "note",            "toId": note,        }),    )    .json();    assert_ne!(back["id"], first["id"]);    assert_eq!(h.count("SELECT COUNT(*) AS n FROM cotton_links", &[]), 2);}#[test]fn a_kind_the_file_does_not_admit_is_refused_by_name() {    let h = Harness::new();    let answer = call(        &h,        "create_link",        json!({            "fromKind": "note",            "fromId": synthetic_uuid("note"),            "toKind": "screenplay",            "toId": synthetic_uuid("screenplay"),        }),    );    assert!(answer.is_error, "{}", answer.text);    assert!(        answer.text.contains("document"),        "the refusal names what it does take: {}",        answer.text    );    // A missing end is refused too, rather than written as an edge to nothing.    let answer = call(        &h,        "create_link",        json!({ "fromKind": "note", "fromId": synthetic_uuid("note"), "toKind": "todo" }),    );    assert!(answer.is_error, "{}", answer.text);}#[test]fn a_photos_edge_is_not_refused_for_having_an_id_that_is_not_a_uuid() {    // `photo` and `video` records are keyed `photo:<sha256>`, so a uuid gate on    // the id would refuse the two kinds v31 added to this very table.    let h = Harness::new();    let answer = call(        &h,        "create_link",        json!({            "fromKind": "photo",            "fromId": "photo:0000000000000000000000000000000000000000000000000000000000000001",            "toKind": "person",            "toId": synthetic_uuid("person"),        }),    );    assert!(!answer.is_error, "{}", answer.text);    assert_eq!(h.count("SELECT COUNT(*) AS n FROM cotton_links", &[]), 1);}