Cotton code
209 lines · 13.3 KB · RustRaw
//! The project tools, end to end over `dispatch::call_tool` against a real//! store and a fake `ToolServices` rather than the `/v1/mcp` endpoint: a//! project is created, records link to it many-to-many with per-link notes,//! `get_project` gathers the whole working context in one call, and the//! briefing carries the working-context coda. Writes land in the file as sync//! ops so the phone would see every one of them.mod support;use rusqlite::types::Value as SqlValue;use serde_json::json;use support::harness::Harness;use support::mcp::{call_tool, call_tool_raw, mint_token};fn writer_harness() -> (Harness, String) {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    (h, secret)}fn run(h: &Harness, sql: &str, params: Vec<SqlValue>) {    h.with(|db| db.run(sql, &params))        .expect("the statement runs");}fn count(h: &Harness, sql: &str, params: Vec<SqlValue>) -> i64 {    h.with(|db| db.get(sql, &params))        .expect("the read runs")        .and_then(|row| row.int("n"))        .unwrap_or_default()}// ════════════════════════════════════════════════════════════════════════════// create_project// ════════════════════════════════════════════════════════════════════════════// ════════════════════════════════════════════════════════════════════════════// link_to_project// ════════════════════════════════════════════════════════════════════════════// ════════════════════════════════════════════════════════════════════════════// get_project// ════════════════════════════════════════════════════════════════════════════// ── a linked PERSON brings their conversations and calls (§D8) ──────────//// Until schema v38 a person linked to a project contributed nothing but their// name: the thread had to be linked itself, which nobody ever did, so the one// thing a project is actually made of — talking to people — was the one thing// its page did not show. The two derived sections are computed at READ time// and are not link rows, so a person in two projects shows their calls in// both, which is the truth of it.// ════════════════════════════════════════════════════════════════════════════// unlink_from_project// ════════════════════════════════════════════════════════════════════════════// ════════════════════════════════════════════════════════════════════════════// list_projects and update_project// ════════════════════════════════════════════════════════════════════════════// ════════════════════════════════════════════════════════════════════════════// a project's summary carries its provenance// ════════════════════════════════════════════════════════════════════════════//// A project's description IS its summary (R80), so `update_project` is the verb// that writes it — and the stamp it leaves is what lets the project page say// who wrote the paragraph and when (spec §D2). The clock is frozen in every// case that reads a stamp: `update_project` takes its instant from the server's// own `now`, so these would otherwise be wall-clock assertions.#[test]fn refuses_a_description_longer_than_a_summary_may_be_at_birth_too() {    // The cap is the summary's, so it has to hold on the verb that writes the    // first one — `create_project` refuses through the same core validator.    let (h, secret) = writer_harness();    let max = cotton_core::rules::summaries::SUMMARY_MAX_CHARS;    let refused = call_tool_raw(        &h,        &secret,        "create_project",        json!({ "slug": "toolong", "name": "Too long", "description": "a".repeat(max + 1) }),    );    assert!(refused.is_error);    assert!(refused.text.contains(&max.to_string()), "{}", refused.text);    // And no half-made project was left behind.    assert_eq!(        count(            &h,            "SELECT COUNT(*) AS n FROM cotton_memory_projects WHERE slug = ?",            vec![SqlValue::Text("toolong".to_string())]        ),        0    );}// ════════════════════════════════════════════════════════════════════════════// procedures — a note whose first line names its trigger// ════════════════════════════════════════════════════════════════════════════// ════════════════════════════════════════════════════════════════════════════// the briefing's working-context coda// ════════════════════════════════════════════════════════════════════════════// ════════════════════════════════════════════════════════════════════════════// the project journal// ════════════════════════════════════════════════════════════════════════════//// The per-project journal (spec 2026-09-02 §3.1/§3.2). A journal page belongs// to a CONTEXT — `cotton_notes.project_id`, authoritative — and the link row on// a project's own page is a MIRROR of that column. These are the two seams that// could make the mirror lie, plus the read the whole feature exists for.// ════════════════════════════════════════════════════════════════════════════// a project's BRAND KIT (schema v27)// ════════════════════════════════════════════════════════════════════════════//// `update_project({ brand })` writes it, `get_project` and `list_projects` read// it back, and the logo FILES come back as `brandAssets` — the documents linked// to the project whose link note is one of `BRAND_ASSET_ROLES`.//// The two properties this block exists for:////   1. the server refuses exactly what the app refuses, because both ask//      `parse_project_brand` and neither has a rule of its own — a hex the//      phone accepts and the server rejects would be an edit that vanishes on//      sync;//   2. a brand asset is an ORDINARY document with an ordinary link, so//      `link_to_project` needed no change at all: the four role strings are//      just notes, and the assistant that files one uses the tool it already//      has.const BRAND_AT: &str = "2026-09-03T09:00:00.000Z";// ── brandAssets — the logo files ────────────────────────────────────────────// ════════════════════════════════════════════════════════════════════════════// project templates// ════════════════════════════════════════════════════════════════════════════// `POST /v1/projects/from-template` belongs to the ROUTES lane rather than to a// handler group, and `PROJECT_TEMPLATES` is a `const` table nothing can// substitute, so the partial-failure path is exercised through the seam the// seeder already has (`project_templates.rs`: a seed whose tool this build does// not carry lands in `failures` rather than failing to compile). That is why// these two ask the DISPATCH TABLE what is registered instead of hard-coding a// number that goes stale the day the money group lands./// Whether `create_money_account` — a MONEY-group tool the templates seed/// through — is registered on this build.fn money_accounts_ported() -> bool {    cotton_tools::mcp::dispatch::handler_for("create_money_account").is_some()}/// A templated book whose money already has a currency: a template names/// none, so its account takes the book's own (the first account's).fn template_harness() -> (Harness, String) {    let (h, secret) = template_harness_with_no_account();    if money_accounts_ported() {        call_tool(&h, &secret, "create_money_account", json!({ "name": "Everyday", "kind": "bank", "currency": "INR" }));    }    (h, secret)}fn template_harness_with_no_account() -> (Harness, String) {    let (h, secret) = writer_harness();    // Without a zone the recurrence writer files the template and materializes    // nothing — a real state, tested in its own right below, but not the one    // the seeding tests are about.    run(        &h,        "INSERT INTO cotton_news_settings (workspace_id, timezone, created_at, updated_at) \         VALUES (?, 'Asia/Kolkata', ?, ?)",        vec![            SqlValue::Text(h.workspace_id.clone()),            SqlValue::Text(BRAND_AT.to_string()),            SqlValue::Text(BRAND_AT.to_string()),        ],    );    (h, secret)}#[test]fn refuses_an_unknown_template_before_it_writes_anything() {    let (h, secret) = template_harness();    let refused = call_tool_raw(        &h,        &secret,        "create_project",        json!({ "slug": "driving", "name": "Driving", "template": "astronaut" }),    );    assert!(refused.is_error);    assert!(refused.text.contains("cab-driver"), "{}", refused.text);    let projects = call_tool(&h, &secret, "list_projects", json!({}));    assert!(!projects.to_string().contains("driving"));}// ════════════════════════════════════════════════════════════════════════════// get_project, the feedback section — what was FILED, and only that// ════════════════════════════════════════════════════════════════════════════// ════════════════════════════════════════════════════════════════════════════// link_to_project, kind memory — the pin, the last unlink, the way back// ════════════════════════════════════════════════════════════════════════════// ════════════════════════════════════════════════════════════════════════════// the page's sections, and the owner's order of them (schema 42)// ════════════════════════════════════════════════════════════════════════════