Cotton code
962 lines · 48.0 KB · TypeScriptRaw
/** * gen-kind — ONE DECLARATION PER RECORD KIND, and the generator writes every * mechanical seam the gates name. * * WHY. Adding a kind to Cotton touched thirty-nine files when `device` joined * (#777) and sixty-five when `secret` did (#598): the enum variant and its * facility enums, the registry entry, the two sentences in `words.rs`, the * table's DDL with its indexes, search index, history triggers and author * index, the sync codec (`TableSpec`), the schema version, the CHECK constraints * of four facility tables, the search lanes, the bin source, the tool-surface * grid, and the counts a dozen tests pin. Every one of them is * a pure function of the same handful of facts, and the day cost was typing * them twenty times without drift. * * WHAT THIS IS, AND IS NOT. It is a SCAFFOLD, run once per kind: it reads a * JSON declaration, inserts code at the `// gen-kind: <seam>` anchors the * Rust and Swift files carry, and bumps the lengths and counts those files * pin. It is not a framework and it generates * no behaviour — the primitives registry stays the runtime truth * (`crates/cotton-core/src/primitives.rs`, "a REGISTRY, not a framework"), and * after the run the checked-in code is the declaration. The gates are what * hold the result: `primitives_tests.rs`, `tool_surface_tests.rs`, * `schema_snapshot.rs`, `totality.rs` and the rest read the seams this wrote. * * WHAT IT REFUSES, AND WHY EACH IS A REFUSAL RATHER THAN A GUESS. Four * facilities are decisions with a hand-written reader behind them and cannot be * scaffolded honestly: `embedded` (chunk_tests pins a digest per source), * `summarized` (`rules::summaries` names where each summary lives), * `route_target` (the classifier and `capture_links` decide where a capture * lands), `project_linkable` (`project_sections` and the project page's * `kind_source` pick a section and its columns), `shareable` (an * `origin_handle` column and the consent question). The declaration gives each * a written reason instead — the registry's rule that a "no" is never a * missing entry. The LIKE search lane is refused for the same reason (two * bespoke statements today; a third is written beside them). * * WHAT STAYS BY HAND, and is printed at the end of a run: the MCP tools the * verb grid names (their `ToolDef`, handler and dispatch arm), the phone's * screens (`Route.swift`, `RouteTier`, `RouteColumns`, `RouteScreen`, * `RecordRoute`, Kotlin's `Route.kt`), and the schema snapshot, which is * rewritten only by its own ignored test. A generator that wrote a screen would * be writing a placeholder screen. * * ANCHORS. Every insertion point is a comment `// gen-kind: <name>` placed at * the end of the array, enum or match it belongs to; `SEAMS` below is the one * list of them, and `scripts/__tests__/gen-kind.test.ts` holds every anchor to * exactly one occurrence in the real tree, so a refactor that loses one is red * before the next kind finds out. * * THE FRESH LINE (9a). The store's ladder is ONE rung, * `Migration::at(SCHEMA_VERSION, SCHEMA_DDL)`: there are no migrations. So a * new kind lands as DDL and a version bump ONLY — its constants in * `schema/ddl.rs`, the same constants appended to `SCHEMA_DDL` by phase, the * facility CHECKs widened in the constants a fresh file is built from, and * `pub const SCHEMA_VERSION: u32 = N;` raised by one. It writes no rung, no * per-version `*_DDL` statement list, no carry/rebuild of the CHECKed tables * and no migrator test: an old file is refused, never climbed. What it hands * back instead is the SHAPE ledger line for the change * (`SHAPE <date> <pr> — <table>: absent → <columns>, an old file has no rows`), * which the run prints for the PR to record. */import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { dirname, join } from "node:path";// ---- the declaration --------------------------------------------------------export type Codec = "Text" | "Int" | "Real" | "Bool" | "Json" | "MoneyMinor" | "DecimalText" | "Timestamp";export interface ColumnDecl {  /** snake_case column name. */  name: string;  /** Everything after the name in the CREATE, e.g. `TEXT NOT NULL`. Default `TEXT`. */  sql?: string;  codec: Codec;  /** A comment written beside the column in the sync codec, one line. */  comment?: string;}/** `true` = participates; a sentence = the written reason it does not. */export type Membership = true | string;export type Verb = string | { not: string };export type HistoryForm = "Text" | "Prose" | "Moment" | "Day" | "Flag" | "Number" | "List";export interface KindDeclaration {  /** The wire string, snake_case: `alarm`, `person_note`. */  kind: string;  /** The Rust/Swift identifier. Derived from `kind` when absent. */  variant?: string;  /** The synced table, `cotton_<plural>`. */  table: string;  /** One or two sentences: why this is a kind. Becomes the enum doc and the rung's comment. */  why: string;  /** The kind's own columns — `id`, `workspace_id`, the stamps and (when binnable) `trashed_at` are implied. */  columns: ColumnDecl[];  /** The column a list, the bin and a search hit show as the row's title. */  title_column: string;  /** Table-level CHECKs, each the text inside `CHECK (...)`. */  checks?: string[];  /** Further indexes, as whole statements. The author index is implied. */  indexes?: string[];  facilities: {    fts: Membership;    embedded: string;    search: "fts" | string;    versioned: Membership;    commentable: Membership;    summarized: string;    project_linkable: string;    linkable: Membership;    route_target: string;    addressable: Membership;    binnable: Membership;    shareable: string;  };  /** The columns the search index covers, title first. Default `[title_column]`. */  fts_columns?: string[];  /** History, required when `versioned` is true: what the screen draws, and what a restore writes back. */  history?: {    fields: { column: string; label: string; form?: HistoryForm }[];    restore: string[] | string;  };  words: { meaning: string; feeds: string };  /** A navigator section key (`writing`, `calendar`, …) or the reason the kind is machinery. */  section: string | { machinery: string };  verbs: { create: Verb; list: Verb; get: Verb; update: Verb; remove: Verb };  /** The phone's screen family the table invalidates. Default: the kind. */  screen_family?: string;  /** Optional screens. `list` reads through the list verb's tool; `page` through the get verb's. */  routes?: { list: string; page?: string };}const SNAKE = /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/;/** The words `words_tests::every_feeds_line_names_a_source` accepts as naming a source. */const FEEDS_NAMES_A_SOURCE = ["_", "screen", "import", "worker", "router", "sweep", "pipeline", "share sheet", "picker", "keyboard", "relay", "editor", "pass", "registration"];export function pascal(snake: string): string {  return snake    .split("_")    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))    .join("");}export function screamingSnake(snake: string): string {  return snake.toUpperCase();}function isReason(value: unknown): value is string {  return typeof value === "string" && value.trim().length >= 10 && !/\b(TODO|TBD|FIXME)\b/.test(value);}/** Every rule the declaration must meet before a byte is written. */export function validate(decl: KindDeclaration): string[] {  const problems: string[] = [];  const need = (cond: boolean, message: string) => {    if (!cond) problems.push(message);  };  need(SNAKE.test(decl.kind ?? ""), `kind must be snake_case, got ${JSON.stringify(decl.kind)}`);  need(typeof decl.table === "string" && /^cotton_[a-z0-9_]+$/.test(decl.table), `table must be cotton_<name>, got ${JSON.stringify(decl.table)}`);  need(isReason(decl.why), "why: one real sentence about why this is a kind");  need(Array.isArray(decl.columns) && decl.columns.length > 0, "columns: at least one column of the kind's own");  const implied = new Set(["id", "workspace_id", "created_at", "updated_at", "_hlc", "_born", "trashed_at"]);  const seen = new Set<string>();  for (const column of decl.columns ?? []) {    need(SNAKE.test(column.name ?? ""), `column name must be snake_case, got ${JSON.stringify(column.name)}`);    need(!implied.has(column.name), `column ${column.name} is implied — leave it out`);    need(!seen.has(column.name), `column ${column.name} is declared twice`);    seen.add(column.name);    need(      ["Text", "Int", "Real", "Bool", "Json", "MoneyMinor", "DecimalText", "Timestamp"].includes(column.codec),      `column ${column.name}: codec must be a cotton-store Codec, got ${JSON.stringify(column.codec)}`,    );  }  need(seen.has(decl.title_column), `title_column ${JSON.stringify(decl.title_column)} is not a declared column`);  const f = decl.facilities ?? ({} as KindDeclaration["facilities"]);  const yesOrReason = (name: keyof KindDeclaration["facilities"]) => {    const value = f[name];    need(value === true || isReason(value), `facilities.${name}: true or a written reason of at least ten characters`);  };  const reasonOnly = (name: keyof KindDeclaration["facilities"], seam: string) => {    const value = f[name];    need(isReason(value), `facilities.${name}: a written reason only — a "yes" is hand-written (${seam})`);  };  yesOrReason("fts");  yesOrReason("versioned");  yesOrReason("commentable");  yesOrReason("linkable");  yesOrReason("addressable");  yesOrReason("binnable");  reasonOnly("embedded", "rules/chunk.rs EMBED_SOURCES and the digest chunk_tests pins per source");  reasonOnly("summarized", "rules/summaries.rs names where each summary lives");  reasonOnly("route_target", "routing/classify.rs and rules/capture_links.rs decide where a capture lands");  reasonOnly("project_linkable", "rules/project_sections.rs and handlers/projects/kinds.rs pick a section and its columns");  reasonOnly("shareable", "an origin_handle column and the consent question the sharing design asks");  need(    f.search === "fts" || isReason(f.search),    'facilities.search: "fts" or a written reason — a LIKE lane is hand-written beside the two that exist',  );  if (f.search === "fts") need(f.fts === true, "facilities.search is fts, so facilities.fts must be true");  if (f.fts === true) {    const columns = decl.fts_columns ?? [decl.title_column];    need(columns.length > 0, "fts_columns: at least one column");    for (const column of columns) need(seen.has(column), `fts_columns names ${column}, which is not a declared column`);    need(columns[0] === decl.title_column, "fts_columns: the title column comes first (bm25 weights it double)");  }  if (f.versioned === true) {    need(decl.history !== undefined, "history: required when versioned — what the screen draws, and what a restore writes back");    for (const field of decl.history?.fields ?? []) {      need(seen.has(field.column), `history names ${field.column}, which is not a declared column`);      need(typeof field.label === "string" && field.label.length > 0, `history field ${field.column} needs a label`);    }    const restore = decl.history?.restore;    need(      Array.isArray(restore) ? restore.every((column) => seen.has(column)) : isReason(restore),      "history.restore: the columns a restore writes back, or the written reason it writes none",    );  }  need(isReason(decl.words?.meaning), "words.meaning: one sentence saying what one of these is");  need(isReason(decl.words?.feeds), "words.feeds: one sentence saying what creates rows of this kind");  need(    FEEDS_NAMES_A_SOURCE.some((word) => (decl.words?.feeds ?? "").includes(word)),    "words.feeds: name the source — a tool (snake_case), a screen, a worker, an import… (words_tests::every_feeds_line_names_a_source)",  );  if (typeof decl.section === "string") {    need(SNAKE.test(decl.section), `section must be a SectionKey string, got ${JSON.stringify(decl.section)}`);  } else {    need(isReason(decl.section?.machinery), "section.machinery: the written reason the kind is never a section");  }  for (const verb of ["create", "list", "get", "update", "remove"] as const) {    const cell = decl.verbs?.[verb];    need(      (typeof cell === "string" && SNAKE.test(cell)) || (typeof cell === "object" && cell !== null && isReason(cell.not)),      `verbs.${verb}: a tool name or { not: <written reason> }`,    );  }  if (decl.routes) {    need(/^\/[a-z0-9/[\]-]+$/.test(decl.routes.list), `routes.list must be a path, got ${JSON.stringify(decl.routes.list)}`);    need(typeof decl.verbs?.list === "string", "routes.list reads through the list verb, so verbs.list must name a tool");    if (decl.routes.page !== undefined) {      need(decl.routes.page.endsWith("/[id]"), "routes.page must end in /[id]");      need(typeof decl.verbs?.get === "string", "routes.page reads through the get verb, so verbs.get must name a tool");    }  }  if (decl.screen_family !== undefined) need(/^[a-z][A-Za-z0-9]*$/.test(decl.screen_family), "screen_family: a Swift case name");  return problems;}// ---- text helpers -----------------------------------------------------------/** Insert `text` (whole lines) before the line carrying `// gen-kind: <name>`. */function insertBeforeAnchor(source: string, anchor: string, text: string, file: string): string {  const marker = `// gen-kind: ${anchor}`;  const lines = source.split("\n");  const hits = lines.map((line, index) => (line.trim() === marker ? index : -1)).filter((index) => index >= 0);  if (hits.length !== 1) {    throw new Error(`${file}: expected exactly one anchor ${marker}, found ${hits.length}`);  }  lines.splice(hits[0], 0, ...text.replace(/\n$/, "").split("\n"));  return lines.join("\n");}/** Replace exactly one match, or refuse. */function replaceOnce(source: string, pattern: RegExp, replacement: string | ((match: string, ...groups: string[]) => string), file: string): string {  const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;  const all = source.match(new RegExp(pattern.source, flags));  if (!all || all.length !== 1) {    throw new Error(`${file}: expected exactly one match of ${pattern}, found ${all?.length ?? 0}`);  }  return source.replace(pattern, replacement as string);}/** Replace every match — at least one, or refuse. For a literal repeated across a test file. */function replaceAll(source: string, pattern: RegExp, replacement: string, file: string): string {  const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;  const all = source.match(new RegExp(pattern.source, flags));  if (!all || all.length === 0) throw new Error(`${file}: expected at least one match of ${pattern}, found 0`);  return source.replace(new RegExp(pattern.source, flags), replacement);}/** `NAME: [T; 17]` → `NAME: [T; 18]`. */function bumpArrayLength(source: string, name: string, file: string): string {  return replaceOnce(source, new RegExp(`(${name}: \\[[^;\\]]+; )(\\d+)(\\])`), (_m, a, n, c) => `${a}${Number(n) + 1}${c}`, file);}/** A Rust string literal wrapped at ~90 columns with `\` continuations, indented. */export function rustString(text: string, indent: string): string {  const words = text.replace(/"/g, '\\"').split(/\s+/).filter(Boolean);  const lines: string[] = [];  let current = "";  for (const word of words) {    if (current.length > 0 && current.length + 1 + word.length > 84) {      lines.push(current);      current = word;    } else {      current = current.length === 0 ? word : `${current} ${word}`;    }  }  if (current.length > 0) lines.push(current);  if (lines.length === 1) return `"${lines[0]}"`;  return lines.map((line, index) => (index === 0 ? `"${line} \\` : index === lines.length - 1 ? `${indent} ${line}"` : `${indent} ${line} \\`)).join("\n");}/** A Rust `///` doc comment block wrapped at ~76 columns. */function docComment(text: string, indent: string): string {  const words = text.split(/\s+/).filter(Boolean);  const lines: string[] = [];  let current = "";  for (const word of words) {    if (current.length > 0 && current.length + 1 + word.length > 76 - indent.length) {      lines.push(current);      current = word;    } else {      current = current.length === 0 ? word : `${current} ${word}`;    }  }  if (current.length > 0) lines.push(current);  return lines.map((line) => `${indent}/// ${line}`).join("\n");}function lineComment(text: string, indent: string): string {  return docComment(text, indent).replace(new RegExp(`^${indent}/// `, "gm"), `${indent}// `);}function rawString(sql: string): string {  return `r#"${sql}"#`;}// ---- the plan: what one declaration becomes ---------------------------------export interface Facts {  kind: string;  variant: string;  table: string;  /** `cotton_alarms` → `ALARMS`. */  tableShort: string;  version: number;  /** Every column of the table in CREATE order, including the implied ones. */  columns: string[];  /** The declared columns plus, when binnable, `trashed_at`. */  own: ColumnDecl[];  ftsColumns: string[];  fts: boolean;  searchable: boolean;  versioned: boolean;  commentable: boolean;  linkable: boolean;  addressable: boolean;  binnable: boolean;  screenFamily: string;}const HISTORY_STAMPS = ["_hlc", "_born"];export function facts(decl: KindDeclaration, currentVersion: number): Facts {  const binnable = decl.facilities.binnable === true;  const own: ColumnDecl[] = [...decl.columns];  if (binnable) own.push({ name: "trashed_at", sql: "TEXT", codec: "Timestamp", comment: "The bin (schema v33's shape): readers hide the row, Restore clears it, emptying the bin erases." });  const columns = ["id", "workspace_id", ...own.map((c) => c.name), "created_at", "updated_at", ...HISTORY_STAMPS];  return {    kind: decl.kind,    variant: decl.variant ?? pascal(decl.kind),    table: decl.table,    tableShort: screamingSnake(decl.table.replace(/^cotton_/, "")),    version: currentVersion + 1,    columns,    own,    ftsColumns: decl.fts_columns ?? [decl.title_column],    fts: decl.facilities.fts === true,    searchable: decl.facilities.search === "fts",    versioned: decl.facilities.versioned === true,    commentable: decl.facilities.commentable === true,    linkable: decl.facilities.linkable === true,    addressable: decl.facilities.addressable === true,    binnable,    screenFamily: decl.screen_family ?? decl.kind.replace(/_([a-z])/g, (_m, c: string) => c.toUpperCase()),  };}// ---- DDL --------------------------------------------------------------------export function createTable(decl: KindDeclaration, f: Facts): string {  const lines = [`CREATE TABLE IF NOT EXISTS ${f.table} (`, "    id TEXT PRIMARY KEY,", "    workspace_id TEXT NOT NULL,"];  for (const column of f.own) lines.push(`    ${column.name} ${column.sql ?? "TEXT"},`);  lines.push("    created_at TEXT NOT NULL,", "    updated_at TEXT NOT NULL,", "    _hlc TEXT NOT NULL DEFAULT '',", "    _born TEXT,");  for (const check of decl.checks ?? []) lines.push(`    CHECK (${check}),`);  lines.push("    FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE", "  )");  return lines.join("\n");}function authorIndex(f: Facts): string {  return `CREATE INDEX IF NOT EXISTS idx_${f.table}_author ON ${f.table} (substr(_hlc, 20), _hlc)`;}function ftsTable(f: Facts): string {  return `CREATE VIRTUAL TABLE fts_${f.table.replace(/^cotton_/, "")} USING fts5(\n       ${f.ftsColumns.join(", ")}, content = '${f.table}', content_rowid = 'rowid',\n       tokenize = 'unicode61 remove_diacritics 2'\n     )`;}function ftsName(f: Facts): string {  return `fts_${f.table.replace(/^cotton_/, "")}`;}function ftsTriggers(f: Facts): { ai: string; ad: string; au: string } {  const fts = ftsName(f);  const cols = f.ftsColumns;  const news = cols.map((c) => `new.${c}`).join(", ");  const olds = cols.map((c) => `old.${c}`).join(", ");  const list = cols.join(", ");  return {    ai: `CREATE TRIGGER ${fts}_ai AFTER INSERT ON ${f.table} BEGIN\n       INSERT INTO ${fts} (rowid, ${list}) VALUES (new.rowid, ${news});\n     END`,    ad: `CREATE TRIGGER ${fts}_ad AFTER DELETE ON ${f.table} BEGIN\n       INSERT INTO ${fts} (${fts}, rowid, ${list}) VALUES ('delete', old.rowid, ${olds});\n     END`,    au: `CREATE TRIGGER ${fts}_au AFTER UPDATE OF ${list} ON ${f.table}\n       FOR EACH ROW WHEN (${cols.map((c) => `new.${c} IS NOT old.${c}`).join(" OR ")}) BEGIN\n       INSERT INTO ${fts} (${fts}, rowid, ${list}) VALUES ('delete', old.rowid, ${olds});\n       INSERT INTO ${fts} (rowid, ${list}) VALUES (new.rowid, ${news});\n     END`,  };}/** The three facility tables whose CHECK enumerates kinds — widened in place in the flat DDL. */const CHECKED_TABLES: Record<"comments" | "links" | "project_links", { table: string; constant: string; columnsChecked: string[] }> = {  comments: {    table: "cotton_comments",    constant: "COMMENTS_TABLE",    columnsChecked: ["record_kind"],  },  links: {    table: "cotton_links",    constant: "LINKS_TABLE",    columnsChecked: ["from_kind", "to_kind"],  },  project_links: {    table: "cotton_project_links",    constant: "PROJECT_LINKS_TABLE",    columnsChecked: ["record_kind"],  },};/** The columns a `CREATE TABLE` statement declares, in order — for the SHAPE line and the checks on the CHECKed tables. */export function columnsOfCreate(sql: string): string[] {  const body = sql.slice(sql.indexOf("(") + 1);  const columns: string[] = [];  for (const raw of body.split("\n")) {    const line = raw.trim();    if (!line || /^(CHECK|UNIQUE|FOREIGN KEY|PRIMARY KEY|\))/.test(line)) continue;    // `"position" REAL, origin_handle TEXT …` — two columns on one line, and a    // quoted name: split on `, ` only where a new `name TYPE` follows.    for (const piece of line.split(/,\s+(?=(?:"[a-z_]+"|[a-z_]+)\s+(?:TEXT|INTEGER|REAL|BLOB)\b)/)) {      const name = piece.trim().split(/\s+/)[0]?.replace(/,$/, "");      if (name) columns.push(name);    }  }  return columns;}/** Widen `CHECK (<column> IN (…))` of one constant by one kind, in the DDL source. */function widenCheck(ddl: string, constant: string, column: string, kind: string, file: string): string {  const start = ddl.indexOf(`pub const ${constant}: &str = r#"`);  if (start < 0) throw new Error(`${file}: no constant ${constant}`);  const end = ddl.indexOf('"#;', start);  const block = ddl.slice(start, end);  const pattern = new RegExp(`(CHECK \\(${column} IN \\([^)]*)\\)\\)`);  const match = block.match(pattern);  if (!match) throw new Error(`${file}: ${constant} has no CHECK (${column} IN (...))`);  if (match[1].includes(`'${kind}'`)) throw new Error(`${file}: ${constant} already admits '${kind}'`);  const widened = block.replace(pattern, `$1, '${kind}'))`);  return ddl.slice(0, start) + widened + ddl.slice(end);}// ---- the seams --------------------------------------------------------------export interface Seam {  file: string;  /** The anchors this seam inserts at; the guard holds each to one occurrence. */  anchors: string[];  /** Whether this seam runs for the declaration. */  applies: (f: Facts, decl: KindDeclaration) => boolean;  edit: (source: string, f: Facts, decl: KindDeclaration, tree: Tree) => string;}/** The files a run reads before it writes — a seam may need another file's text. */export interface Tree {  read(file: string): string;}const CONSTANTS = "crates/cotton-core/src/constants.rs";const PRIMITIVES = "crates/cotton-core/src/primitives.rs";const WORDS = "crates/cotton-core/src/primitives/words.rs";const SECTIONS = "crates/cotton-core/src/design/sections.rs";const BIN = "crates/cotton-core/src/rules/bin.rs";const SEARCH = "crates/cotton-core/src/rules/search_everything.rs";const HISTORY = "crates/cotton-core/src/rules/history/fields.rs";const HISTORY_TESTS = "crates/cotton-core/src/rules/history/fields_tests.rs";const DDL = "crates/cotton-store/src/schema/ddl.rs";const TABLE_SPECS = "crates/cotton-store/src/schema/table_specs.rs";const FTS = "crates/cotton-store/src/schema/fts.rs";const VERSIONED = "crates/cotton-store/src/schema/versioned.rs";const SURFACE = "crates/cotton-tools/src/mcp/surface.rs";const SEARCH_HANDLER = "crates/cotton-tools/src/mcp/handlers/records_2/search.rs";const ROUTES = "crates/cotton-ffi/src/phone/routes.rs";const READS = "crates/cotton-ffi/src/phone/reads.rs";const READS_TESTS = "crates/cotton-ffi/src/phone/reads_tests.rs";const INVALIDATION = "apps/cotton/Sources/CottonKit/InvalidationMap.swift";function variantLine(f: Facts): string {  return `        ${f.variant} => "${f.kind}",\n`;}function verbCell(cell: Verb): string {  return typeof cell === "string" ? `VerbCell::Tool("${cell}")` : `VerbCell::Not(r#"${cell.not}"#)`;}function membership(value: Membership): string {  return value === true ? "Yes" : `No("${value.replace(/"/g, '\\"')}")`;}export const SEAMS: Seam[] = [  // ── cotton-core: the vocabulary ──────────────────────────────────────────  {    file: CONSTANTS,    anchors: ["primitive-kind", "record-kind", "comment-record-kind", "version-record-kind", "bin-kind", "link-kind"],    applies: () => true,    edit(source, f, decl) {      let out = insertBeforeAnchor(source, "primitive-kind", `${docComment(`v${f.version}. ${decl.why}`, "        ")}\n${variantLine(f)}`, CONSTANTS);      if (f.addressable) out = insertBeforeAnchor(out, "record-kind", variantLine(f), CONSTANTS);      if (f.commentable) out = insertBeforeAnchor(out, "comment-record-kind", variantLine(f), CONSTANTS);      if (f.versioned) out = insertBeforeAnchor(out, "version-record-kind", variantLine(f), CONSTANTS);      if (f.binnable) out = insertBeforeAnchor(out, "bin-kind", variantLine(f), CONSTANTS);      if (f.linkable) out = insertBeforeAnchor(out, "link-kind", variantLine(f), CONSTANTS);      return out;    },  },  {    file: PRIMITIVES,    anchors: ["primitive-spec"],    applies: () => true,    edit(source, f, decl) {      const fac = decl.facilities;      const search = fac.search === "fts" ? "SearchLane::Fts" : `SearchLane::No("${fac.search.replace(/"/g, '\\"')}")`;      const arm = `${lineComment(`v${f.version} of the store schema. ${decl.why}`, "        ")}        PrimitiveKind::${f.variant} => PrimitiveSpec {            table: "${f.table}",            fts: ${membership(fac.fts)},            embedded: ${membership(fac.embedded)},            search: ${search},            versioned: ${membership(fac.versioned)},            commentable: ${membership(fac.commentable)},            summarized: ${membership(fac.summarized)},            project_linkable: ${membership(fac.project_linkable)},            linkable: ${membership(fac.linkable)},            route_target: ${membership(fac.route_target)},            addressable: ${membership(fac.addressable)},            binnable: ${membership(fac.binnable)},            shareable: ${membership(fac.shareable)},        },`;      return insertBeforeAnchor(source, "primitive-spec", arm, PRIMITIVES);    },  },  {    file: WORDS,    anchors: ["meaning", "feeds"],    applies: () => true,    edit(source, f, decl) {      const arm = (text: string) => `        ${f.variant} => {\n            ${rustString(text, "            ")}\n        }\n`;      let out = insertBeforeAnchor(source, "meaning", arm(decl.words.meaning), WORDS);      out = insertBeforeAnchor(out, "feeds", arm(decl.words.feeds), WORDS);      return out;    },  },  {    file: SECTIONS,    anchors: ["machinery-kinds"],    applies: () => true,    edit(source, f, decl) {      if (typeof decl.section === "string") {        const key = pascal(decl.section);        const lines = source.split("\n");        const index = lines.findIndex((line) => line.trim().startsWith(`SectionKey::${key} => &[`));        if (index < 0) throw new Error(`${SECTIONS}: no section arm for SectionKey::${key}`);        if (lines[index].trim().endsWith("],")) {          lines[index] = lines[index].replace(/\],$/, `, PrimitiveKind::${f.variant}],`).replace("[, ", "[");        } else {          const close = lines.findIndex((line, at) => at > index && line.trim() === "],");          lines.splice(close, 0, `            PrimitiveKind::${f.variant},`);        }        return lines.join("\n");      }      const entry = `    (\n        PrimitiveKind::${f.variant},\n        ${rustString(decl.section.machinery, "        ")},\n    ),\n`;      let out = insertBeforeAnchor(source, "machinery-kinds", entry, SECTIONS);      out = bumpArrayLength(out, "MACHINERY_KINDS", SECTIONS);      return out;    },  },  {    file: BIN,    anchors: ["bin-source", "bin-hand-title"],    applies: (f) => f.binnable,    edit(source, f, decl) {      // A new kind ships no built-in definition, so its bin title column is a      // hand entry until one does; its untitled words are the bin line set's      // `untitled_any` until a line names it.      const hand = `    (BinKind::${f.variant}, "${decl.title_column}"),\n`;      const arm = `        // v${f.version}. Restoring is clearing \`trashed_at\`; nothing else has to hear.        BinKind::${f.variant} => BinSource {            table: "${f.table}",            restore_also: &[],        },`;      return insertBeforeAnchor(insertBeforeAnchor(source, "bin-source", arm, BIN), "bin-hand-title", hand, BIN);    },  },  {    file: SEARCH,    anchors: ["everything-kind", "everything-kind-str", "everything-kinds", "everything-section", "everything-section-str", "everything-sections", "section-of", "fts-lanes", "map-fts-row"],    applies: (f) => f.searchable,    edit(source, f, decl) {      let out = source;      const V = f.variant;      out = insertBeforeAnchor(out, "everything-kind", `    /// v${f.version}. On the FTS lane over \`${ftsName(f)}\`.\n    #[serde(rename = "${f.kind}")]\n    ${V},\n`, SEARCH);      out = insertBeforeAnchor(out, "everything-kind-str", `            EverythingKind::${V} => "${f.kind}",\n`, SEARCH);      out = insertBeforeAnchor(out, "everything-kinds", `    EverythingKind::${V},\n`, SEARCH);      out = bumpArrayLength(out, "EVERYTHING_KINDS", SEARCH);      out = insertBeforeAnchor(out, "everything-section", `    #[serde(rename = "${f.kind}")]\n    ${V},\n`, SEARCH);      out = insertBeforeAnchor(out, "everything-section-str", `            EverythingSection::${V} => "${f.kind}",\n`, SEARCH);      out = insertBeforeAnchor(out, "everything-sections", `    EverythingSection::${V},\n`, SEARCH);      out = bumpArrayLength(out, "EVERYTHING_SECTIONS", SEARCH);      out = insertBeforeAnchor(out, "section-of", `        EverythingKind::${V} => EverythingSection::${V},\n`, SEARCH);      const weights = f.ftsColumns.map((_c, index) => (index === 0 ? 2 : 1)).join(", ");      const where = f.binnable ? `Some("t.trashed_at IS NULL")` : "None";      out = insertBeforeAnchor(        out,        "fts-lanes",        `    // v${f.version}. The title column counts double, as every lane's does; ${f.binnable ? "rows in the bin stay out" : "there is no soft delete to filter"}.    FtsLane {        kind: EverythingKind::${V},        fts: "${ftsName(f)}",        table: "${f.table}",        weights: &[${weights}],        select: Some("t.${decl.title_column} AS d_title, t.updated_at AS d_when"),        where_clause: ${where},        archived: None,        recency: "t.updated_at",    },`,        SEARCH,      );      out = bumpArrayLength(out, "FTS_LANES", SEARCH);      out = insertBeforeAnchor(        out,        "map-fts-row",        `        EverythingKind::${V} => HitExtra {            title: row.text("d_title").map(str::to_string),            when: row.text("d_when").map(str::to_string),            ..HitExtra::default()        },`,        SEARCH,      );      return out;    },  },  {    file: HISTORY,    anchors: ["history-specs", "history-kind"],    applies: (f) => f.versioned,    edit(source, f, decl) {      const history = decl.history!;      const fields = history.fields        .map((field) => (field.form && field.form !== "Text" ? `        ff("${field.column}", "${field.label}", ${field.form}),` : `        f("${field.column}", "${field.label}"),`))        .join("\n");      const restore = Array.isArray(history.restore) ? `Restore::Columns(&[${history.restore.map((c) => `"${c}"`).join(", ")}])` : `Restore::Refusal(${rustString(history.restore, "    ")})`;      const spec = `/// v${f.version}.\nconst ${screamingSnake(f.kind)}: HistoryKindSpec = HistoryKindSpec {\n    table: "${f.table}",\n    fields: &[\n${fields}\n    ],\n    restore: ${restore},\n};\n\n`;      let out = insertBeforeAnchor(source, "history-specs", spec, HISTORY);      out = insertBeforeAnchor(out, "history-kind", `        VersionRecordKind::${f.variant} => &${screamingSnake(f.kind)},\n`, HISTORY);      return out;    },  },  {    file: HISTORY_TESTS,    anchors: [],    applies: (f) => f.versioned,    edit(source) {      // The declaration-order list and the VersionRecordKind::ALL count that      // once lived here were deleted on 12 Oct 2026 (27f292199: a counter is      // not a guard), as were primitives_tests.rs's order lists and      // search_everything_tests.rs's FTS_LANES count, so a kind writes into      // none of them. `versioned_tables()` — one entry per versioned TABLE; a      // kind with its own table is one more.      return replaceOnce(source, /(let tables = versioned_tables\(\);\n\s*assert_eq!\(tables\.len\(\), )(\d+)(\);)/, (_m, a, n, c) => `${a}${Number(n) + 1}${c}`, HISTORY_TESTS);    },  },  // ── cotton-store: the file ───────────────────────────────────────────────  {    file: DDL,    anchors: ["ddl-consts", "schema-ddl-tables", "schema-ddl-fts", "schema-ddl-indexes", "schema-ddl-triggers"],    applies: () => true,    edit(source, f, decl) {      let out = source;      const S = f.tableShort;      const consts: string[] = [];      // `SCHEMA_DDL` is grouped by phase — tables, FTS, indexes, triggers — and      // `create::tests::the_phase_order_is_the_order_the_generator_wrote` holds it so.      const fresh: Record<"tables" | "fts" | "indexes" | "triggers", string[]> = { tables: [], fts: [], indexes: [], triggers: [] };      consts.push(`${docComment(`\`${f.table}\` — v${f.version}. ${decl.why}`, "")}\npub const ${S}_TABLE: &str = ${rawString(createTable(decl, f))};\n`);      fresh.tables.push(`    ${S}_TABLE,`);      (decl.indexes ?? []).forEach((index, at) => {        const name = `${S}_INDEX_${at + 1}`;        consts.push(`pub const ${name}: &str = ${rawString(index)};`);        fresh.indexes.push(`    ${name},`);      });      consts.push(`pub const AUTHOR_INDEX_${screamingSnake(f.table)}: &str = ${rawString(authorIndex(f))};`);      fresh.indexes.push(`    AUTHOR_INDEX_${screamingSnake(f.table)},`);      if (f.fts) {        const fts = ftsName(f);        const FTS = screamingSnake(fts);        const triggers = ftsTriggers(f);        consts.push(`/// \`${fts}\` — the external-content index over \`${f.table}\`.\npub const ${FTS}_TABLE: &str = ${rawString(ftsTable(f))};`);        consts.push(`/// \`${fts}\` on insert.\npub const ${FTS}_AI: &str = ${rawString(triggers.ai)};`);        consts.push(`/// \`${fts}\` on delete.\npub const ${FTS}_AD: &str = ${rawString(triggers.ad)};`);        consts.push(`/// \`${fts}\` on update.\npub const ${FTS}_AU: &str = ${rawString(triggers.au)};`);        fresh.fts.push(`    ${FTS}_TABLE,`);        fresh.triggers.push(`    ${FTS}_AI,`, `    ${FTS}_AD,`, `    ${FTS}_AU,`);      }      if (f.commentable) {        out = widenCheck(out, CHECKED_TABLES.comments.constant, "record_kind", f.kind, DDL);      }      if (f.linkable) {        out = widenCheck(out, CHECKED_TABLES.links.constant, "from_kind", f.kind, DDL);        out = widenCheck(out, CHECKED_TABLES.links.constant, "to_kind", f.kind, DDL);      }      // The fresh line: no rung and no per-version statement list. The constants      // land above `ddl-consts`, `SCHEMA_DDL` gains them by phase below, and the      // CHECKs above widen in the constants a fresh file is built from.      out = insertBeforeAnchor(out, "ddl-consts", `${consts.join("\n")}\n\n`, DDL);      for (const phase of ["tables", "fts", "indexes", "triggers"] as const) {        if (fresh[phase].length === 0) continue;        out = insertBeforeAnchor(out, `schema-ddl-${phase}`, `    // v${f.version} — \`${f.kind}\`.\n${fresh[phase].join("\n")}\n`, DDL);      }      out = replaceOnce(out, /(pub const SCHEMA_VERSION: u32 = )(\d+);/, (_m, a, n) => `${a}${Number(n) + 1};`, DDL);      return out;    },  },  {    file: TABLE_SPECS,    anchors: ["table-specs", "table-names"],    applies: () => true,    edit(source, f, decl) {      const columns = [        `            ("id", Codec::Text),`,        `            ("workspace_id", Codec::Text),`,        ...f.own.flatMap((column) => [...(column.comment ? [lineComment(column.comment, "            ")] : []), `            ("${column.name}", Codec::${column.codec}),`]),        `            ("created_at", Codec::Timestamp),`,        `            ("updated_at", Codec::Timestamp),`,      ].join("\n");      const spec = `    // v${f.version} — \`${f.kind}\`.\n    TableSpec {\n        name: "${f.table}",\n        pk: "id",\n        columns: &[\n${columns}\n        ],\n        natural_key: &[],\n        fts_into: ${f.fts ? `Some("${ftsName(f)}")` : "None"},\n    },\n`;      let out = insertBeforeAnchor(source, "table-specs", spec, TABLE_SPECS);      out = insertBeforeAnchor(out, "table-names", `    "${f.table}",\n`, TABLE_SPECS);      void decl;      return out;    },  },  {    file: FTS,    anchors: ["fts-sources"],    applies: (f) => f.fts,    edit(source, f) {      const entry = `    // v${f.version} — \`${f.kind}\`.\n    FtsSource {\n        fts: "${ftsName(f)}",\n        source: "${f.table}",\n        columns: &[${f.ftsColumns.map((c) => `"${c}"`).join(", ")}],\n    },\n`;      // FTS_SOURCES carries no hand-counted length assert any more; the list is the count.      return insertBeforeAnchor(source, "fts-sources", entry, FTS);    },  },  // The schema-snapshot test no longer carries a hand-counted fts assert: since v122 it compares the file against  // FTS_SOURCES itself (one list, read where it lives), so a new searchable kind edits only FTS_SOURCES above.  {    file: VERSIONED,    anchors: ["versioned-tables"],    applies: (f) => f.versioned,    edit: (source, f) => insertBeforeAnchor(source, "versioned-tables", `    VersionedTable { table: "${f.table}", kind: "${f.kind}", redact: &[], omit: &[] },\n`, VERSIONED),  },  // ── cotton-tools: the MCP surface ────────────────────────────────────────  {    file: SURFACE,    anchors: ["primitive-kinds", "tool-surface"],    applies: () => true,    edit(source, f, decl) {      let out = insertBeforeAnchor(source, "primitive-kinds", `    "${f.kind}",\n`, SURFACE);      const row = `    // v${f.version} — \`${f.kind}\`. The tools the cells name are written by hand beside\n    // this row; a refusal is the sentence a caller reads instead.\n    ("${f.kind}", VerbSet {\n        create: ${verbCell(decl.verbs.create)},\n        list: ${verbCell(decl.verbs.list)},\n        get: ${verbCell(decl.verbs.get)},\n        update: ${verbCell(decl.verbs.update)},\n        remove: ${verbCell(decl.verbs.remove)},\n        also: &[],\n    }),\n`;      out = insertBeforeAnchor(out, "tool-surface", row, SURFACE);      out = replaceOnce(out, /(\/\/! )(\d+)( primitives, )/, (_m, a, n, c) => `${a}${Number(n) + 1}${c}`, SURFACE);      return out;    },  },  {    file: SEARCH_HANDLER,    anchors: ["search-kinds"],    applies: (f) => f.searchable,    edit: (source, f) => insertBeforeAnchor(source, "search-kinds", `    "${f.kind}",\n`, SEARCH_HANDLER),  },  // ── cotton-ffi: the phone's routes and reads ─────────────────────────────  {    file: ROUTES,    anchors: [],    applies: (_f, decl) => decl.routes !== undefined,    edit(source, _f, decl) {      const routes = [decl.routes!.list, ...(decl.routes!.page ? [decl.routes!.page] : [])];      let out = source;      for (const route of routes) {        if (out.includes(`    "${route}",`)) throw new Error(`${ROUTES}: ${route} is already a route`);        const lines = out.split("\n");        const start = lines.findIndex((line) => line.startsWith("pub const ROUTES:"));        let at = start + 1;        while (at < lines.length && lines[at].trim() !== "];") {          const existing = lines[at].trim().replace(/^"|",$/g, "");          if (lines[at].trim().startsWith('"') && existing > route) break;          at += 1;        }        lines.splice(at, 0, `    "${route}",`);        out = lines.join("\n");      }      return out;    },  },  {    file: READS,    anchors: ["reads"],    applies: (_f, decl) => decl.routes !== undefined,    edit(source, f, decl) {      // The list screen draws the whole set — `ToolWholeSet` sends `limit: "all"` — because a      // phone list that pages is a screen that can ask for more, and that screen is by hand.      const reads = [`    ScreenRead {\n        name: "${f.kind}_list",\n        audience: Audience::Screens(&["${decl.routes!.list}"]),\n        source: ReadSource::ToolWholeSet("${decl.verbs.list as string}"),\n    },\n`];      if (decl.routes!.page) {        reads.push(`    ScreenRead {\n        name: "${f.kind}",\n        audience: Audience::Screens(&["${decl.routes!.page}"]),\n        source: ReadSource::Tool("${decl.verbs.get as string}"),\n    },\n`);      }      return insertBeforeAnchor(source, "reads", `    // ── v${f.version}: \`${f.kind}\` ──────────────────────────────────────\n${reads.join("")}`, READS);    },  },  {    file: READS_TESTS,    anchors: ["tool-backed-scale"],    applies: (_f, decl) => decl.routes !== undefined,    edit(source, f, decl) {      const rows = [`    ("${f.kind}_list", ListScale::WholeSet),\n`];      if (decl.routes!.page) rows.push(`    ("${f.kind}", ListScale::Record),\n`);      return insertBeforeAnchor(source, "tool-backed-scale", rows.join(""), READS_TESTS);    },  },  // ── the phone: which screens re-read when the table changes ──────────────  {    file: INVALIDATION,    anchors: ["screen-families", "invalidation-entries"],    applies: () => true,    edit(source, f) {      let out = source;      if (!new RegExp(`^    case ${f.screenFamily}$`, "m").test(out)) {        out = insertBeforeAnchor(out, "screen-families", `    case ${f.screenFamily}\n`, INVALIDATION);      }      return insertBeforeAnchor(out, "invalidation-entries", `        Entry(\n            tables: ["${f.table}"],\n            families: [.${f.screenFamily}]\n        ),\n`, INVALIDATION);    },  },];// ---- numbers in words ---------------------------------------------------const WORDS_FOR_NUMBERS = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];const TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];export function numberWords(n: number): string {  if (n < 20) return WORDS_FOR_NUMBERS[n];  if (n < 100) return `${TENS[Math.floor(n / 10)]}${n % 10 ? `_${WORDS_FOR_NUMBERS[n % 10]}` : ""}`;  return `${WORDS_FOR_NUMBERS[Math.floor(n / 100)]}_hundred${n % 100 ? `_${numberWords(n % 100)}` : ""}`;}// ---- running it -------------------------------------------------------------export interface RunResult {  written: string[];  version: number;  handSeams: string[];  /** The SHAPE ledger line for this change — printed, for the PR to record. */  shapeLine: string;}export interface RunOptions {  /** The ledger date, `YYYY-MM-DD`. Absent means today, UTC. */  date?: string;  /** The PR the change lands in, e.g. `#1400`. Absent leaves a `#<pr>` to fill. */  pr?: string;}/** * The SHAPE ledger line a new kind's table is recorded with on the fresh line: * there is no rung to read the change from, so the ledger says it in one line. */export function shapeLine(f: Facts, options: RunOptions = {}): string {  const date = options.date ?? new Date().toISOString().slice(0, 10);  const pr = options.pr ?? "#<pr>";  return `SHAPE ${date} ${pr} — ${f.table}: absent → ${f.columns.join(", ")}, an old file has no rows`;}export function currentSchemaVersion(ddl: string): number {  const match = ddl.match(/pub const SCHEMA_VERSION: u32 = (\d+);/);  if (!match) throw new Error(`${DDL}: no SCHEMA_VERSION`);  return Number(match[1]);}/** The kinds the registry already has, read off the enum. */export function existingKinds(constants: string): string[] {  const start = constants.indexOf("    PrimitiveKind {");  const end = constants.indexOf("// gen-kind: primitive-kind", start);  return [...constants.slice(start, end).matchAll(/=> "([a-z_]+)",/g)].map((m) => m[1]);}/** What stays by hand after a run, as one line each — printed, and the PR's checklist. */export function handSeams(decl: KindDeclaration, f: Facts): string[] {  const tools = (["create", "list", "get", "update", "remove"] as const).map((verb) => decl.verbs[verb]).filter((cell): cell is string => typeof cell === "string");  const lines = [    `cargo test -p cotton-store --test schema_snapshot -- --ignored   (rewrites tests/fixtures/schema-snapshot.json for v${f.version})`,    `the shape ledger — the SHAPE line printed above, with the PR number filled in`,    ...tools.map((tool) => `crates/cotton-tools/src/mcp/catalogue.rs — a ToolDef named ${tool}, its handler group and dispatch arm (the grid names it; the gate is red until it exists)`),    "crates/cotton-tools/src/mcp/tool_surface_tests.rs — the TOOLS count, and each new write tool in DESTRUCTIVE or ADDITIVE",  ];  if (f.searchable) {    lines.push(      `crates/cotton-core/src/rules/search_everything_tests.rs — the whole-file transcript read out of Node: a sql::${screamingSnake(f.kind)} and sql::COUNT_${screamingSnake(f.kind)} fixture, the lane in each expected list, and the statement counts and indices after it (the generator will not write a test's expectation from the code it tests)`,    );  }  if (decl.routes) {    lines.push(      `apps/cotton/Sources/CottonMailbox/Route.swift — cases for ${[decl.routes.list, decl.routes.page].filter(Boolean).join(" and ")}, their path and parse arms; RouteTier.swift, RouteColumns.swift and Boot/RouteScreen.swift's total switches`,      `apps/cotton-android/core/src/main/kotlin/com/cottondb/android/navigation/Route.kt — the same routes, their parse arms and tier`,    );  }  if (f.addressable) lines.push("apps/cotton/Sources/CottonMailbox/RecordRoute.swift — the RecordKind case and where Route.record opens it");  lines.push(`docs are records in Cotton: a note on the kind's design, and the todo closed when the PR merges`);  return lines;}export function runGenKind(decl: KindDeclaration, root: string, options: RunOptions = {}): RunResult {  const problems = validate(decl);  if (problems.length > 0) throw new Error(`the declaration is refused:\n  - ${problems.join("\n  - ")}`);  const read = (file: string) => {    const path = join(root, file);    if (!existsSync(path)) throw new Error(`${file}: not in the tree at ${root}`);    return readFileSync(path, "utf8");  };  const constants = read(CONSTANTS);  if (existingKinds(constants).includes(decl.kind)) throw new Error(`${decl.kind} is already a record kind`);  const specs = read(TABLE_SPECS);  if (specs.includes(`"${decl.table}"`)) throw new Error(`${decl.table} is already a synced table`);  const f = facts(decl, currentSchemaVersion(read(DDL)));  const tree: Tree = { read };  const outputs = new Map<string, string>();  for (const seam of SEAMS) {    if (!seam.applies(f, decl)) continue;    const before = outputs.get(seam.file) ?? read(seam.file);    outputs.set(seam.file, seam.edit(before, f, decl, tree));  }  for (const [file, text] of outputs) {    mkdirSync(dirname(join(root, file)), { recursive: true });    writeFileSync(join(root, file), text);  }  return { written: [...outputs.keys()].sort(), version: f.version, handSeams: handSeams(decl, f), shapeLine: shapeLine(f, options) };}