Cotton code
130 lines · 7.5 KB · TypeScriptRaw
/** * Computed reads (owner, 26 Oct 2026), worked out in the object's SQLite so a * figure never needs a table paged through an assistant: * * - `summarize_records { table, where?, group_by?, measures }`: counts, sums, *   averages, least and most, over a table's live records the token sees (no *   internal table, no binned record), optionally one group per value. * - `storage_summary`: what the object holds against its caps, table by table. */import { closed } from "../../../agent_statement.ts";import { changeWindow } from "../../../changes.ts";import { fail, type Data, type ToolContext } from "../../context.ts";import { col, typeOf, type Cond } from "../../../store.ts";import { liveSql } from "./list.ts";import { isSensitiveColumn, resolveTable, tableArg, type Column, type Table } from "./table.ts";import { describe, quoted } from "./values.ts";import { clauseSql, parseWhere } from "./where.ts";const OPS = ["count", "sum", "avg", "min", "max"] as const;type Op = (typeof OPS)[number];const NUMERIC = new Set(["number", "amount"]);const ORDERED = new Set(["number", "amount", "date", "time", "text"]);const MAX_GROUPS = 200;interface Measure {  op: Op;  column: Column | null;  key: string;  sql: string;}/** A column a figure may read: one the table has, never a sealed or hashed one. */function readable(t: Table, key: unknown, what: string): Column {  if (typeof key !== "string" || !key.trim()) fail(`${what} is a column key of ${t.plural}`);  const c = t.column(key.trim()) ?? fail(`${t.plural} have no column ${quoted(key.trim())}`);  if (isSensitiveColumn(c.key) || c.secret === true) fail(`${quoted(c.key)} is never read`);  if (t.sealed(c.key)) fail(`${t.plural} keep ${quoted(c.key)} sealed: the object cannot read it to work a figure out`);  return c;}/** A filled value: absent, null and "" are not. */const filled = (key: string): string => `${typeOf(key)} <> 'null' AND ${col(key)} <> ''`;function measuresOf(t: Table, raw: unknown): Measure[] {  if (!Array.isArray(raw) || !raw.length) fail('measures is a list of { column, op }: [{ "op": "count" }, { "column": "amount_minor", "op": "sum" }]');  if (raw.length > 20) fail("measures is at most 20 figures");  return raw.map((m, i) => {    if (!m || typeof m !== "object" || Array.isArray(m)) fail(`measures[${i}] is { column, op }; ${describe(m)} is not`);    const asked = m as Data;    const op = asked.op as Op;    if (!OPS.includes(op)) fail(`measures[${i}].op is one of ${OPS.join(", ")}`);    if (op === "count" && (asked.column === undefined || asked.column === null)) return { op, column: null, key: "count", sql: "COUNT(*)" };    const c = readable(t, asked.column, `measures[${i}].column`);    const k = col(c.key);    if (op === "count") return { op, column: c, key: `count_${c.key}`, sql: `SUM(CASE WHEN ${filled(c.key)} THEN 1 ELSE 0 END)` };    if ((op === "sum" || op === "avg") && !NUMERIC.has(c.type)) fail(`${op} adds up a number or amount column; ${quoted(c.key)} is ${c.type}`);    if ((op === "min" || op === "max") && !ORDERED.has(c.type)) fail(`${op} reads a number, amount, date, time or text column; ${quoted(c.key)} is ${c.type}`);    const numeric = `CASE WHEN ${typeOf(c.key)} IN ('integer', 'real') THEN ${k} END`;    const value = NUMERIC.has(c.type) ? numeric : `CASE WHEN ${filled(c.key)} THEN ${k} END`;    return { op, column: c, key: `${op}_${c.key}`, sql: `${op.toUpperCase()}(${value})` };  });}export function summarizeRecords(ctx: ToolContext, args: Data): Data {  const t = resolveTable(ctx, tableArg(args), args.table);  const measures = measuresOf(t, args.measures);  const keys = new Set<string>();  for (const m of measures) {    if (keys.has(m.key)) fail(`${m.key} is asked twice`);    keys.add(m.key);  }  const conds: Cond[] = [...liveSql(t)];  const now = Date.parse(ctx.now);  for (const clause of parseWhere(t, args.where)) conds.push(clauseSql(clause, now));  const group = args.group_by === undefined || args.group_by === null ? null : readable(t, args.group_by, "group_by");  const groupSql = group ? `CASE WHEN ${filled(group.key)} THEN ${col(group.key)} END` : null;  const found = ctx.store.summary(t.id, conds, groupSql, measures.map((m) => m.sql), MAX_GROUPS + 1);  const groups = found.slice(0, MAX_GROUPS).map((row) => {    const out: Data = {};    if (group) out[group.key] = row.group;    measures.forEach((m, i) => {      const v = row.figures[i] ?? null;      out[m.key] = m.op === "count" ? Number(v ?? 0) : v;    });    return out;  });  return { table: t.id, groups, more: found.length > MAX_GROUPS };}/** From this fraction of a cap the summary warns (src/business.ts DATABASE_WARN_FRACTION). */export const WARN_FRACTION = 0.8;export function storageSummary(ctx: ToolContext, args: Data = {}): Data {  if (args.parts !== undefined && typeof args.parts !== "boolean") fail("parts is true or false");  const size = ctx.size();  // The tables, the parts and the log's writers each read the whole file: a big object's are its alarm's last measure  // (src/storage_measure.ts), said with when; until the first is made, the tables' rows as row_counts holds them.  const { measure, measuring } = ctx.store.storageMeasure(new Date(ctx.now));  const changes = ctx.store.changeCount();  // A CLOSED table (agent_statement.ts; Sites' list) is not there for an assistant, so it is neither named nor counted  // here, as every other read answers (coordinator, 26 Nov 2026, the GENESIS KITS review).  const tables = (measure ? measure.tables : ctx.store.countsProgress().ready ? Object.entries(ctx.store.counts()).map(([table, rows]) => ({ table, rows, tombstones: null, bytes: null })) : []).filter((t) => !closed(t.table));  const fraction = (n: number, cap: number) => Math.round((n / cap) * 10_000) / 10_000;  const database: Data = { bytes: size.database, cap: size.databaseCap, used: fraction(size.database, size.databaseCap) };  const media: Data = { bytes: size.media, cap: size.mediaCap, used: fraction(size.media, size.mediaCap) };  const warning = (what: string, d: Data): void => {    const used = Number(d.used);    if (used >= 1) d.warning = `The ${what} is full: it takes nothing new until something is removed.`;    else if (used >= WARN_FRACTION) d.warning = `The ${what} is ${Math.floor(used * 100)}% full: new ${what === "database" ? "records" : "files"} are refused once it reaches its cap.`;  };  warning("database", database);  warning("media store", media);  // The change log's window as this account sets it (src/changes.ts), and its counted size once counting has begun.  const window = changeWindow(ctx.store);  const counted = ctx.store.changeSize();  const changeLog: Data = { rows: changes, keeps: { days: window.days, rows: window.rows, chars: window.bytes } };  if (counted.counting) changeLog.chars = { counted: counted.bytes, ready: counted.ready };  const out: Data = { database, media, tables, change_log: changeLog };  out.measured = measure ? { at: measure.at, done_at: measure.done_at } : null;  if (measuring) out.measuring = measuring;  // Which Worker version answered (wrangler version_metadata): a cap or a field that looks old says which deploy it came from.  out.worker = size.worker ?? null;  // Where the file's bytes go, part by part (src/storage_parts.ts), unless asked not to (coordinator, 22 Nov 2026: a  // client with a cached schema sends no argument, so the parts come by default).  if (args.parts !== false) {    out.parts = measure ? measure.parts : null;    changeLog.by = measure ? measure.changes_by.filter((by) => !closed(by.table)) : null;  }  return out;}