Cotton code
277 lines · 8.9 KB · RustRaw
//! A thought carries pictures (schema v36) — `update_thought` files the list,//! `get_thought`, `list_thoughts` and `get_record` answer it.//!//! The mechanism is the note's (`handlers::attachments`), so what this file//! holds is the THOUGHT half of the contract: the list is diffed onto a//! thought, a picture the database does not hold refuses the whole call, `[]`//! takes every picture off, a removed picture answers `missing`, and the note's//! own rows are never touched by a thought's list. Every row is synthetic and//! every value invented ([nothing-real-ever-goes-in-cotton-s-public-tree]).mod support;use std::sync::atomic::{AtomicU64, Ordering};use cotton_store::schema::ddl::SCHEMA_VERSION;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::{synthetic_uuid, Harness};use support::mcp::{call_tool, call_tool_raw, mint_token_ref};const AT: &str = "2026-09-27T10:00:00.000Z";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!("01K{: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,    })}/// A 64-character content hash, distinct per letter.fn media_hash(letter: char) -> String {    std::iter::repeat_n(letter, 64).collect()}struct Attached {    h: Harness,    secret: String,    thought: String,    photo: String,    document: String,}fn harness() -> Attached {    let h = Harness::new();    let secret = mint_token_ref(&h, &["read", "write"], "Claude");    let thought = synthetic_uuid("thought-with-a-screenshot");    let photo = format!("photo:{}", media_hash('a'));    let document = synthetic_uuid("attach-document");    // The capture row straight into the file — the app writes these, never MCP.    h.run(        "INSERT INTO cotton_inbox_items \           (id, workspace_id, raw_text, captured_at, route_status, created_at, updated_at) \         VALUES (?, ?, ?, ?, 'pending', ?, ?)",        &[            SqlValue::Text(thought.clone()),            SqlValue::Text(h.workspace_id.clone()),            SqlValue::Text("the list jumps when I scroll the day".to_string()),            SqlValue::Text(AT.to_string()),            SqlValue::Text(AT.to_string()),            SqlValue::Text(AT.to_string()),        ],    );    h.seed(&[        op(            "cotton_photos",            &photo,            json!({                "workspace_id": h.workspace_id,                "key": format!("{}/photos/{}.png", h.workspace_id, media_hash('a')),                "sha256": media_hash('a'),                "content_type": "image/png",                "size_bytes": 4096,                "width": 1179,                "height": 2556,                "taken_at": AT,                "caption": "screenshot of the day",                "created_at": AT,                "updated_at": AT,            }),        ),        op(            "cotton_documents",            &document,            json!({                "workspace_id": h.workspace_id,                "title": "Crash log",                "original_name": "crash.txt",                "mime": "text/plain",                "byte_size": 512,                "sha256": media_hash('c'),                "storage_path": format!("{}/documents/crash.txt", h.workspace_id),                "status": "ready",                "status_changed_at": AT,                "facts": {},                "source": "app",                "created_at": AT,                "updated_at": AT,            }),        ),    ]);    Attached {        h,        secret,        thought,        photo,        document,    }}fn attachments_of(a: &Attached) -> Vec<Value> {    let thought = call_tool(&a.h, &a.secret, "get_thought", json!({ "id": a.thought }));    thought["attachments"].as_array().expect("attachments").clone()}#[test]fn a_thought_with_no_pictures_answers_an_empty_list_not_an_absent_key() {    let a = harness();    let thought = call_tool(&a.h, &a.secret, "get_thought", json!({ "id": a.thought }));    assert_eq!(thought["attachments"], json!([]));}#[test]fn a_picture_the_database_does_not_hold_refuses_the_whole_list() {    let a = harness();    let ghost = format!("photo:{}", media_hash('f'));    let refused = call_tool_raw(        &a.h,        &a.secret,        "update_thought",        json!({            "id": a.thought,            "attachments": [                { "kind": "photo", "id": a.photo },                { "kind": "photo", "id": ghost },            ],        }),    );    assert!(refused.is_error);    assert!(        refused.text.contains("a thought names a picture that already exists"),        "{}",        refused.text    );    // Whole, not half: the good picture did not land either.    assert_eq!(attachments_of(&a), Vec::<Value>::new());}#[test]fn the_refusals_say_thought_not_note() {    let a = harness();    let refused = call_tool_raw(        &a.h,        &a.secret,        "update_thought",        json!({ "id": a.thought, "attachments": null }),    );    assert!(refused.is_error);    assert!(        refused.text.contains("off the thought"),        "the sentence is about the record it was said to: {}",        refused.text    );}#[test]fn an_empty_list_takes_every_picture_off_and_the_rest_of_the_row_stands() {    let a = harness();    call_tool(        &a.h,        &a.secret,        "update_thought",        json!({ "id": a.thought, "attachments": [{ "kind": "photo", "id": a.photo }] }),    );    assert_eq!(attachments_of(&a).len(), 1);    let cleared = call_tool(        &a.h,        &a.secret,        "update_thought",        json!({ "id": a.thought, "attachments": [] }),    );    assert_eq!(cleared["attachments"], json!([]));    assert_eq!(cleared["text"], "the list jumps when I scroll the day");    assert_eq!(cleared["standing"], "open");}/// RULE: A removed picture waits in the bin and its attachment reads as missing in its place; only the bin's erase takes the attachment row with it.#[test]fn a_removed_picture_takes_its_attachment_row_with_it() {    let a = harness();    call_tool(        &a.h,        &a.secret,        "update_thought",        json!({ "id": a.thought, "attachments": [{ "kind": "photo", "id": a.photo }] }),    );    // `remove_photo` moves the picture to the bin: the attachment keeps its    // place and reads as missing, so a restore brings it back where it was.    call_tool(&a.h, &a.secret, "remove_photo", json!({ "id": a.photo }));    let waiting = attachments_of(&a);    assert_eq!(waiting.len(), 1, "a binned picture's attachment lost its place");    assert_eq!(waiting[0]["missing"], json!(true), "a binned picture still reads as attached");    // The bin's erase is an ERASE (slice 5a-ii): an attachment row is OWNED_BY    // its picture (`cotton_store::erase::OWNED_BY`), so it leaves with it.    let erased = support::mcp::call_tool_as_owner(&a.h, "device:phone", "empty_bin", json!({ "kind": "photo" }));    assert!(!erased.is_error, "{}", erased.text);    assert_eq!(attachments_of(&a), Vec::<Value>::new(), "the attachment went with the picture");    // And the list the phone re-sends after that names what is still there.    call_tool(        &a.h,        &a.secret,        "update_thought",        json!({            "id": a.thought,            "attachments": [{ "kind": "document", "id": a.document }],        }),    );    assert_eq!(attachments_of(&a).len(), 1);}#[test]fn a_thoughts_list_never_touches_a_notes_rows() {    let a = harness();    let note = call_tool(        &a.h,        &a.secret,        "create_note",        json!({            "body": "the same screenshot, on a note",            "attachments": [{ "kind": "photo", "id": a.photo }],        }),    );    let note_id = note["id"].as_str().expect("a note id").to_string();    call_tool(        &a.h,        &a.secret,        "update_thought",        json!({ "id": a.thought, "attachments": [{ "kind": "photo", "id": a.photo }] }),    );    call_tool(        &a.h,        &a.secret,        "update_thought",        json!({ "id": a.thought, "attachments": [] }),    );    let record = call_tool(        &a.h,        &a.secret,        "get_record",        json!({ "kind": "note", "id": note_id }),    );    assert_eq!(        record["attachments"].as_array().map(Vec::len),        Some(1),        "two owners, two tables — a thought letting go of a picture is not a note doing so"    );}#[test]fn update_thought_still_refuses_a_call_that_changes_nothing() {    let a = harness();    let refused = call_tool_raw(        &a.h,        &a.secret,        "update_thought",        json!({ "id": a.thought }),    );    assert!(refused.is_error);    assert!(refused.text.contains("attachments"), "{}", refused.text);}