Cotton code
162 lines · 8.1 KB · RustRaw
//! Todos lost labels (architect ruling, 5 Oct 2026). The serving Mac's start//! (`cotton_tools::todo_labels`) takes back the todo groups the old label//! move made from the night pass's title-derived labels, makes none, and//! clears the labels; the todo verbs refuse a label.//!//! Every title and name is invented.mod support;use std::sync::Arc;use chrono::{DateTime, Duration, Utc};use cotton_tools::definitions::{SEED_JOB, SEED_LABEL};use cotton_tools::mcp::dispatch::{Ctx, ToolServices};use cotton_tools::todo_labels::{take_back_label_groups, LabelGroups};use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::Harness;use support::mcp::{call_tool, call_tool_raw, mint_token};fn now(h: &Harness) -> DateTime<Utc> {    cotton_tools::clock::Clock::now(&h.clock)}/// One start's run, committed the way the server's start commits it.fn run_start(h: &Harness, at: DateTime<Utc>) -> LabelGroups {    let services = ToolServices::none();    let audit = |_tool: &str, _summary: &str| {};    h.with(|db| {        let mut ctx = Ctx::for_worker(            db,            &h.file,            &h.owner_id,            cotton_tools::mcp::writer::job(SEED_JOB),            SEED_LABEL,            at,            Arc::clone(&h.random),            &services,            &audit,        );        let taken = take_back_label_groups(&mut ctx).expect("the step runs");        ctx.commit().expect("commits");        taken    })}/// A todo carrying `label` as the night pass left it: its own title's words.fn todo(h: &Harness, secret: &str, title: &str, label: Option<&str>) -> String {    let made = call_tool(h, secret, "create_record", json!({ "table": "todo", "data": { "title": title } }));    let id = made["record"]["id"].as_str().unwrap_or_else(|| panic!("no todo: {made}")).to_string();    if let Some(label) = label {        h.run(            "UPDATE cotton_todos SET label = ? WHERE id = ?",            &[SqlValue::Text(label.to_string()), SqlValue::Text(id.clone())],        );    }    id}/// A group row as the old label move wrote it: by the seed job, holding the/// todos, with no change row.fn made_by_the_old_move(h: &Harness, name: &str, todos: &[&str]) -> String {    let id = format!("old-move-{}", name.to_lowercase().replace(' ', "-"));    h.run(        "INSERT INTO cotton_groups (id, workspace_id, table_id, name, record_byline, created_at, updated_at) \         VALUES (?, ?, 'todo', ?, ?, '2026-10-06T00:00:00.000Z', '2026-10-06T00:00:00.000Z')",        &[            SqlValue::Text(id.clone()),            SqlValue::Text(h.workspace_id.clone()),            SqlValue::Text(name.to_string()),            SqlValue::Text(SEED_LABEL.into()),        ],    );    for (place, todo) in todos.iter().enumerate() {        h.run(            "INSERT INTO cotton_group_members (id, workspace_id, group_id, record_id, place, created_at, updated_at) \             VALUES (?, ?, ?, ?, ?, '2026-10-06T00:00:00.000Z', '2026-10-06T00:00:00.000Z')",            &[                SqlValue::Text(cotton_store::protocol::derived_id::group_member_id(&id, todo)),                SqlValue::Text(h.workspace_id.clone()),                SqlValue::Text(id.clone()),                SqlValue::Text(todo.to_string()),                SqlValue::Real((place + 1) as f64),            ],        );    }    id}fn live_groups(h: &Harness) -> Vec<String> {    h.all(        "SELECT name FROM cotton_groups WHERE deleted_at IS NULL ORDER BY name",        &[],    )    .into_iter()    .map(|row| row["name"].as_str().unwrap_or_default().to_string())    .collect()}/// RULE: A server start makes no group, and it bins every todo group the old label move made from the night pass's title-derived labels (by the seed job, no create change, untouched since) — 273 such groups sat in the owner's personal database on 11 Oct 2026, one per todo, and a Mac on an older build re-makes them — while a group a person made, one the old move added todos to, and one a person changed since all stay; every label is cleared, no todo re-dated, and a second start writes nothing.#[test]fn a_start_takes_back_the_groups_the_label_move_made_and_makes_none() {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let call = todo(&h, &secret, "Call the invented aunt", Some("Call the invented aunt"));    let call_again = todo(&h, &secret, "Call the invented aunt", Some("Call the invented aunt"));    let litter = todo(&h, &secret, "Buy the invented litter", Some("Buy invented litter"));    let bench = todo(&h, &secret, "Fix the invented bench", Some("Fix bench"));    let bare = todo(&h, &secret, "Post the invented letter", None);    let workshop = call_tool(&h, &secret, "create_group", json!({ "table": "todo", "name": "Workshop", "records": [bare] }));    let workshop = workshop["group"]["id"].as_str().unwrap().to_string();    // The old move found "workshop" already there and added to it, signing it.    h.run(        "UPDATE cotton_groups SET record_byline = ? WHERE id = ?",        &[SqlValue::Text(SEED_LABEL.into()), SqlValue::Text(workshop.clone())],    );    made_by_the_old_move(&h, "Call the invented aunt", &[&call, &call_again]);    made_by_the_old_move(&h, "Buy invented litter", &[&litter]);    let renamed = made_by_the_old_move(&h, "Fix bench", &[&bench]);    call_tool(&h, &secret, "update_group", json!({ "id": renamed, "name": "Bench work" }));    let before: Vec<Value> =        h.all("SELECT updated_at FROM cotton_todos ORDER BY id", &[]).into_iter().map(|row| row["updated_at"].clone()).collect();    let taken = run_start(&h, now(&h) + Duration::minutes(1));    assert_eq!(taken, LabelGroups { groups_binned: 2, labels_cleared: 4 });    assert_eq!(live_groups(&h), vec!["Bench work".to_string(), "Workshop".to_string()], "only what a person made or changed stays");    assert_eq!(        h.count("SELECT COUNT(*) FROM cotton_groups WHERE deleted_at IS NOT NULL", &[]),        2,        "the old move's groups are binned, not erased"    );    assert_eq!(h.count("SELECT COUNT(*) FROM cotton_todos WHERE label IS NOT NULL", &[]), 0, "every label is cleared");    let after: Vec<Value> =        h.all("SELECT updated_at FROM cotton_todos ORDER BY id", &[]).into_iter().map(|row| row["updated_at"].clone()).collect();    assert_eq!(after, before, "clearing a label does not re-date the todo");    let records = || h.all("SELECT id, name, record_byline, deleted_at, updated_at FROM cotton_groups ORDER BY id", &[]);    let (rows_then, writes_then) = (records(), h.count("SELECT COUNT(*) FROM _writes", &[]));    let again = run_start(&h, now(&h) + Duration::minutes(2));    assert_eq!(again, LabelGroups::default());    assert!(!again.wrote());    assert_eq!(records(), rows_then, "a second start changes nothing");    assert_eq!(h.count("SELECT COUNT(*) FROM _writes", &[]), writes_then, "a second start writes nothing");}/// RULE: A todo verb that still names label is refused in plain words pointing at groups, never quietly dropped — a caller who meant to sort the todo would otherwise think it had.#[test]fn a_todo_verb_naming_a_label_is_refused_and_pointed_at_groups() {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let made = call_tool_raw(&h, &secret, "create_todo", json!({ "title": "Buy invented string", "label": "Errands" }));    assert!(made.is_error, "{}", made.text);    assert!(made.text.contains("no label any more") && made.text.contains("create_group"), "{}", made.text);    let todo = call_tool(&h, &secret, "create_todo", json!({ "title": "Buy invented string" }));    let id = todo["todo"]["id"].as_str().or(todo["id"].as_str()).unwrap_or_else(|| panic!("no id: {todo}")).to_string();    let changed = call_tool_raw(&h, &secret, "update_todo", json!({ "id": id, "label": "Errands" }));    assert!(changed.is_error && changed.text.contains("no label any more"), "{}", changed.text);    let listed = call_tool(&h, &secret, "list_todos", json!({}));    assert!(listed["todos"].as_array().unwrap().iter().all(|todo| todo.get("label").is_none()), "{listed}");}