Cotton code
470 lines · 18.5 KB · RustRaw
//! How this reader projects ONE ROW of each linkable kind into a compact MCP//! answer: what to call it, which response group it lands in, and what else its//! row carries.//!//! THE TOTALITY IS THE `match`. The TypeScript builds `KIND_SOURCES` by//! reducing `PROJECT_LINK_KINDS` over a hand-written `KIND_PROJECTIONS` and//! throws at module load for a missing entry — a runtime backstop, because//! TypeScript cannot prove a record built by iteration is total. Here//! [`kind_source`] is an exhaustive `match` on [`ProjectLinkKind`], so a kind//! added without a projection fails the BUILD. That is the same discipline one//! step earlier, and the reason it matters is unchanged: a kind missing from a//! read registry is SILENTLY INVISIBLE — `get_project` would answer nothing for//! it and count nothing, for ever, with no error anywhere.//!//! WHERE the rows live is NOT decided here: `table` and `where` come from//! [`super::engine_shim::project_kind_table`], the one fact this reader and the//! app's project page genuinely share (R46). Everything else stays split on//! purpose — the app needs a title and a recency for a row on a page, this//! needs columns, a response group and extras.use cotton_core::constants::ProjectLinkKind;use serde_json::{Map, Value};use crate::mcp::handlers::common::{flag, text};use crate::mcp::handlers::projects::engine_shim::{    project_kind_table, ProjectKindFilter,};/// One kind's whole projection.pub struct ProjectKindSource {    /// Derived from core's registry — never typed twice.    pub table: &'static str,    /// The row's discriminator, where the kind shares its table with another    /// (note / journal), or the null test that keeps replies out (feedback).    pub where_clause: Option<ProjectKindFilter>,    pub columns: &'static [&'static str],    /// The response group this kind lands in — one per kind unless two kinds    /// really are one thing to a reader. Journal is NOT one of those.    pub group: &'static str,}/// Where each kind's rows live and what a reader selects of them.pub const fn kind_source(kind: ProjectLinkKind) -> ProjectKindSource {    use ProjectLinkKind::*;    let (columns, group): (&'static [&'static str], &'static str) = match kind {        // Schema v34: a memory is a member like any other. Archived entries are        // excluded by core's `where`; the group is re-sorted into the link's        // arrangement after the loop, because a project's memory reads in the        // owner's order, not by arrival.        Memory => (            &[                "id",                "slug",                "title",                "status",                "updated_at",            ],            "memory",        ),        // A call the phone recorded (v36). The HANDLE is the title, and this        // reader mints no name for one it cannot attribute.        Call => (            &[                "id",                "handle",                "provider",                "direction",                "outcome",                "started_at",                "duration_s",                "person_id",            ],            "calls",        ),        Thread => (            &[                "id",                "kind",                "title",                "contact_id",                "last_message_at",                "archived",            ],            "threads",        ),        EmailThread => (&["id", "subject", "last_at", "email_count"], "emailThreads"),        Person => (            &["id", "full_name", "org", "role_title", "archived_at"],            "people",        ),        Note => (            &[                "id",                "title",                "kind",                "journal_date",                "body",                "updated_at",                "archived_at",            ],            "notes",        ),        // `project_id` is read but NOT projected out: it is what the mirror        // guards compare against, not a fact this group's rows carry.        //        // ITS OWN GROUP, not "notes". Folding it in double-reported a project's        // own pages — every one arriving in `journal.recent` AND, through its        // mirror link row, in `linked.notes` — so a project with seven pages        // and no notes read as having seven notes.        Journal => (            &[                "id",                "title",                "kind",                "journal_date",                "project_id",                "body",                "updated_at",                "archived_at",            ],            "journal",        ),        Todo => (&["id", "title", "status", "due_at"], "todos"),        Event => (&["id", "title", "starts_at"], "events"),        Document => (            &[                "id",                "title",                "original_name",                "doc_type",                "document_date",                "status",                "issuer",            ],            "documents",        ),        Transaction => (&["id", "description", "occurred_on"], "transactions"),        // Two projections rather than one shared "media" reader, for the reason        // the two kinds are two kinds: a video answers with how long it runs,        // and a photo never can.        Photo => (            &[                "id",                "caption",                "summary",                "taken_at",                "size_bytes",                "review_note",            ],            "photos",        ),        Album => (            &["id", "kind", "state", "title", "starts_at", "ends_at"],            "albums",        ),        // A password (v6 of the Rust ladder). The PLAIN columns and the hint,        // exactly what `list_secrets` answers — `value_enc` is not in this list        // and must never join it.        Secret => (            &[                "id",                "kind",                "name",                "site",                "username",                "service",                "hint",                "updated_at",            ],            "secrets",        ),        Video => (            &[                "id",                "caption",                "summary",                "taken_at",                "size_bytes",                "duration_ms",                "review_note",            ],            "videos",        ),        // A repository (v19). The KEY is `owner/name`, which is how a person        // names one; `sync_state` rides along because "no access token" is an        // answer a reader has to be able to print.        Repository => (            &[                "id",                "key",                "host",                "name",                "default_branch",                "description",                "open_pulls",                "open_issues",                "sync_state",                "held",                "origin",                // `created_at` is not printed — it is what `ordering_moment`                // orders a repository by, because `updated_at` is the worker's                // last pass and not a moment anything happened.                "created_at",                "updated_at",            ],            // `repositories` as the PUBLIC JSON key, plural like every other            // group's; the SECTION key is `code` (`ProjectSectionKey::Code`),            // which is the word in the route. The app's own table pairs the            // two, and `ProjectFacts.swift` states it: `key: "code"`,            // `group: "repositories"`.            "repositories",        ),    };    let table = project_kind_table(kind);    ProjectKindSource {        table: table.table,        where_clause: table.where_clause,        columns,        group,    }}/// What one row is CALLED in a project's list.pub fn title_of(kind: ProjectLinkKind, row: &Map<String, Value>) -> String {    use ProjectLinkKind::*;    let or = |value: Option<String>, fallback: &str| value.unwrap_or_else(|| fallback.to_string());    match kind {        Memory => or(text(row, "title"), ""),        Call => or(text(row, "title").or_else(||text(row,"handle")), "(unknown number)"),        Thread => or(text(row, "title"), "(direct chat)"),        EmailThread => or(text(row, "subject"), "(no subject)"),        Person => or(text(row, "full_name"), "(unnamed)"),        Note | Journal => or(            text(row, "title").or_else(|| text(row, "journal_date")),            "(untitled)",        ),        Todo | Event => or(text(row, "title"), "(untitled)"),        Document => or(            text(row, "title").or_else(|| text(row, "original_name")),            "(untitled)",        ),        Transaction => or(text(row, "description"), "(no description)"),        // The person's own caption first and the describe worker's description        // second, which is the order the picture itself was named in.        Photo => or(            text(row, "caption").or_else(|| text(row, "summary")),            "A photo",        ),        Album => or(text(row, "title"), "An album"),        Secret => or(text(row, "name"), "(unnamed)"),        // The KEY, `owner/name` — the bare name would collide across hosts,        // and it is what a person and `pnpm forge` both say.        Repository => or(text(row, "key"), "(unnamed repository)"),        Video => or(            text(row, "caption").or_else(|| text(row, "summary")),            "A video",        ),    }}fn put_text(out: &mut Map<String, Value>, key: &str, value: Option<String>) {    if let Some(value) = value {        out.insert(key.to_string(), Value::from(value));    }}fn carry(out: &mut Map<String, Value>, key: &str, row: &Map<String, Value>, column: &str) {    out.insert(        key.to_string(),        row.get(column).cloned().unwrap_or(Value::Null),    );}/// What else a row of this kind carries into its group's line./// How much of a page's opening a preview carries.////// A slip clamps to three lines and the phone's line is about forty-five/// characters, so this is comfortably more than is ever drawn — the cap exists/// so a project of fifty pages does not carry fifty whole page bodies over the/// boundary, not to decide the layout. The app strips the Markdown; the raw/// opening is what travels, because stripping here would make this the second/// implementation of a rule the editor already owns.const PREVIEW_CHARS: usize = 240;/// The opening of a page's body, or `None` when there is nothing to open with.////// A blank body answers `None` rather than an empty string: a slip that gets/// `Some("")` draws an empty prose line and a gap under the title, which reads/// as a page whose first line is missing rather than as a page with no body./// Cut by CHARACTERS, never bytes — a body opening with an emoji or any/// non-Latin script would panic a byte slice on a boundary.#[must_use]pub fn preview_of(body: Option<&str>) -> Option<String> {    let trimmed = body?.trim();    if trimmed.is_empty() {        return None;    }    Some(trimmed.chars().take(PREVIEW_CHARS).collect())}pub fn extras_of(kind: ProjectLinkKind, row: &Map<String, Value>) -> Map<String, Value> {    use ProjectLinkKind::*;    let mut out = Map::new();    match kind {        Memory => {            put_text(&mut out, "slug", text(row, "slug"));        }        Call => {            carry(&mut out, "provider", row, "provider");            carry(&mut out, "direction", row, "direction");            carry(&mut out, "outcome", row, "outcome");            carry(&mut out, "startedAt", row, "started_at");            carry(&mut out, "durationS", row, "duration_s");            put_text(&mut out, "personId", text(row, "person_id"));        }        Thread => {            carry(&mut out, "kind", row, "kind");            put_text(&mut out, "lastMessageAt", text(row, "last_message_at"));            if flag(row, "archived") {                out.insert("archived".to_string(), Value::Bool(true));            }        }        EmailThread => {            put_text(&mut out, "lastAt", text(row, "last_at"));            carry(&mut out, "emailCount", row, "email_count");        }        Person => {            put_text(&mut out, "org", text(row, "org"));            put_text(&mut out, "roleTitle", text(row, "role_title"));            if text(row, "archived_at").is_some() {                out.insert("archived".to_string(), Value::Bool(true));            }        }        Note => {            put_text(&mut out, "updatedAt", text(row, "updated_at"));            put_text(&mut out, "preview", preview_of(text(row, "body").as_deref()));            if text(row, "archived_at").is_some() {                out.insert("archived".to_string(), Value::Bool(true));            }        }        Journal => {            out.insert("journal".to_string(), Value::Bool(true));            put_text(&mut out, "preview", preview_of(text(row, "body").as_deref()));            if text(row, "archived_at").is_some() {                out.insert("archived".to_string(), Value::Bool(true));            }        }        Todo => {            carry(&mut out, "status", row, "status");            put_text(&mut out, "dueAt", text(row, "due_at"));        }        Event => put_text(&mut out, "startsAt", text(row, "starts_at")),        Document => {            carry(&mut out, "docType", row, "doc_type");            carry(&mut out, "status", row, "status");            put_text(&mut out, "documentDate", text(row, "document_date"));            put_text(&mut out, "issuer", text(row, "issuer"));        }        Transaction => put_text(&mut out, "occurredOn", text(row, "occurred_on")),        Photo => {            carry(&mut out, "takenAt", row, "taken_at");            carry(&mut out, "sizeBytes", row, "size_bytes");            // Flagged for the owner to look at again. Carried here because a            // project page is exactly where somebody notices a screenshot they            // are done with — and nothing about the note deletes anything.            put_text(&mut out, "reviewNote", text(row, "review_note"));        }        Album => {            carry(&mut out, "kind", row, "kind");            carry(&mut out, "state", row, "state");            carry(&mut out, "startsAt", row, "starts_at");            carry(&mut out, "endsAt", row, "ends_at");        }        // Never `value_enc`, and never anything derived from it: a project's        // line carries what a person reads to RECOGNISE the row, and `hint` is        // the four characters that do that without being the secret.        Secret => {            carry(&mut out, "kind", row, "kind");            put_text(&mut out, "site", text(row, "site"));            put_text(&mut out, "username", text(row, "username"));            put_text(&mut out, "service", text(row, "service"));            put_text(&mut out, "hint", text(row, "hint"));        }        Video => {            carry(&mut out, "takenAt", row, "taken_at");            carry(&mut out, "sizeBytes", row, "size_bytes");            if row.get("duration_ms").and_then(Value::as_i64).unwrap_or(0) != 0 {                carry(&mut out, "durationMs", row, "duration_ms");            }            put_text(&mut out, "reviewNote", text(row, "review_note"));        }        // A repository (v19). The three facts a reader needs before deciding        // whether to ask for more: what is open on it, whether Cotton holds        // its bytes, and the worker's state in words — a repository with no        // access token answers nothing else and must say so.        Repository => {            put_text(&mut out, "host", text(row, "host"));            put_text(&mut out, "defaultBranch", text(row, "default_branch"));            put_text(&mut out, "description", text(row, "description"));            carry(&mut out, "openPulls", row, "open_pulls");            carry(&mut out, "openIssues", row, "open_issues");            carry(&mut out, "syncState", row, "sync_state");            if flag(row, "held") {                out.insert("held".to_string(), Value::Bool(true));            }            put_text(&mut out, "origin", text(row, "origin"));        }    }    out}#[cfg(test)]mod preview_tests {    use super::{preview_of, PREVIEW_CHARS};    /// A page with nothing in it has no opening, and must not answer one: an    /// empty string draws a blank prose line under the title, which reads as a    /// page whose first line went missing.    #[test]    fn nothing_to_open_with_answers_nothing() {        assert_eq!(preview_of(None), None);        assert_eq!(preview_of(Some("")), None);        assert_eq!(preview_of(Some("   \n\t  ")), None);    }    /// The ordinary case: the opening travels as it was written, Markdown and    /// all — the app strips it, because the editor already owns that rule and a    /// second implementation here would eventually disagree with it.    #[test]    fn a_short_body_travels_whole_and_keeps_its_markdown() {        assert_eq!(            preview_of(Some("  # Monday\n\nRan the numbers again.  ")),            Some("# Monday\n\nRan the numbers again.".to_string()),            "trimmed at the ends, untouched in the middle"        );    }    /// The cap is on CHARACTERS, and it is a cap rather than a layout: a slip    /// clamps to three lines long before this.    #[test]    fn a_long_body_is_cut_to_the_cap() {        let body = "a".repeat(PREVIEW_CHARS * 3);        let cut = preview_of(Some(&body)).expect("a body this long has an opening");        assert_eq!(cut.chars().count(), PREVIEW_CHARS);        assert_eq!(            preview_of(Some(&"b".repeat(PREVIEW_CHARS)))                .expect("exactly the cap")                .chars()                .count(),            PREVIEW_CHARS,            "exactly the cap is not cut"        );    }    /// CHARACTERS and never bytes. A body opening in Devanagari or with an    /// emoji is three or four bytes per character, so a byte slice would land    /// mid-character and panic — on the owner's own journal, in a read every    /// project page makes.    #[test]    fn a_body_that_is_not_latin_is_cut_on_a_character_and_never_panics() {        let body = "मैंने आज ".repeat(200);        let cut = preview_of(Some(&body)).expect("an opening");        assert_eq!(cut.chars().count(), PREVIEW_CHARS);        assert!(body.starts_with(&cut), "the cut is a prefix of the body");        let emoji = "🙂".repeat(PREVIEW_CHARS + 10);        let cut = preview_of(Some(&emoji)).expect("an opening");        assert_eq!(cut.chars().count(), PREVIEW_CHARS);    }}