Cotton code
283 lines · 17.4 KB · TypeScriptRaw
/** Definition writes shared by the owner's MCP tool and the phone's act. * Table storage stays fixed; only its look is overlaid. Tools, boards and * themes are replaced whole, with the same validation on either path. */import { fail, type Data, type ToolContext } from "./mcp/context.ts";import { definitionProblem, tableProblem } from "./definitions.ts";import { sealedSetProblem, toolSealProblem } from "./seal.ts";import { resolveTable, type Table } from "./mcp/tools/records/table.ts";import { KITS, PERSONAL } from "./kits.ts";import { faceProblem } from "./faces.ts";import { withoutEmpty } from "./fan.ts";import definitionKeys from "./definition_keys.json";/** * `definable`: a key's definition write is held to it for every table it touches (ADMIN KEYS 4): a table that holds who * may do what is never a key's, and a key with a list reshapes only a table it reads (update_definition is how a list * looks, named in `allow.acts`, not a write of its rows). */export type DefinitionWriter = Pick<ToolContext, "store" | "defs"> & { write<T>(fn: () => T): T; byKey?: boolean; definable?: (table: string) => string };/** Every table id a whole definition (a tool, board or theme) names anywhere, at any depth (`table` keys and view reads). */function tablesNamed(doc: unknown, known: (id: string) => boolean, out = new Set<string>()): Set<string> {  if (Array.isArray(doc)) for (const v of doc) tablesNamed(v, known, out);  else if (doc && typeof doc === "object") {    for (const [k, v] of Object.entries(doc as Data)) {      if ((k === "table" || k === "tables") && typeof v === "string" && known(v)) out.add(v);      else if (k === "tables" && Array.isArray(v)) for (const t of v) if (typeof t === "string" && known(t)) out.add(t);      tablesNamed(v, known, out);    }  }  return out;}/** ADMIN KEYS 4: a key's whole-definition write (or removal) is held to `definable` for every table it names. */function guardTables(ctx: DefinitionWriter, ...docs: unknown[]): void {  if (!ctx.definable) return;  const known = (id: string) => ctx.store.definitions("table").some((d) => d.id === id);  for (const doc of docs) for (const table of tablesNamed(doc, known)) ctx.definable(table);}/** * THE ONE LIST of what in a table's definition decides access (ADMIN KEYS 1b, 4): never a key's to set or change, at * update_definition or the definition act. A tool's context is always a key's; the act's says `byKey` when a token sent it. * - `visibility`: who may read or write the table (owner, staff, public, mine(...)); * - `producer`: the one token whose writes fill the readonly columns (values.ts `authored`); * - a column's `readonly`: that only the producer writes it. * Everything else a person may set is look. `seal` (who can read it at all) and a column's `computed` are FIXED already: * nobody changes them here. */export const ACCESS_KEYS: ReadonlySet<string> = new Set(["visibility", "producer"]);export const ACCESS_COLUMN_KEYS: ReadonlySet<string> = new Set(["readonly"]);/** The access key a key's write would change on table `t`, or null: the table's own, then each column's. */function accessChanged(t: Table, args: Data): string | null {  const own = Object.keys(args).find((k) => ACCESS_KEYS.has(k) && !same(args[k] ?? undefined, t.raw[k] ?? undefined));  if (own) return own;  if (!Array.isArray(args.columns)) return null;  for (const entry of args.columns as unknown[]) {    const said = entry && typeof entry === "object" && !Array.isArray(entry) ? (entry as Data) : null;    const theirs = t.columns.find((c) => c.key === said?.key) as Data | undefined;    if (!said || !theirs) continue;    const key = [...ACCESS_COLUMN_KEYS].find((k) => k in said && !same(said[k] ?? undefined, theirs[k] ?? undefined));    if (key) return `${String(said.key)}.${key}`;  }  return null;}function keyWrite(ctx: DefinitionWriter): boolean {  return ctx.byKey ?? "caller" in ctx;}/** The keys that say what a table IS, never how it looks (cotton-core `FIXED_DEFINITION_KEYS`, generated into definition_keys.json), and this object's `internal`. A keep reads every other key but `columns` and `card` as the table's look (src/kit_keep.ts, KEEP_RULE 11). */export const FIXED = new Set([...definitionKeys.fixed, "internal"]);/** A column's look: what a person may set on it (`COLUMN_LOOK_KEYS`). */const COLUMN_LOOK = new Set(definitionKeys.look);/** The keys of a definition a person may write, as they stand (`writable`). */function writable(raw: Data): Data {  const out: Data = {};  for (const [k, v] of Object.entries(raw)) if (!FIXED.has(k)) out[k] = v;  return out;}const q = (s: string) => JSON.stringify(s);/** The marks the ink reads that a table may bind to a command (`card::MARKS`). */const MARKS = new Set(["check"]);/** * Why a table's `marks` cannot stand (`TableDefinition::validate_marks`): * each mark one the ink reads, bound to one of the table's commands that runs * on the record at once — an update that neither asks first nor picks, never * a list's act. Null when they stand. */export function marksProblem(table: Data): string | null {  const marks = table.marks;  if (marks === undefined || marks === null) return null;  if (typeof marks !== "object" || Array.isArray(marks)) return "marks names each mark's command by the mark";  const commands = [...(Array.isArray(table.commands) ? table.commands : []), ...(Array.isArray(table.acts) ? table.acts : [])] as Data[];  for (const [mark, id] of Object.entries(marks as Data)) {    if (!MARKS.has(mark)) return `marks names ${q(mark)}, which is not one of "marks"'s choices`;    const command = commands.find((c) => c.id === id);    if (!command) return `marks.${mark} names ${q(String(id))}, which is not one of the definition's commands`;    const asks = command.kind === "delete" || command.destructive === true;    const picks = ["pick", "picks", "pick_table", "sheet", "list"].some((key) => command[key] !== undefined && command[key] !== null);    if (command.kind !== "update" || asks || picks) return `marks.${mark} needs an update command that does not ask first`;  }  return null;}/** `columns` on a made table: its whole existing list, each column's look overlaid, nothing added, removed or retyped. */function columnsOn(t: Table, value: unknown): Data[] {  if (!Array.isArray(value)) fail("the definition is refused: columns is the table's whole list of existing columns");  const overlays = new Map<string, Data>();  for (const entry of value as unknown[]) {    const said = entry && typeof entry === "object" && !Array.isArray(entry) ? (entry as Data) : null;    const key = typeof said?.key === "string" ? said.key : "";    if (overlays.has(key)) fail(`the definition is refused: column ${q(key)} is named twice`);    const theirs = t.columns.find((c) => c.key === key) as Data | undefined;    if (!theirs) fail(`the definition is refused: ${q(key)} is no column of ${q(t.id)}: columns cannot be added here`);    const changed = !said || Object.entries(said).some(([name, v]) => !COLUMN_LOOK.has(name) && JSON.stringify(theirs[name] ?? null) !== JSON.stringify(v));    if (changed) fail(`the definition is refused: ${q(key)} is a column of ${q(t.id)}: it is never removed or retyped — its name, readonly, format, units, hidden and placeholder are look`);    if (said.hidden === true && key === t.title) fail(`the definition is refused: ${q(key)} is the title of ${q(t.plural)} and is always drawn`);    const overlay: Data = { ...theirs };    for (const look of COLUMN_LOOK) {      if (!(look in said)) continue;      if (said[look] === null) delete overlay[look];      else overlay[look] = said[look];    }    overlays.set(key, overlay);  }  const gone = t.columns.find((c) => !overlays.has(c.key));  if (gone) fail(`the definition is refused: ${q(gone.key)} is a shipped column of ${q(t.id)}: it is never removed — hide it instead`);  return t.columns.map((c) => overlays.get(c.key)!);}/** The kinds a definition merged whole by id may be. */const WHOLE = ["tool", "board", "theme"] as const;/** * A tool, board or theme definition put whole in place of the one with its id * (or added), the rest of its kind left as they are, in one write that moves * the definitions' version and etag; a definition that already reads so * writes nothing. */function putWhole(ctx: DefinitionWriter, kind: (typeof WHOLE)[number], args: Data): Data {  if (args.remove !== undefined) return removeWhole(ctx, kind, args);  const extra = Object.keys(args).find((k) => k !== "kind" && k !== "definition");  if (extra) fail(`a ${kind} is put whole: send kind and definition, not ${q(extra)}`);  const doc = args.definition;  if (kind === "tool" && doc && typeof doc === "object" && !Array.isArray(doc)) {    const tool = doc as Data;    // A view's card is the build's: a tool sent back whole carries each view's    // card as the object holds it; one that names, changes or drops a card is refused.    const heldViews = ctx.store.definitions("tool").find((d) => d.id === tool.id)?.views;    const cards = new Map((Array.isArray(heldViews) ? (heldViews as Data[]) : []).map((v) => [v.id, "card" in v ? v.card : undefined]));    const view = Array.isArray(tool.views)      ? (tool.views as unknown[]).find((v) => {          if (!v || typeof v !== "object" || Array.isArray(v)) return false;          const said = v as Data;          return !same("card" in said ? said.card : undefined, cards.get(said.id));        })      : undefined;    if (view) fail(`tool ${q(String(tool.id))}'s view ${q(String((view as Data).id))}'s card is the build's; the kit names it, so it is not written here`);  }  const problem = definitionProblem(kind, doc) ?? (kind === "tool" ? toolSealProblem(doc as Data, (id) => ctx.defs().table(id)) : null);  if (problem) fail(`the definition is refused: ${problem}`);  // A board is kept without what the object works out for it: a phone sends Home back as it was served.  const definition = kind === "board" ? withoutEmpty(doc as Data) : (doc as Data);  const held = ctx.store.definitions(kind).find((d) => d.id === definition.id) ?? null;  guardTables(ctx, definition, held);  // A phone serialises keys in its own order: the same definition in another order writes nothing.  const changed = !same(held, definition);  if (changed) ctx.write(() => ctx.store.mergeDefinitions(kind, [definition]));  return { kind, id: definition.id, changed, before: held, definition };}export function updateDefinition(ctx: DefinitionWriter, args: Data): Data {  const kind = args.kind ?? "table";  if (kind !== "table" && !WHOLE.includes(kind as (typeof WHOLE)[number])) fail(`kind is table, tool, board or theme; ${JSON.stringify(kind)} is not one`);  if (kind !== "table") return putWhole(ctx, kind as (typeof WHOLE)[number], args);  delete args.kind;  const table = typeof args.table === "string" && args.table.trim() ? args.table.trim() : fail("table is required");  const fixed = Object.keys(args).find((k) => k !== "table" && FIXED.has(k));  if (fixed) fail(`${q(fixed)} cannot be changed here: column types, engines, commands, connections and table identity stay as the table defines them`);  const changed = Object.keys(args)    .filter((k) => k !== "table")    .sort((a, b) => Number(a !== "columns") - Number(b !== "columns"));  const t = resolveTable(ctx, table, args.table);  ctx.definable?.(t.id);  const access = keyWrite(ctx) ? accessChanged(t, args) : null;  if (access) fail(`${q(access)} says who may read or write the table: the owner changes it from their own device, never a key`);  const current = t.raw;  if (!changed.length) return { table, definition: writable(current) };  if (changed.includes("card")) fail(`table ${q(table)}'s card is the build's; the kit names it, so it is not written here`);  if (current.engine !== undefined && current.engine !== null) fail(`table ${q(table)} is kept by an engine; its definition is not written here`);  const merged: Data = { ...current };  for (const key of changed) {    const value = key === "columns" ? columnsOn(t, args.columns) : args[key];    if (value === null) delete merged[key];    else merged[key] = value;  }  const unread = tableProblem(merged);  if (unread) fail(`the definition does not read: ${unread}`);  const marks = changed.includes("marks") ? marksProblem(merged) : null;  if (marks) fail(`the definition is refused: ${marks}`);  // Only what this write says is held to the faces the app draws: a key it leaves stands as it was.  const faces = faceProblem(Object.fromEntries([["id", table], ...changed.map((key) => [key, merged[key]])]));  if (faces) fail(`the definition is refused: ${faces}`);  const next = ctx.store.definitions("table").map((d) => (d.id === table ? merged : d));  const sealing = sealedSetProblem(next, [], ctx.store.definitions("tool"));  if (sealing) fail(`the definition is refused: ${sealing}`);  ctx.write(() => ctx.store.replaceDefinitions("table", next));  // The links index follows the definitions as they now stand.  ctx.defs();  const before: Data = {};  for (const key of changed) before[key] = current[key] === undefined ? null : current[key];  return { table, changed, before, definition: writable(merged) };}/** * A tool, board or theme the object holds taken out whole, by id, in one * write that moves the definitions' version and etag: every phone stops * drawing it on its next fetch. One the kit still ships is the kit's to say * and is refused here (it leaves the kit first); one the kit gave and no * longer ships stays removed, since kit_keep gives a definition once. */function removeWhole(ctx: DefinitionWriter, kind: (typeof WHOLE)[number], args: Data): Data {  const extra = Object.keys(args).find((k) => k !== "kind" && k !== "remove");  if (extra) fail(`a ${kind} is removed by id: send kind and remove, not ${q(extra)}`);  const id = typeof args.remove === "string" && args.remove.trim() ? args.remove.trim() : fail("remove names the id to take out");  if (kind === "tool" && [...PERSONAL.own, ...PERSONAL.tools].some((t) => String(t.id) === id)) fail(`the tool ${q(id)} is one the kit ships: it is the kit's to say, so it leaves the kit before it leaves an object`);  // A shell board is the app's own screen, laid by the kit on every keep (src/kit_keep.ts): taken out, the phone would lose it until the next kit.  if (kind === "board" && (KITS.shell?.boards ?? []).some((b) => String(b.id) === id)) fail(`the board ${q(id)} is one of the app's shell screens: the kit lays it, so it never leaves an object`);  const held = ctx.store.definitions(kind);  const before = held.find((d) => d.id === id) ?? null;  if (!before) fail(`no ${kind} ${q(id)} is held`);  guardTables(ctx, before);  ctx.write(() => ctx.store.replaceDefinitions(kind, held.filter((d) => d.id !== id)));  return { kind, id, removed: true, before };}/** JSON objects compare by content, independent of a phone's key order. */function same(a: unknown, b: unknown): boolean {  if (a === b) return true;  if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;  if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((v, i) => same(v, b[i]));  const left = a as Data, right = b as Data;  return Object.keys(left).length === Object.keys(right).length && Object.keys(left).every((k) => Object.hasOwn(right, k) && same(left[k], right[k]));}/** A phone sends a whole table; identity and storage keys must still match. */export function definitionAct(ctx: DefinitionWriter, args: Data): Data {  const { base, ...write } = args;  const kind = write.kind;  const doc = write.definition;  const definition = doc && typeof doc === "object" && !Array.isArray(doc) ? doc as Data : null;  const id = typeof write.remove === "string" ? write.remove : definition?.id;  if (kind === "tool" || kind === "board" || kind === "theme" || kind === "table") {    const held = ctx.store.definitions(kind).find((d) => d.id === id) ?? null;    // The last definition this phone received is its precondition. Stale    // writes answer the authority's whole version; the next fetch lays it.    // Home is served with a computed empty-tools list. That read decoration    // changing is not an edit to the person's board.    const comparable = (value: unknown) => kind === "board" && value && typeof value === "object" && !Array.isArray(value) ? withoutEmpty(value as Data) : value;    if (Object.hasOwn(args, "base") && !same(comparable(base), comparable(held))) return { kind, id, conflict: true, definition: held };  }  if (kind !== "table") return updateDefinition(ctx, write);  if (write.remove !== undefined) fail("a table is never removed — hide it instead");  if (!definition || typeof definition.id !== "string") fail("the definition does not read: it names no id");  const extra = Object.keys(write).find((key) => key !== "kind" && key !== "definition");  if (extra) fail(`a table is put whole: send kind and definition, not ${q(extra)}`);  const current = resolveTable(ctx, definition.id).raw;  const patch: Data = { table: definition.id };  for (const key of new Set([...Object.keys(current), ...Object.keys(definition)])) {    if (same(current[key], definition[key])) continue;    if (FIXED.has(key)) fail(`${q(key)} cannot be changed here: column types, engines, commands, connections and table identity stay as the table defines them`);    patch[key] = definition[key] ?? null;  }  const result = updateDefinition(ctx, patch);  return { ...result, kind, definition: ctx.store.definitions("table").find((d) => d.id === definition.id) };}