/** * `list_records` and `get_record_by_table` over a made table (tables/mod.rs * `list_answer_on`, `list_user`, `list_by_ids`, `get_record_by_table`; * groups.rs `list_in_group` for `where: { group }`, which is how a list such * as the Agents todo list is read). */import { boundedLimit, fail, optionalString, typeData, typeToolContext } from"../../context.ts";import { col, typeOf, typeCond, typeStoredRow } from"../../../store.ts";import { idArg, noLongerHere, resolveTable, tableArg, typeTable } from"./table.ts";import { recordJson } from"./shape.ts";import { clauseSql, equalSql, parseWhere, typeClause } from"./where.ts";import { isDate } from"./values.ts";import { readWindow, windowSql } from"./window.ts";import { isSealedTable, openedJson, openStored, windowFor, windowNote } from"../window.ts";import { blindMatches, cellTexts, queryTokens } from"../../../seal.ts";importtype { TableKeys } from"../../../window.ts";const DEFAULT_PAGE = 50;const MAX_PAGE = 5000;const GROUP_KEY = "group";// ── the order, as SQL over the row ────────────────────────────────────────/** A byte-order comparison, for the few in-memory sorts left (a group's members by place). */function cmp(a: unknown, b: unknown): number {const x = String(a ?? "");const y = String(b ?? "");return x < y ? -1 : x > y ? 1 : 0;}/** * A made table's order (`list_user`), as an ORDER BY: a hand order (nulls * last, then made first); else its `sort` (empty as null, nulls last, text * without case, a tie column); else its date, newest first; else the latest * written. SQLite orders the values a row keeps by type — null, then numbers * (a bool its 1 or 0), then text — as the Rust table's columns order. *//** From this many live rows a table is paged along an index on its order (Store.selectOrdered). */exportconst ORDER_INDEX_ROWS = 20_000;exportfunction orderSql(t: Table, asked = t.sort): string {const order = t.order;if (order) return`${col(order)} IS NULL, ${col(order)}, created_at, id`;// A sealed sort is the device's (R3, seal/default.json sorted_on_device): the object holds no word to order by.const sort = asked && !t.sealed(asked.column) ? { ...asked, tie: asked.tie && !t.sealed(asked.tie) ? asked.tie : undefined } : null;if (sort) {const term = (key: string, descending: boolean): string => `NULLIF(${col(key)}, '') IS NULL, NULLIF(${col(key)}, '') COLLATE NOCASE ${descending ? "DESC" : "ASC"}`;const terms = [term(sort.column, sort.descending === true)];if (sort.tie) terms.push(term(sort.tie, sort.tie_descending ?? sort.descending === true));return`${terms.join(", ")}, updated_at DESC, id`; }if (t.date) return`${col(t.date)} IS NULL, ${col(t.date)} DESC, updated_at DESC, id`;return"updated_at DESC, id";}// ── projects ──────────────────────────────────────────────────────────────/** An active project: its status `active` or not said. */const ACTIVE: Cond = { sql: `COALESCE(${col("status")}, 'active') = 'active'`, args: [] };/** `resolve_project`: an active project by its slug (or its id), or the refusal naming the ones there are. */exportfunction resolveProject(ctx: ToolContext, asked: string): string {if (!ctx.defs().table("project")) fail("this workspace has no projects yet — list_projects to confirm, create_project to start one");// Through the call's view, never the store: a sealed project's slug is read opened (tools/window.ts withOpenProjects).const active = [...ctx.scan("project", [ACTIVE])].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id));const found = active.find((p) => p.id === asked) ?? active.find((p) => p.data.slug === asked);if (found) return found.id;const known: string[] = [];for (const p of active) if (typeof p.data.slug === "string" && p.data.slug) known.push(p.data.slug);if (!known.length) fail("this workspace has no projects yet — list_projects to confirm, create_project to start one"); fail(`unknown project ${JSON.stringify(asked)} — projects are: ${known.join(", ")}`);}// ── narrowing, as SQL ─────────────────────────────────────────────────────/** `LIKE '%word%'` with its wildcards taken literally: a substring, ASCII case-insensitive, as SQLite's LIKE is. */exportconst likePattern = (word: string): string => `%${word.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;/** Every word of `query` in some searchable column. */function querySql(t: Table, query: string): Cond {const columns = t.searchable;const words = query.split(/\s+/).filter(Boolean);if (!columns.length) return { sql: "0", args: [] };const one = columns.map((k) => `(${typeOf(k)} = 'text' AND ${col(k)} LIKE ? ESCAPE '\\')`).join(" OR ");return { sql: words.map(() => `(${one})`).join(" AND "), args: words.flatMap((w) => columns.map(() => likePattern(w))) };}/** The same words, held against a row already read (a group's members). */function matchesQuery(t: Table, data: Data, query: string): boolean {const columns = t.searchable;const fold = (s: string) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());return ( columns.length > 0 && query .split(/\s+/) .filter(Boolean) .every((word) => columns.some((k) => typeof data[k] === "string" && fold(data[k] as string).includes(fold(word)))) );}/** A row the archive keeps (`list_user`'s archive test, the builtins' status one), as SQL. */function archivedSql(t: Table): string {const a = t.archive;if (!a) return"0";if ("status"in a) return`COALESCE(${col("status")}, '') = 'archived'`;return`COALESCE(${col(a.column)}, '') NOT IN ('', 0)`;}/** Never a binned row: one whose bin column holds a day. */exportfunction liveSql(t: Table): Cond[] {const b = t.binColumn;return b ? [{ sql: `NOT (${typeOf(b)} = 'text' AND ${col(b)} <> '')`, args: [] }] : [];}function pageArg(args: Data): number {const v = args.page;if (v === undefined || v === null) return0;if (typeof v !== "number" || !Number.isInteger(v) || v < 0) fail("page is the number of records to skip, 0 or more");return v;}/** The table's `shows`: default clauses on every column the ask's `where` does not name itself. */function shown(t: Table, asked: Clause[]): Clause[] {const shows = t.raw.shows;if (!shows) return [];return parseWhere(t, shows).filter((c) => !asked.some((a) => a.column === c.column));}/** A tool view of this table: its `read.where` narrows and its `sort` orders (`as_view_reads`); one the table has none of is refused. */function viewOf(ctx: ToolContext, t: Table, named: string): { where: unknown; sort: Table["sort"] } {const [tool, id] = named.includes("/") ? [named.slice(0, named.indexOf("/")), named.slice(named.indexOf("/") + 1)] : [null, named];for (const def of ctx.store.definitions("tool")) {if (tool !== null && def.id !== tool && def.key !== tool) continue;const views = Array.isArray(def.views) ? (def.views asData[]) : [];for (const v of views) {const read = (v.read ?? {}) asData;if (v.id !== id || read.table !== t.id) continue;// A view narrowed once its rows open on the phone (Health's Sleep, by a// sealed column) cannot be read here: the object holds those rows sealed.// Its `opened.tie` orders only rows its clear sort holds alike, so a view// with a tie alone reads by that sort.const opened = v.opened as { where?: unknown } | null | undefined;if (opened?.where && typeof opened.where === "object" && Object.keys(opened.where asData).length > 0) fail(`the view ${JSON.stringify(id)} is narrowed on the owner's phone once its ${t.plural.toLowerCase()} open: read ${t.plural.toLowerCase()} here by their clear columns (${t.date ?? "their key"}) instead`);return { where: read.where ?? null, sort: (v.sort asTable["sort"]) ?? t.sort }; } } fail(`${t.plural} have no view ${JSON.stringify(named)}`);}// ── period ────────────────────────────────────────────────────────────────const PERIODS = ["this_month", "today", "tomorrow", "next_7_days", "next_day", "this_year"];function addDay(day: string, n: number): string {const d = newDate(`${day}T00:00:00Z`); d.setUTCDate(d.getUTCDate() + n);return d.toISOString().slice(0, 10);}/** The records whose own date falls in the period, as SQL; `next_day` asks the table for its first day after today. */function periodSql(ctx: ToolContext, t: Table, args: Data): Cond {const period = args.period;if (typeof period !== "string" || !PERIODS.includes(period)) fail("period is this_month, today, tomorrow, next_7_days, next_day or this_year");const today = optionalString(args, "today");if (!today) fail("a period is read from today: say today");if (!isDate(today)) fail("today is a day, YYYY-MM-DD");const date = t.date;if (!date) fail(`${t.plural} have no date a period can keep`);const text = `${typeOf(date)} = 'text'`;const day = `substr(${col(date)}, 1, 10)`;switch (period) {case"this_month":return { sql: `${text} AND substr(${col(date)}, 1, 7) = ?`, args: [today.slice(0, 7)] };case"this_year":return { sql: `${text} AND substr(${col(date)}, 1, 4) = ?`, args: [today.slice(0, 4)] };case"today":return { sql: `${text} AND ${day} = ?`, args: [today] };case"tomorrow":return { sql: `${text} AND ${day} = ?`, args: [addDay(today, 1)] };case"next_7_days":return { sql: `${text} AND ${day} >= ? AND ${day} <= ?`, args: [today, addDay(today, 6)] };default: {const next = ctx.store.value(t.id, `MIN(${day})`, [...liveSql(t), { sql: `${text} AND ${day} > ?`, args: [today] }]);returntypeof next === "string" ? { sql: `${text} AND ${day} = ?`, args: [next] } : { sql: "0", args: [] }; } }}// ── list_records ──────────────────────────────────────────────────────────const ID_REFUSED_BESIDE = ["project", "query", "where", "since", "until", "page", "limit", "section", "day"];/** At most this many ids a blind query reads per column before the page is cut. */const BLIND_IDS = 5000;/** The blind columns' tokens for `query`, each column's list (a column whose query keeps no word is left out). */asyncfunction blindQuery(t: Table, keys: TableKeys, query: string): Promise<{ column: string; tokens: string[] }[]> {const out: { column: string; tokens: string[] }[] = [];for (const column of t.def.seal?.blind ?? []) {const tokens = await queryTokens(keys.bk, column, query);if (tokens.length) out.push({ column, tokens }); }return out;}/** In a window: the sealed rows whose blind tokens hold every query word in one column, as SQL over their ids. */exportasyncfunction blindSql(ctx: ToolContext, t: Table, keys: TableKeys, query: string): Promise<Cond> {const ids = newSet<string>();for (const q ofawait blindQuery(t, keys, query)) for (const id of ctx.store.blindIds(t.id, q.tokens, t.date, BLIND_IDS)) ids.add(id);return { sql: "id IN (SELECT value FROM json_each(?))", args: [JSON.stringify([...ids])] };}/** * In a window, a hit the tokens let by is held to the words in plaintext * (`blindMatches`: each word whole, the last as a word's start): the column * that holds them, or null. A truncated token's collision and a longer word * behind the last word's six-letter prefix token are dropped here. */exportfunction blindVerified(t: Table, query: string, data: Data): string | null {for (const column of t.def.seal?.blind ?? []) {if (blindMatches(cellTexts(data[column]).join("\n"), query)) return column; }returnnull;}exportasyncfunction listRecords(ctx: ToolContext, args: Data): Promise<Data> {const asked = tableArg(args);const t = resolveTable(ctx, asked, args.table);// A sealed table's rows are read in a window, opened with its keys; a count or the last change reads only clear columns.const sealedQuery = isSealedTable(t) && typeof args.query === "string" && args.query.trim() !== "";// The view first: one the object cannot read is refused before a window is asked.let sort = t.sort;let viewWhere: unknown = null;const view = optionalString(args, "view");if (view) ({ where: viewWhere, sort } = viewOf(ctx, t, view));const keys = (args.last_changed === true || args.count_only === true) && !sealedQuery ? null : await windowFor(ctx, t, "list_records");if (args.last_changed === true) {if (Object.keys(args).some((k) => !["table", "last_changed", "timezone", "today"].includes(k))) fail("last_changed reads the whole table; ask without filters or paging");const latest = ctx.store.value(t.id, "MAX(updated_at)", [...liveSql(t), { sql: `NOT (${archivedSql(t)})`, args: [] }]);return { table: t.id, last_changed: typeof latest === "string" ? latest : null }; }if (args.from !== undefined || args.to !== undefined) fail("A date window applies to a monthly Money runway view.");if (args.count_only !== undefined && args.count_only !== null && typeof args.count_only !== "boolean") fail("count_only is true or false");if (args.section !== undefined && args.section !== null) {if (args.archived === true) fail(`The archived ${t.plural.toLowerCase()} are not read in sections; ask without section`); fail(`${t.plural} is not read in sections; ask without section`); }// `where: { group }` alone reads that group's records (groups.rs).const where = args.where;const group = where && typeof where === "object" && !Array.isArray(where) && !t.column(GROUP_KEY) ? (where asData)[GROUP_KEY] : undefined;if (typeof group === "string" && group.trim()) {if (args.archived === true) fail("A group lists its live records; ask without archived");return listInGroup(ctx, t, group.trim(), args, keys); }let archived = false;if (args.archived === true) {if (!t.archive) fail(`${t.plural} are never archived`);if (args.ids !== undefined && args.ids !== null) fail("ids names the records itself; ask without archived"); archived = true; } elseif (args.archived !== undefined && args.archived !== null && args.archived !== false) fail("archived is true or false");if (args.ids !== undefined && args.ids !== null) return listByIds(ctx, t, args, keys);const clauses = parseWhere(t, where);const all = [...clauses, ...shown(t, clauses), ...parseWhere(t, viewWhere)];const conds: Cond[] = [...liveSql(t), { sql: archived ? archivedSql(t) : `NOT (${archivedSql(t)})`, args: [] }];const projectArg = optionalString(args, "project");if (projectArg) {if (!t.project) fail(`${t.plural} do not belong to projects`); conds.push(equalSql(t.project, resolveProject(ctx, projectArg))); }const query = optionalString(args, "query");if (query !== null) {const words = querySql(t, query);// In a window, a sealed table's words are found by their blind tokens, beside its clear columns' words.if (keys) {const blind = await blindSql(ctx, t, keys, query); conds.push({ sql: `((${words.sql}) OR (${blind.sql}))`, args: [...words.args, ...blind.args] }); } else conds.push(words); }const now = Date.parse(ctx.now);for (const c of all) conds.push(clauseSql(c, now));if (args.period !== undefined && args.period !== null) conds.push(periodSql(ctx, t, args)); conds.push(...windowSql(t, readWindow(ctx, args)));if (args.count_only === true) {if (Object.keys(args).some((k) => !["table", "count_only", "today", "timezone", "from", "to"].includes(k))) fail("count_only reads the whole table; ask without filters or paging");return { table: t.id, total: ctx.store.count(t.id, conds) }; }const page = pageArg(args);// A whole table asked for (no condition but the always-true ones): its count is the one row_counts keeps, and a big// one is paged along an index on its order (Store.selectOrdered).const whole = conds.every((c) => c.sql === "NOT (0)" && !c.args.length);const held = whole ? ctx.store.liveCount(t.id) : null;const total = held ?? ctx.store.count(t.id, conds);if (archived && args.limit === 0) return { table: t.id, records: [], next_page: null, total };const limit = boundedLimit(args, DEFAULT_PAGE, MAX_PAGE);const big = (held ?? total) >= ORDER_INDEX_ROWS;const slice = (big ? ctx.store.selectOrdered(t.id, conds, orderSql(t, sort), limit + 1, page) : null) ?? ctx.store.select(t.id, conds, orderSql(t, sort), limit + 1, page);const more = slice.length > limit;let records = slice.slice(0, limit);if (keys && query !== null) {// A sealed hit holds the words once opened, or it was a token's collision and is dropped.const kept: StoredRow[] = [];for (const r of records) {const { row, parked } = await openStored(ctx, t, keys, r);if (parked || row === r || blindVerified(t, query, row.data) !== null) kept.push(r); } records = kept; }return { table: t.id, records: await openAll(ctx, t, keys, records), next_page: more ? page + slice.slice(0, limit).length : null, total, ...windowNote(keys) };}/** Records as a read answers them, opened in a window. */asyncfunction openAll(ctx: ToolContext, t: Table, keys: TableKeys | null, rows: StoredRow[]): Promise<Data[]> {if (!keys) return rows.map((r) => recordJson(t, r));const out: Data[] = [];for (const r of rows) out.push(await openedJson(ctx, t, keys, r));return out;}asyncfunction listByIds(ctx: ToolContext, t: Table, args: Data, keys: TableKeys | null): Promise<Data> {for (const key of ID_REFUSED_BESIDE) if (args[key] !== undefined && args[key] !== null) fail(`ids names the records itself; ask without ${key}`);const ids = args.ids;if (!Array.isArray(ids) || ids.length < 1 || ids.length > 5000) fail("ids is a list of 1 to 5000 record ids");const seen = newSet<string>();const records: StoredRow[] = [];for (const raw of ids) {if (typeof raw !== "string" || !raw.trim()) fail("each of ids is one record id");const id = raw.trim();if (seen.has(id)) continue; seen.add(id);const row = ctx.get(t.id, id);if (row && t.binned(row) === null) records.push(row); }return { table: t.id, records: await openAll(ctx, t, keys, records), next_page: null, total: records.length, ...windowNote(keys) };}// ── groups ────────────────────────────────────────────────────────────────const GROUPS = "record_group";const MEMBERS = "group_member";/** `list_records { table, where: { group }, query?, page?, limit? }`: the group's live members, in its own order. */asyncfunction listInGroup(ctx: ToolContext, t: Table, groupId: string, args: Data, keys: TableKeys | null): Promise<Data> {const asked = args.where asData;const more = Object.keys(asked).length > 1;const other = ["ids", "project", "since", "until"].find((k) => args[k] !== undefined && args[k] !== null) ?? (more ? "another where" : null);if (other) fail(`group names the records itself; ask without ${other}`);const held = ctx.defs().table(GROUPS) ? ctx.get(GROUPS, groupId) : null;// A sealed group (its name and filter) is read inside the owner's window, as the records are.const groups = held ? resolveTable(ctx, GROUPS) : null;const group = held && groups && isSealedTable(groups) ? (await openStored(ctx, groups, await windowFor(ctx, groups, "list_records in a group"), held)).row : held;const gone = !group || (typeof group.data.deleted_at === "string" && group.data.deleted_at !== "");if (gone) fail("There is no such group. It may have been deleted.");if (group.data.table_id !== t.id) fail(`That group is not a group of ${t.plural}.`);const filter = filterOf(group.data.filter);if (filter) {// A filter group is the table's list narrowed by its filter.const { where: _where, ...rest } = args;void _where;return listRecords(ctx, { ...rest, where: filter }); }const page = pageArg(args);const limit = boundedLimit(args, DEFAULT_PAGE, MAX_PAGE);const placed = ctx .where(MEMBERS, "group", groupId) .filter((m) => typeof m.data.record_id === "string" && typeof m.data.place === "number") .sort((a, b) => (a.data.place as number) - (b.data.place as number) || cmp(a.data.record_id, b.data.record_id));const seen = newSet<string>();let members: StoredRow[] = [];for (const m of placed) {const id = m.data.record_id as string;if (seen.has(id)) continue; seen.add(id);const row = ctx.get(t.id, id);if (row && t.binned(row) === null) members.push(row); }const query = optionalString(args, "query");if (query) members = members.filter((r) => matchesQuery(t, r.data, query));const total = members.length;const records = members.slice(page, page + limit);return { table: t.id, records: await openAll(ctx, t, keys, records), next_page: page + records.length < total ? page + records.length : null, total, ...windowNote(keys) };}/** A filter group keeps a `where` as JSON in its `filter` column. */function filterOf(v: unknown): Data | null {if (v && typeof v === "object" && !Array.isArray(v)) return v asData;if (typeof v !== "string" || !v.trim()) returnnull;try {const parsed: unknown = JSON.parse(v);return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed asData) : null; } catch { fail("this group's filter does not read as a where"); }}// ── get_record_by_table ───────────────────────────────────────────────────exportasyncfunction getRecordByTable(ctx: ToolContext, args: Data): Promise<Data> {const t = resolveTable(ctx, tableArg(args), args.table);const id = idArg(args);const keys = await windowFor(ctx, t, "get_record_by_table");const row = ctx.get(t.id, id);if (!row) fail(noLongerHere(t));const out = { ...(await openedJson(ctx, t, keys, row)), ...windowNote(keys) };const computed = t.columns.filter((c) => c.computed !== undefined && c.computed !== null).map((c) => c.key);if (computed.length) out.computed_unavailable = computed; out.edited_by_person_id = null; out.edited_by_photo_key = null;return out;}