Cotton code
905 lines · 39.2 KB · RustRaw
//! Settings tables whose rows are supporting records rather than record kinds.//!//! These views are deliberately read through the generic records verbs: an//! assistant and the app therefore receive the same rows.  The repository//! settings below are stored locally, but their page columns differ from the//! storage names (`checks` is JSON in the store, for example), so sending them//! through `builtin` would silently expose the wrong shape.use cotton_core::definitions::TableDefinition;use cotton_core::records::{holds, matches_query, Data, WhereClause};use rusqlite::types::Value as SqlValue;use serde_json::Value;use super::{Page, Stored};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::Valid;use crate::mcp::protocol::ToolFailure;/// Settings tables this build answers from supporting storage.  Tables whose/// facts come from a serving host stay in their host engine; they must never/// fall back to an empty local replica view.pub const TABLES: &[&str] = &[    "project_feedback",    "project_item",    "briefing",    "record_version",    "voice_word",    "repo_label",    "repo_rule",];pub fn handles(definition: &TableDefinition) -> bool {    definition.has_engine() && TABLES.contains(&definition.rows_table())}pub(super) fn read_one(    ctx: &Ctx<'_>,    definition: &TableDefinition,    id: &str,) -> Valid<Option<Stored>> {    Ok(read(ctx, definition, Some(id))?        .into_iter()        .find(|record| record.id == id))}pub(super) fn list(    ctx: &Ctx<'_>,    definition: &TableDefinition,    project: Option<&str>,    query: Option<&str>,    clauses: &[WhereClause],    offset: i64,    limit: i64,) -> Valid<Page> {    let zone = crate::mcp::handlers::common::where_zone(ctx)?;    if project.is_some() {        return Err(ToolFailure::new(format!(            "{} do not belong to projects",            definition.plural        )));    }    // History is paged in SQL: a database holds as many versions as edits,    // and building every one before the page made a ten-minute list on a    // large database (owner, 15 Oct 2026: "everything should load instantly").    if definition.id == "record_version" && query.is_none() {        if let Some(page) = version_page(ctx, clauses, offset, limit)? {            return Ok(page);        }    }    let rows: Vec<_> = read(ctx, definition, None)?        .into_iter()        .filter(|record| {            query.is_none_or(|words| matches_query(definition, &record.data, words))                && clauses.iter().all(|clause| holds(&record.data, clause, &zone))        })        .collect();    let total = rows.len() as i64;    let mut records: Vec<_> = rows        .into_iter()        .skip(usize::try_from(offset).unwrap_or(usize::MAX))        .take(usize::try_from(limit + 1).unwrap_or(usize::MAX))        .collect();    let more = records.len() as i64 > limit;    records.truncate(usize::try_from(limit).unwrap_or(0));    Ok(Page {        records,        more,        total,    })}fn read(ctx: &Ctx<'_>, definition: &TableDefinition, id: Option<&str>) -> Valid<Vec<Stored>> {    match definition.id.as_str() {        "project_feedback" => feedback(ctx, id),        "project_item" => project_items(ctx, id),        "briefing" => briefings(ctx, id),        "record_version" => versions(ctx, id),        "voice_word" => voice_words(ctx, id),        "repo_label" => labels(ctx, id),        "repo_rule" => rules(ctx, id),        other => Err(ToolFailure::new(format!(            "{other} is not a settings table view"        ))),    }}/// History is rebuilt by the core trail reader, never by treating a change/// receipt as a version: a receipt has only the fields an edit moved, whereas/// a version is the complete preceding record state.fn versions(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> {    use cotton_core::constants::VersionRecordKind;    use cotton_core::rules::history::trail::trail_tables;    if let Some(id) = id {        return one_version(ctx, id);    }    let mut out = Vec::new();    for kind in VersionRecordKind::ALL {        let [storage, named] = trail_tables(kind);        let ids = ctx.read.driver().all(            "SELECT DISTINCT record_id FROM cotton_changes WHERE table_id IN (?, ?) ORDER BY created_at DESC, rowid DESC",            &[SqlValue::Text(storage.into()), SqlValue::Text(named.into())],        ).map_err(sql_error)?;        for found in ids {            let Some(record_id) = found.text("record_id") else {                continue;            };            out.extend(record_versions(ctx, kind, record_id)?);        }    }    newest_first(&mut out);    Ok(out)}/// Versions newest first; one moment's are ordered by their key, descending.fn newest_first(rows: &mut [Stored]) {    rows.sort_by(|left, right| {        right            .created_at            .cmp(&left.created_at)            .then_with(|| right.id.cmp(&left.id))    });}/// One version by its key, `{kind}/{record id}#{change id}`: only that/// record's history is rebuilt. The record id may hold slashes, so the kind/// ends at the first `/` and the change starts after the last `#`.fn one_version(ctx: &Ctx<'_>, key: &str) -> Valid<Vec<Stored>> {    use cotton_core::constants::VersionRecordKind;    let Some((record, _)) = key.rsplit_once('#') else { return Ok(Vec::new()) };    let Some((kind, record_id)) = record.split_once('/') else { return Ok(Vec::new()) };    let Some(kind) = VersionRecordKind::parse(kind) else { return Ok(Vec::new()) };    Ok(record_versions(ctx, kind, record_id)?.into_iter().filter(|row| row.id == key).collect())}/// What `list` may page in SQL: a history narrowed by nothing but its kind/// and its record. Any other filter is read the long way (`None`).fn version_page(ctx: &Ctx<'_>, clauses: &[WhereClause], offset: i64, limit: i64) -> Valid<Option<Page>> {    use cotton_core::constants::VersionRecordKind;    use cotton_core::rules::history::trail::trail_tables;    use cotton_core::records::Condition;    let mut kinds: Vec<VersionRecordKind> = VersionRecordKind::ALL.to_vec();    let mut records: Option<Vec<String>> = None;    for clause in clauses {        let values: Vec<String> = match &clause.condition {            Condition::Is(value) => vec![value.as_str().map(str::to_string)].into_iter().flatten().collect(),            Condition::OneOf(values) => values.iter().filter_map(|value| value.as_str().map(str::to_string)).collect(),            Condition::Present(_) | Condition::NoneOf(_) | Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => return Ok(None),        };        match clause.column.as_str() {            "record_kind" => kinds.retain(|kind| values.iter().any(|value| value == kind.as_str())),            "record_id" => records = Some(values),            _ => return Ok(None),        }    }    // One record's history (the History screen's read): rebuilt whole.    if let Some(ids) = records.as_ref().filter(|ids| ids.len() == 1) {        let mut rows = Vec::new();        for kind in &kinds {            rows.extend(record_versions(ctx, *kind, &ids[0])?);        }        newest_first(&mut rows);        let total = rows.len() as i64;        let mut rows: Vec<_> = rows.into_iter().skip(usize::try_from(offset).unwrap_or(usize::MAX)).collect();        let more = rows.len() as i64 > limit;        rows.truncate(usize::try_from(limit).unwrap_or(0));        return Ok(Some(Page { records: rows, more, total }));    }    if kinds.is_empty() {        return Ok(Some(Page { records: Vec::new(), more: false, total: 0 }));    }    // A version is a change row whose `before` is an object    // (`record_trail`), one to one, so the rows are counted and paged here    // and only the records on the page are rebuilt.    let mut parts = Vec::new();    let mut binds: Vec<SqlValue> = Vec::new();    for kind in &kinds {        let [storage, named] = trail_tables(*kind);        let mut part = String::from(            "SELECT ? AS kind, record_id, id, created_at FROM cotton_changes WHERE table_id IN (?, ?) \             AND before IS NOT NULL AND CASE WHEN json_valid(before) THEN json_type(before) END = 'object'",        );        binds.extend([SqlValue::Text(kind.as_str().into()), SqlValue::Text(storage.into()), SqlValue::Text(named.into())]);        if let Some(ids) = &records {            part.push_str(&format!(" AND record_id IN ({})", vec!["?"; ids.len()].join(", ")));            binds.extend(ids.iter().map(|id| SqlValue::Text(id.clone())));        }        parts.push(part);    }    let changes = parts.join(" UNION ALL ");    let total = ctx        .read        .driver()        .all(&format!("SELECT COUNT(*) AS n FROM ({changes})"), &binds)        .map_err(sql_error)?        .first()        .and_then(|row| row.int("n"))        .unwrap_or(0);    let mut paged = binds.clone();    paged.extend([SqlValue::Integer(limit + 1), SqlValue::Integer(offset)]);    let page = ctx        .read        .driver()        .all(            &format!(                "SELECT kind, record_id, id FROM ({changes}) \                 ORDER BY created_at DESC, kind || '/' || record_id || '#' || id DESC LIMIT ? OFFSET ?"            ),            &paged,        )        .map_err(sql_error)?;    let more = page.len() as i64 > limit;    let requested: Vec<_> = page.iter().take(usize::try_from(limit).unwrap_or(0)).filter_map(|row| {        Some((VersionRecordKind::parse(row.text("kind")?)?, row.text("record_id")?.to_string()))    }).collect();    let mut built = record_versions_batch(ctx, &requested)?;    let rows = page.iter().take(usize::try_from(limit).unwrap_or(0)).filter_map(|row| {        let key = format!("{}/{}#{}", row.text("kind")?, row.text("record_id")?, row.text("id")?);        built.remove(&key)    }).collect();    Ok(Some(Page { records: rows, more, total }))}/// One record's versions as Settings rows, newest first.fn record_versions(    ctx: &Ctx<'_>,    kind: cotton_core::constants::VersionRecordKind,    record_id: &str,) -> Valid<Vec<Stored>> {    use cotton_core::rules::history::fields::history_kind;    use cotton_core::rules::history::trail::{trail_tables, TRAIL_SQL};    let table = history_kind(kind).table;    let [storage, named] = trail_tables(kind);    let current = ctx.read.by_id(table, record_id).map_err(sql_error)?;    let rows = ctx        .read        .driver()        .all(            TRAIL_SQL,            &[                SqlValue::Text(record_id.into()),                SqlValue::Text(storage.into()),                SqlValue::Text(named.into()),            ],        )        .map_err(sql_error)?;    let live_lines = Vec::new();    let lines = crate::presentation::line_rows(ctx.db(), ctx.workspace_id);    version_rows(ctx.workspace_id, &lines, kind, record_id, current, rows, live_lines)}/// The complete histories and current rows of just the records on the page,/// read once per kind. Folding stays the same core trail and restore logic.fn record_versions_batch(    ctx: &Ctx<'_>,    requested: &[(cotton_core::constants::VersionRecordKind, String)],) -> Valid<std::collections::HashMap<String, Stored>> {    use cotton_core::constants::VersionRecordKind;    use cotton_core::rules::history::{fields::history_kind, trail::trail_tables};    use crate::mcp::read_db::{Filter, Query};    let mut by_kind: std::collections::BTreeMap<&str, Vec<String>> = std::collections::BTreeMap::new();    for (kind, id) in requested { by_kind.entry(kind.as_str()).or_default().push(id.clone()); }    let mut built = std::collections::HashMap::new();    let lines = crate::presentation::line_rows(ctx.db(), ctx.workspace_id);    for (kind, mut ids) in by_kind {        let kind = VersionRecordKind::parse(kind).expect("requested kind");        ids.sort(); ids.dedup();        let values: Vec<_> = ids.iter().map(|id| SqlValue::Text(id.clone())).collect();        let mut current: std::collections::HashMap<String, Data> = ctx.read.select(            &Query::on(history_kind(kind).table).filter(Filter::In("id".into(), values.clone()))        ).map_err(sql_error)?.into_iter().filter_map(|row| Some((row.get("id")?.as_str()?.to_string(), row))).collect();        let marks = vec!["?"; ids.len()].join(", ");        let [storage, named] = trail_tables(kind);        let mut params = values.clone();        params.extend([SqlValue::Text(storage.into()), SqlValue::Text(named.into())]);        let mut trails: std::collections::HashMap<String, Vec<cotton_store::Row>> = std::collections::HashMap::new();        for row in ctx.read.driver().all(&format!(            "SELECT record_id, id, before, after, actor, created_at FROM cotton_changes \             WHERE record_id IN ({marks}) AND table_id IN (?, ?) ORDER BY created_at DESC, rowid DESC"        ), &params).map_err(sql_error)? {            if let Some(id) = row.text("record_id") { trails.entry(id.to_string()).or_default().push(row); }        }        for id in ids {            for row in version_rows(                ctx.workspace_id,                &lines,                kind,                &id,                current.remove(&id),                trails.remove(&id).unwrap_or_default(),                Vec::new(),            )? {                built.insert(row.id.clone(), row);            }        }    }    Ok(built)}fn version_rows(    workspace: &str,    lines: &[cotton_core::rules::shell_lines::LineRow],    kind: cotton_core::constants::VersionRecordKind,    record_id: &str,    current: Option<Data>,    rows: Vec<cotton_store::Row>,    _live_lines: Vec<(String, String)>,) -> Valid<Vec<Stored>> {    use cotton_core::rules::history::entries::history_entries;    use cotton_core::rules::history::restorable::{restore_block, restore_patch};    use cotton_core::rules::history::trail::record_trail;    let trail = record_trail(kind, workspace, record_id, &rows, current.as_ref());    let block = restore_block(kind, current.as_ref());    let current_data = current.clone().unwrap_or_default();    let mut out = Vec::new();    for entry in history_entries(kind, &trail, current.as_ref()) {        // This is the route key Settings has always used: the record        // id may contain slashes, so the final `#` is the only        // separator the reader needs to find the version again.        let record_key = format!("{kind}/{record_id}#{}", entry.version.id);        let mut data = Data::new();        data.insert("record_kind".into(), Value::from(kind.as_str()));        data.insert("record_id".into(), Value::from(record_id.to_string()));        data.insert("version".into(), Value::from(entry.version.id.clone()));        data.insert("hand".into(), Value::from(entry.actor.to_string()));        data.insert(            "when_line".into(),            Value::from(entry.version.created_at.clone()),        );        data.insert(            "day_line".into(),            Value::from(                entry                    .version                    .created_at                    .get(..10)                    .unwrap_or_default()                    .to_string(),            ),        );        data.insert(            "changed_line".into(),            Value::from(format!("{} field(s) changed", entry.changes.len())),        );        // `changes` is a long-text page field.  Keep its structured        // shape as JSON text, as the existing Settings source does,        // rather than answering an array to a text column.        let changes = Value::Array(            entry                .changes                .iter()                .map(|change| {                    serde_json::json!({                        "column": change.column,                        "before": change.before,                        "after": change.after,                    })                })                .collect(),        );        data.insert(            "changes".into(),            Value::from(serde_json::to_string(&changes).unwrap_or_else(|_| "[]".into())),        );        data.insert(            "op".into(),            Value::from(match entry.version.op {                cotton_core::constants::VersionOp::Delete => "delete",                _ => "update",            }),        );        // Put back is an offered write only when the same native        // restore calculation would move a field or transaction side.        let restorable =            block.is_none() && !restore_patch(kind, &entry.version.data, &current_data).is_empty();        data.insert("restorable".into(), Value::Bool(restorable));        if let Some(blocked) = block {            data.insert("blocked_line".into(), Value::from(blocked.words(lines)));        }        out.push(Stored {            id: record_key,            data,            created_at: Some(entry.version.created_at.clone()),            updated_at: None,            deleted_at: None,            byline: None,        });    }    Ok(out)}fn briefings(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> {    use crate::mcp::handlers::records_2::memory::{briefing_previews, memory_projects};    let projects = memory_projects(ctx)?;    let selected: Vec<_> = projects.iter()        .filter(|project| project.status == "active" && id.is_none_or(|id| id == project.slug))        .cloned().collect();    Ok(briefing_previews(ctx, &projects, &selected)?.into_iter().map(|preview| {        let mut data = Data::new();        data.insert("name".into(), Value::from(preview.name));        data.insert("size".into(), Value::from(format!("{} tokens", preview.tokens)));        if preview.left_out > 0 {            data.insert("left_out".into(), Value::from(format!("{} entries are not shown here", preview.left_out)));        }        data.insert("briefing".into(), Value::from(preview.markdown));        Stored { id: preview.slug, data, created_at: None, updated_at: None, deleted_at: None, byline: None }    }).collect())}fn voice_words(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> {    let owner_person = ctx.read.driver().get("SELECT owner_person_id FROM cotton_workspaces WHERE id = ?", &[SqlValue::Text(ctx.workspace_id.to_string())]).map_err(sql_error)?        .and_then(|row| row.text("owner_person_id").map(str::to_string)).filter(|id| !id.is_empty());    let mut sql = String::from("SELECT id, term, source, use_count, last_used_at, created_at FROM cotton_voice_vocabulary WHERE workspace_id = ? AND source = 'manual'");    let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];    if let Some(id) = id {        sql.push_str(" AND id = ?");        params.push(SqlValue::Text(id.to_string()));    }    sql.push_str(" ORDER BY term COLLATE NOCASE, id");    let rows = ctx.read.driver().all(&sql, &params).map_err(sql_error)?;    Ok(rows        .iter()        .map(|row| {            let mut data = Data::new();            put_text(&mut data, "term", row.text("term"));            data.insert("source".into(), Value::from("you"));            put_text(&mut data, "added_by", owner_person.as_deref());            let uses = row.int("use_count").unwrap_or(0);            data.insert("use_count".into(), Value::from(uses));            data.insert(                "line".into(),                Value::from(if uses == 1 {                    "Heard once".to_string()                } else {                    format!("Heard {uses} times")                }),            );            put_text(&mut data, "last_used_at", row.text("last_used_at"));            Stored {                id: row.text("id").unwrap_or_default().to_string(),                data,                created_at: row.text("created_at").map(str::to_string),                updated_at: row.text("last_used_at").map(str::to_string),                deleted_at: None,                byline: None,            }        })        .collect())}pub(super) fn voice_word_create(    ctx: &mut Ctx<'_>,    _definition: &TableDefinition,    values: &Data,) -> Valid<String> {    if values.len() != 1 || !values.contains_key("term") {        return Err(ToolFailure::new("Say one voice word."));    }    let Some(term) = values        .get("term")        .and_then(Value::as_str)        .map(crate::dictation::normalize)        .filter(|term| !term.is_empty())    else {        return Err(ToolFailure::new("A voice word is text."));    };    let result = crate::dictation::upsert_term(        ctx,        &crate::dictation::VoiceTerm {            term,            source: "manual".into(),        },    )    .map_err(ToolFailure::new)?;    // The generic receipt rereads through the snapshot reader. Dictation's    // writer is separate, so make its durable term visible before that read.    ctx.commit()?;    result        .get("id")        .and_then(Value::as_str)        .map(str::to_string)        .ok_or_else(|| ToolFailure::new("dictation did not return the word it saved"))}pub(super) fn voice_word_delete(    ctx: &mut Ctx<'_>,    _definition: &TableDefinition,    id: &str,) -> Valid<()> {    crate::dictation::forget_term(ctx, id).map_err(ToolFailure::new)?;    ctx.commit()?;    Ok(())}/// The feedback engine keeps replies with their root report.  A table row is/// the root, so an answer never lets a reply acquire a second lifecycle.fn feedback(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> {    let (project, feedback) = id        .and_then(feedback_key)        .map_or((None, id), |(project, feedback)| {            (Some(project), Some(feedback))        });    // A report's links are found by the report (`+` keeps the link's    // workspace off its index), never by reading every link per report: that    // read every link once per row, 97 ms to count five hundred.    let mut sql = String::from(        "SELECT f.id, f.body, f.context, f.status, f.author_label, f.resolution_note, f.created_at, f.image_sha256, f.image_ext, \         CASE WHEN json_extract(f.context, '$.kind') = 'report' OR f.app IS NOT NULL THEN 'report' ELSE 'feedback' END AS kind, \         (SELECT GROUP_CONCAT(p2.name, ', ') FROM cotton_project_links l2 JOIN cotton_memory_projects p2 ON p2.id = l2.project_id AND p2.workspace_id = f.workspace_id WHERE +l2.workspace_id = f.workspace_id AND l2.record_kind = 'feedback' AND l2.record_id = f.id) AS filed, \         p.slug AS project_slug, p.name AS project_name, \         GROUP_CONCAT(r.body, char(10)) AS replies \         FROM cotton_feedback f \         LEFT JOIN cotton_project_links l ON +l.workspace_id = f.workspace_id \           AND l.record_kind = 'feedback' AND l.record_id = f.id \         LEFT JOIN cotton_memory_projects p ON p.id = l.project_id AND p.workspace_id = f.workspace_id \         LEFT JOIN cotton_feedback r ON r.parent_id = f.id \         WHERE f.workspace_id = ? AND f.parent_id IS NULL",    );    let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];    match (project, feedback) {        // A report filed in a project, or one whose own id holds a colon        // (a definition upgrade's) and is in none: the split read either        // way, so a listed report never opens as gone (292, walker291).        (Some(project), Some(feedback)) => {            sql.push_str(" AND ((f.id = ? AND p.slug = ?) OR (f.id = ? AND p.slug IS NULL))");            params.push(SqlValue::Text(feedback.to_string()));            params.push(SqlValue::Text(project.to_string()));            params.push(SqlValue::Text(id.unwrap_or_default().to_string()));        }        (_, Some(feedback)) => {            sql.push_str(" AND f.id = ?");            params.push(SqlValue::Text(feedback.to_string()));        }        (_, None) => {}    }    sql.push_str(" GROUP BY f.id, l.project_id ORDER BY f.resolved_at IS NOT NULL, f.created_at DESC, f.id, p.slug");    let rows = ctx.read.driver().all(&sql, &params).map_err(sql_error)?;    let delivery = crate::feedback::delivery::Readings::load(ctx).map_err(ToolFailure::new)?;    Ok(rows        .iter()        .map(|row| {            let mut data = Data::new();            put_text(&mut data, "kind", row.text("kind"));            put_text(&mut data, "filed", row.text("filed"));            let image_key = row.text("image_sha256").zip(row.text("image_ext"))                .map(|(sha, ext)| cotton_core::media::keys::walkthrough_image_key(ctx.file.id(), sha, ext));            let transport = delivery.delivery(row.text("id").unwrap_or_default(), image_key.as_deref());            // The state alone: a transport's own sentence is for the log,            // never a line (291 words row 2).            data.insert("delivery".into(), transport["state"].clone());            put_text(                &mut data,                "project",                row.text("project_slug"),            );            put_text(&mut data, "project_name", row.text("project_name"));            put_text(&mut data, "feedback_id", row.text("id"));            put_text(&mut data, "body", row.text("body"));            let context = row.text("context").and_then(|raw| serde_json::from_str(raw).ok()).unwrap_or(Value::Null);            if cotton_core::rules::feedback::is_system_notice(&context) {                data.insert("kind".into(), Value::from("notice"));            }            // A write the door refused is a notice in the definition's words            // and typed facts — the table by its definition's name and the            // connection — never the door's sentence with a tool's slug, a            // table's id and the field paths it refused (291 words row 2).            if let Some(refused) = context.get("refused_write").filter(|refused| refused.is_object()) {                let words = notice_words("refused_write");                data.insert("kind".into(), Value::from("notice"));                data.insert("notice".into(), Value::from("refused_write"));                data.insert("body".into(), Value::from(words.clone()));                data.insert("line".into(), Value::from(words));                if let Some(table) = refused["table"].as_str().and_then(cotton_core::definitions::builtin_table_definition) {                    data.insert("refused_table".into(), Value::from(table.plural.clone()));                }                put_text(&mut data, "refused_by", refused["connection"].as_str());            }            // An edit an upgrade set aside is a notice in the definition's            // words, never the file's path and the key's (292, walker291:            // 'themes/paper.json: scale.tokens.fanbandgap'); the file, the            // key and both values stay in the context.            if context["kind"].as_str() == Some("definition_upgrade") {                let words = notice_words("definition_upgrade");                data.insert("kind".into(), Value::from("notice"));                data.insert("notice".into(), Value::from("definition_upgrade"));                data.insert("body".into(), Value::from(words.clone()));                data.insert("line".into(), Value::from(words));            }            // A table a phone could not draw, so it drew its own copy, is a            // notice in the definition's words — the tool's and the table's            // names — never the parse error, which stays in the context (294,            // walker293: '…does not parse: unknown variant `account_number`…').            if context["surface"].as_str() == Some("definitions") && context["kind"].as_str() == Some("table") {                let words = context["id"].as_str()                    .and_then(cotton_core::rules::feedback::definition_fallback_line)                    .unwrap_or_else(|| notice_words("definition_fallback"));                data.insert("kind".into(), Value::from("notice"));                data.insert("notice".into(), Value::from("definition_fallback"));                data.insert("body".into(), Value::from(words.clone()));                data.insert("line".into(), Value::from(words));            }            let line = match cotton_core::rules::feedback::system_notice_line(&context) {                // A backup notice's page says the backup's one line too, never                // the body it was filed with (an older row's is the Mac's                // script line); the reason stays in the context.                Some(notice) => {                    data.insert("body".into(), Value::from(notice.clone()));                    notice                }                None => cotton_core::rules::feedback::feedback_line(row.text("body").unwrap_or_default()),            };            if !data.contains_key("notice") {                data.insert("line".into(), Value::from(line));            }            let verdict = match row.text("status").unwrap_or("open") {                "open" => "Open",                "agreed" => "Agreed",                "declined" => "Declined",                "shipped" => "Shipped",                "dismissed" => "Dismissed",                _ => "Resolved",            };            data.insert("verdict".into(), Value::from(verdict));            // The page groups as open/closed, but the engine's three verdict            // commands must know which precise verdict is current.            put_text(&mut data, "verdict_status", row.text("status"));            data.insert(                "status".into(),                Value::from(if row.text("status") == Some("open") {                    "open"                } else {                    "closed"                }),            );            put_text(&mut data, "who", row.text("author_label"));            put_text(&mut data, "resolution", row.text("resolution_note"));            put_text(&mut data, "replies", row.text("replies"));            Stored {                id: match row.text("project_slug") {                    Some(project) => format!("{project}:{}", row.text("id").unwrap_or_default()),                    None => row.text("id").unwrap_or_default().to_string(),                },                data,                created_at: row.text("created_at").map(str::to_string),                updated_at: None,                deleted_at: None,                byline: None,            }        })        .collect())}/// The `project_feedback` definition's words for a notice.fn notice_words(notice: &str) -> String {    cotton_core::definitions::builtin_table_definition("project_feedback")        .and_then(|definition| definition.column("notice"))        .and_then(|column| column.labels.as_ref())        .and_then(|labels| labels.get(notice))        .cloned()        .unwrap_or_default()}/// A project-feedback row is a membership, so its route identity contains/// both the project slug and the durable feedback id.fn feedback_key(id: &str) -> Option<(&str, &str)> {    let (project, feedback) = id.split_once(':')?;    (!project.is_empty() && !feedback.is_empty()).then_some((project, feedback))}/// This is the project engine's membership projection.  The identity includes/// both project and kind: an id can legitimately occur in two project lists,/// and notes and journals share storage while remaining different records.fn project_items(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> {    use crate::mcp::handlers::projects::kinds::{kind_source, title_of};    use crate::mcp::handlers::projects::{links_of, memory_projects, read_linked_rows, KindRef};    use cotton_core::constants::ProjectLinkKind;    let projects = memory_projects(ctx)?;    let links = links_of(        &ctx.read,        &projects            .iter()            .filter_map(|p| crate::mcp::handlers::common::text(p, "id"))            .collect::<Vec<_>>(),    )?;    let refs: Vec<_> = links        .iter()        .filter_map(|link| {            Some(KindRef {                kind: ProjectLinkKind::parse(&link.record_kind)?,                id: link.record_id.clone(),            })        })        .collect();    let rows = read_linked_rows(&ctx.read, &refs)?;    let mut result = Vec::new();    for link in links {        let Some(kind) = ProjectLinkKind::parse(&link.record_kind) else {            continue;        };        let Some(row) = rows.get(&format!("{kind}:{}", link.record_id)) else {            continue;        };        let project = projects.iter().find(|p| {            crate::mcp::handlers::common::text(p, "id").as_deref() == Some(&link.project_id)        });        let Some(project) = project else { continue };        let slug = crate::mcp::handlers::common::text(project, "slug").unwrap_or_default();        let item_id = format!("{slug}/{kind}/{}", link.record_id);        if id.is_some_and(|wanted| wanted != item_id) {            continue;        }        let mut data = Data::new();        put_text(            &mut data,            "project",            Some(slug.as_str()),        );        let source = kind_source(kind);        let section = match source.group {            "threads" => "chats", "emailThreads" => "email", "pages" => "reader",            "transactions" => "money", "repositories" => "code", "secrets" => "passwords",            other => other,        };        put_text(&mut data, "project_name", crate::mcp::handlers::common::text(project, "name").as_deref());        data.insert("section".into(), Value::from(section));        // Public target identity comes from the records storage registry.        let target = cotton_core::definitions::builtin_table_definitions().into_iter()            .find(|definition| cotton_core::definitions::builtin_store_table(&definition.id) == Some(source.table))            .map(|definition| definition.id.clone());        if let Some(target) = target {            data.insert("record_table".into(), Value::from(target));            data.insert("record_id".into(), Value::from(link.record_id.clone()));        }        data.insert("title".into(), Value::from(title_of(kind, row)));        put_text(            &mut data,            "line",            crate::mcp::handlers::common::text(row, "body").as_deref(),        );        let when = [            "updated_at",            "created_at",            "started_at",            "last_at",            "due_at",        ]        .into_iter()        .find_map(|column| crate::mcp::handlers::common::text(row, column));        put_text(&mut data, "when", when.as_deref());        result.push(Stored {            id: item_id,            data,            created_at: when,            updated_at: None,            deleted_at: None,            byline: None,        });    }    Ok(result)}fn labels(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> {    let mut sql = String::from(        "SELECT id, repo_id, name, color, description, created_at, updated_at \         FROM cotton_repo_labels WHERE workspace_id = ?",    );    let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];    if let Some(id) = id {        sql.push_str(" AND id = ?");        params.push(SqlValue::Text(id.to_string()));    }    sql.push_str(" ORDER BY name COLLATE NOCASE, id");    let rows = ctx.read.driver().all(&sql, &params).map_err(sql_error)?;    Ok(rows        .iter()        .map(|row| {            let mut data = Data::new();            put_text(&mut data, "name", row.text("name"));            put_text(&mut data, "color", row.text("color"));            put_text(&mut data, "description", row.text("description"));            put_text(&mut data, "repo_id", row.text("repo_id"));            Stored {                id: row.text("id").unwrap_or_default().to_string(),                data,                created_at: row.text("created_at").map(str::to_string),                updated_at: row.text("updated_at").map(str::to_string),                deleted_at: None,                byline: None,            }        })        .collect())}fn rules(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> {    let mut sql = String::from(        "SELECT id, repo_id, branch, required_contexts_json, required_approvals, \         block_outdated, allow_push, created_at, updated_at \         FROM cotton_repo_rules WHERE workspace_id = ?",    );    let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];    if let Some(id) = id {        sql.push_str(" AND id = ?");        params.push(SqlValue::Text(id.to_string()));    }    sql.push_str(" ORDER BY branch COLLATE NOCASE, id");    let rows = ctx.read.driver().all(&sql, &params).map_err(sql_error)?;    Ok(rows        .iter()        .map(|row| {            let mut data = Data::new();            put_text(&mut data, "branch", row.text("branch"));            put_text(&mut data, "repo_id", row.text("repo_id"));            let checks = row                .text("required_contexts_json")                .and_then(|json| serde_json::from_str::<Vec<String>>(json).ok())                .filter(|checks| !checks.is_empty())                .map(|checks| checks.join("\n"));            put_text(&mut data, "checks", checks.as_deref());            if let Some(approvals) = row.int("required_approvals") {                data.insert("approvals".into(), Value::from(approvals));            }            data.insert(                "up_to_date".into(),                Value::Bool(row.int("block_outdated").unwrap_or(0) != 0),            );            data.insert(                "allow_push".into(),                Value::Bool(row.int("allow_push").unwrap_or(0) != 0),            );            Stored {                id: row.text("id").unwrap_or_default().to_string(),                data,                created_at: row.text("created_at").map(str::to_string),                updated_at: row.text("updated_at").map(str::to_string),                deleted_at: None,                byline: None,            }        })        .collect())}fn put_text(data: &mut Data, key: &str, value: Option<&str>) {    if let Some(value) = value.filter(|value| !value.trim().is_empty()) {        data.insert(key.to_string(), Value::from(value.to_string()));    }}fn sql_error(error: impl std::fmt::Display) -> ToolFailure {    ToolFailure::new(error.to_string())}#[cfg(test)]mod tests {    use super::*;    /// RULE: A user-defined table cannot impersonate a shipped supporting    /// engine merely by adopting its id; routing requires its compiled engine binding.    #[test]    fn supporting_engine_identity_cannot_be_claimed_by_a_user_table() {        // The project engine's own table, drawn by no tool: routing is its compiled binding.        let mut definition = TableDefinition::from_json(r#"{"id":"project_feedback","name":"Feedback","plural":"Feedback","builtin":true,"engine":"feedback",            "columns":[{"key":"name","type":"text","required":true}],"title":"name","slip":{"title":"name"},"tile":{"face":"slip-list"},            "page":[{"heading":null,"columns":["name"]}]}"#).unwrap();        assert!(handles(&definition));        definition.builtin = false;        assert!(handles(&definition));        definition.engine = None;        assert!(!handles(&definition));        definition.engine = Some("invented".into());        assert!(!handles(&definition));        definition.id = "personal_table".into();        assert!(!handles(&definition));    }    #[test]    fn a_feedback_row_keeps_its_project_membership_in_its_identity() {        // RULE: A report can be filed in more than one project.  The route key        // must retain that membership while `feedback_id` carries the durable        // id the feedback writer accepts.        assert_eq!(            feedback_key("garden:feedback-7"),            Some(("garden", "feedback-7"))        );        assert_eq!(feedback_key("feedback-7"), None);    }}