Cotton code
186 lines · 6.8 KB · RustRaw
//! The words a coding session is read in, answered by the generic read of the//! `session` table (`cotton_core::definitions::COMPUTED_COLUMNS`) — the words//! the app's `SessionTableSource` worked out in Swift, said by the ONE copy of//! their rules, [`crate::session_words`].//!//! This file only gathers what those rules read: each record's row spelled as//! `list_sessions` and `read.session` spell one to the app (camelCase), its//! project's slug and name, its task counts on a list, and — for one record's//! page — its task list, as `read.session` reads it.//!//! A list is cut by the queue's seven-day window, as `read.sessions` is; a//! search's hits and one project's sessions of all time are cut by the//! history card (`SessionTableSource.records`, STS:72-124), and a page by the//! window again (STS:148-154).use std::collections::BTreeMap;use cotton_core::definitions::TableDefinition;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use super::Stored;use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{rows, text, Valid};use crate::mcp::read_db::{Filter, Order, Query};use crate::session_words::{session_words, Cut, PageFacts, SESSIONS_WINDOW_MS};/// `(camelCase key the rules read, store column)` of a session's row.const SESSION_FIELDS: &[(&str, &str)] = &[    ("id", "id"),    ("projectId", "project_id"),    ("tool", "tool"),    ("externalId", "external_id"),    ("deviceId", "device_id"),    ("machine", "machine"),    ("account", "account"),    ("repoUrl", "repo_url"),    ("branch", "branch"),    ("title", "title"),    ("model", "model"),    ("kind", "kind"),    ("state", "state"),    ("stateAt", "state_at"),    ("waitingKind", "waiting_kind"),    ("waitingRef", "waiting_ref"),    ("lastLine", "last_line"),    ("exitCode", "exit_code"),    ("hostOwned", "host_owned"),    ("holdReason", "hold_reason"),    ("error", "error"),    ("startedAt", "started_at"),    ("claimedAt", "claimed_at"),    ("createdAt", "created_at"),    ("lastActiveAt", "last_active_at"),    ("endedAt", "ended_at"),];/// The row spelled the way the rules read it.pub(super) fn spelled(row: &Map<String, Value>, fields: &[(&str, &str)]) -> Map<String, Value> {    fields        .iter()        .filter_map(|(key, column)| {            let value = row.get(*column).filter(|value| !value.is_null())?;            Some((key.to_string(), value.clone()))        })        .collect()}/// How a list read is cut: a search of two characters or more, or one/// project's list, reaches past the window (STS:74-89, 116-122).pub(super) fn cut_of(args: &Map<String, Value>, whole: bool) -> Cut {    if whole {        return Cut::Window(SESSIONS_WINDOW_MS);    }    let searching = args        .get("query")        .and_then(Value::as_str)        .is_some_and(|query| query.trim().chars().count() >= 2);    let one_project = args.get("project").is_some_and(|project| !project.is_null())        || args            .get("where")            .and_then(Value::as_object)            .is_some_and(|clauses| clauses.contains_key("project_id"));    if searching || one_project {        Cut::History    } else {        Cut::Window(SESSIONS_WINDOW_MS)    }}/// Answer the words of every `session` record read. `whole` is a single/// record read for its page.pub(super) fn session_table_words(    ctx: &Ctx<'_>,    definition: &TableDefinition,    records: &mut [Stored],    args: &Map<String, Value>,    whole: bool,) -> Valid<()> {    if !definition.has_engine() || definition.id != "session" || records.is_empty() {        return Ok(());    }    let ids: Vec<SqlValue> = records.iter().map(|record| SqlValue::Text(record.id.clone())).collect();    let columns: Vec<&str> = SESSION_FIELDS.iter().map(|(_, column)| *column).collect();    let found = rows(ctx, &Query::on("cotton_sessions").columns(&columns).filter(Filter::In("id".into(), ids.clone())))?;    // Its project by slug and name — a conversation is called after it.    let project_ids: Vec<SqlValue> = found        .iter()        .filter_map(|row| text(row, "project_id"))        .map(SqlValue::Text)        .collect();    let projects = if project_ids.is_empty() {        Vec::new()    } else {        rows(            ctx,            &Query::on("cotton_memory_projects")                .columns(&["id", "slug", "name"])                .filter(Filter::In("id".into(), project_ids)),        )?    };    // A list row carries its task counts (`list_sessions`' tasksDone/tasksTotal).    let mut counts: BTreeMap<String, (i64, i64)> = BTreeMap::new();    if !whole {        let tasks = rows(            ctx,            &Query::on("cotton_session_tasks")                .columns(&["id", "session_id", "state"])                .filter(Filter::In("session_id".into(), ids)),        )?;        for task in &tasks {            let Some(session) = text(task, "session_id") else { continue };            let entry = counts.entry(session).or_insert((0, 0));            entry.1 += 1;            if text(task, "state").as_deref() == Some("done") {                entry.0 += 1;            }        }    }    let cut = cut_of(args, whole);    let now = ctx.now.timestamp_millis();    for record in records.iter_mut() {        let Some(row) = found.iter().find(|row| text(row, "id").as_deref() == Some(record.id.as_str())) else {            continue;        };        let mut session = spelled(row, SESSION_FIELDS);        if let Some(project) = text(row, "project_id")            .and_then(|id| projects.iter().find(|project| text(project, "id").as_deref() == Some(id.as_str())))        {            if let Some(slug) = text(project, "slug") {                session.insert("project".into(), Value::from(slug));            }            if let Some(name) = text(project, "name") {                session.insert("projectName".into(), Value::from(name));            }        }        if let Some((done, total)) = counts.get(&record.id) {            session.insert("tasksDone".into(), Value::from(*done));            session.insert("tasksTotal".into(), Value::from(*total));        }        let page = if whole { Some(page_facts(ctx, &record.id)?) } else { None };        for (key, value) in session_words(&session, page.as_ref(), cut, now) {            record.data.insert(key, value);        }    }    Ok(())}/// What one session's page reads besides its row, as `read.session` reads/// it: its task list in the agent's own order.fn page_facts(ctx: &Ctx<'_>, id: &str) -> Valid<PageFacts> {    let tasks = rows(        ctx,        &Query::on("cotton_session_tasks")            .columns(&["id", "seq", "text", "state"])            .eq("session_id", id.to_string())            .order_by("seq", Order::Asc),    )?;    Ok(PageFacts {        tasks: tasks.into_iter().map(Value::Object).collect(),    })}#[cfg(test)]#[path = "session_table_tests.rs"]mod tests;