Cotton code
440 lines · 24.0 KB · TypeScriptRaw
/** * gen-kind — the kind scaffolder, and the guard that keeps its anchors alive. * * THE GUARD (the first block) is the one that matters between runs: every * `// gen-kind: <name>` anchor `SEAMS` names must occur EXACTLY ONCE in the * real tree. A refactor that moves an enum, splits a file or tidies a comment * away would otherwise be found by the next person adding a kind — a day * later, in a run that half-wrote. This test finds it in the same PR. * * THE RUN (the rest) copies the seam files out of the real tree into a scratch * directory, scaffolds a kind there, and reads what came out: the kind is in * every enum and list its facilities put it in, the counts the tests pin moved * by one, the anchors survived for the next kind, and — the store's ladder * being one rung since 9a — the kind landed as DDL and a version bump only: no * rung, no per-version statement list, no migrator test, and a SHAPE ledger * line handed back for the PR. It does not compile the Rust — that is what running the generator * for real and `cargo test` is for, and the PR that added it did exactly that * with a `timer` kind before reverting it. */import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";import { afterEach, describe, expect, it } from "vitest";import {  type KindDeclaration,  SEAMS,  columnsOfCreate,  createTable,  currentSchemaVersion,  existingKinds,  facts,  numberWords,  runGenKind,  shapeLine,  rustString,  validate,} from "../lib/gen-kind";import { EXAMPLE } from "../gen-kind";const ROOT = resolve(__dirname, "../..");const DDL = "crates/cotton-store/src/schema/ddl.rs";/** Every file a run may read or write, for the scratch copy. */const FILES = [  ...new Set([    ...SEAMS.map((seam) => seam.file),    "crates/cotton-core/src/constants.rs",    "crates/cotton-store/src/schema/table_specs.rs",    DDL,    "crates/cotton-tools/src/mcp/catalogue.rs",  ]),];const made: string[] = [];afterEach(() => {  while (made.length > 0) rmSync(made.pop() as string, { recursive: true, force: true });});function scratchTree(): string {  const root = mkdtempSync(join(tmpdir(), "gen-kind-"));  made.push(root);  for (const file of FILES) {    mkdirSync(dirname(join(root, file)), { recursive: true });    cpSync(join(ROOT, file), join(root, file));  }  return root;}function count(haystack: string, needle: string): number {  return haystack.split(needle).length - 1;}/** Lines that are exactly this anchor — `everything-kind` is a prefix of two others. */function anchorLines(source: string, anchor: string): number {  return source.split("\n").filter((line) => line.trim() === `// gen-kind: ${anchor}`).length;}describe("the anchors the generator writes at", () => {  it("each occurs exactly once in the real tree, on a line of its own", () => {    const missing: string[] = [];    for (const seam of SEAMS) {      const source = readFileSync(join(ROOT, seam.file), "utf8");      for (const anchor of seam.anchors) {        const lines = source.split("\n").filter((line) => line.trim() === `// gen-kind: ${anchor}`);        if (lines.length !== 1) missing.push(`${seam.file}: ${anchor} ×${lines.length}`);      }    }    expect(missing).toEqual([]);  });  it("every anchor is named by exactly one seam", () => {    const all = SEAMS.flatMap((seam) => seam.anchors.map((anchor) => `${seam.file}#${anchor}`));    expect(new Set(all).size).toBe(all.length);  });  it("the counts the generator bumps are still where it looks", () => {    const ddl = readFileSync(join(ROOT, DDL), "utf8");    expect(currentSchemaVersion(ddl)).toBeGreaterThanOrEqual(39);    // The fresh line: the version is a literal in ddl.rs, the one thing a new kind bumps.    expect(ddl).toMatch(/^pub const SCHEMA_VERSION: u32 = \d+;$/m);    // primitives_tests.rs's counts and order lists, search_everything_tests.rs's    // FTS_LANES count and fields_tests.rs's VersionRecordKind count are gone    // (12 Oct 2026, 27f292199: a counter is not a guard); the generator no    // longer looks for them, so nothing here expects them.    const search = readFileSync(join(ROOT, "crates/cotton-core/src/rules/search_everything.rs"), "utf8");    expect(search).toMatch(/EVERYTHING_KINDS: \[EverythingKind; \d+\]/);    expect(search).toMatch(/EVERYTHING_SECTIONS: \[EverythingSection; \d+\]/);    expect(search).toMatch(/FTS_LANES: \[FtsLane; \d+\]/);    expect(readFileSync(join(ROOT, "crates/cotton-tools/src/mcp/surface.rs"), "utf8")).toMatch(/^\/\/! \d+ primitives, /m);    const history = readFileSync(join(ROOT, "crates/cotton-core/src/rules/history/fields_tests.rs"), "utf8");    expect(history).toMatch(/let tables = versioned_tables\(\);\n\s*assert_eq!\(tables\.len\(\), \d+\);/);  });  it("the four CHECKed facility tables are named constants whose columns can be read", () => {    const ddl = readFileSync(join(ROOT, DDL), "utf8");    for (const constant of ["COMMENTS_TABLE", "LINKS_TABLE", "PROJECT_LINKS_TABLE"]) {      const start = ddl.indexOf(`pub const ${constant}: &str = r#"`);      expect(start, constant).toBeGreaterThan(0);      const create = ddl.slice(start, ddl.indexOf('"#;', start));      const columns = columnsOfCreate(create);      expect(columns[0]).toBe("id");      expect(columns).toContain("workspace_id");      expect(columns).toContain("_born");      expect(columns.some((c) => /[()]/.test(c))).toBe(false);    }  });});describe("the declaration is refused when it is not whole", () => {  it("accepts the example", () => {    expect(validate(EXAMPLE)).toEqual([]);  });  it("names every problem at once", () => {    const problems = validate({      ...EXAMPLE,      kind: "Timer",      title_column: "nope",      facilities: { ...EXAMPLE.facilities, embedded: true as unknown as string, search: "like", fts: "no thanks" },      words: { meaning: "TODO", feeds: "The owner makes them." },      verbs: { ...EXAMPLE.verbs, remove: { not: "no" } },    });    expect(problems).toEqual(      expect.arrayContaining([        expect.stringContaining("kind must be snake_case"),        expect.stringContaining("title_column"),        expect.stringContaining("facilities.embedded: a written reason only"),        expect.stringContaining("facilities.search"),        expect.stringContaining("facilities.fts: true or a written reason"),        expect.stringContaining("words.meaning"),        expect.stringContaining("words.feeds: name the source"),        expect.stringContaining("verbs.remove"),      ]),    );  });  it("a versioned kind must say what history draws and what a restore writes", () => {    const { history: _dropped, ...rest } = EXAMPLE;    expect(validate(rest as KindDeclaration)).toContainEqual(expect.stringContaining("history: required"));    expect(validate({ ...EXAMPLE, history: { fields: [{ column: "label", label: "Label" }], restore: ["ghost"] } })).toEqual([      expect.stringContaining("history.restore"),    ]);  });  it("a page route needs a get tool to read through, a list route a list tool", () => {    expect(validate({ ...EXAMPLE, verbs: { ...EXAMPLE.verbs, get: { not: "There is nothing to get; the list is the record." } } })).toEqual([      expect.stringContaining("routes.page reads through the get verb"),    ]);    expect(validate({ ...EXAMPLE, routes: { list: "timers" } })).toEqual([expect.stringContaining("routes.list must be a path")]);  });  it("implied columns are not declared twice", () => {    expect(validate({ ...EXAMPLE, columns: [...EXAMPLE.columns, { name: "trashed_at", codec: "Timestamp" }] })).toEqual([      expect.stringContaining("trashed_at is implied"),    ]);  });});describe("the text it writes", () => {  it("a Rust string wraps with continuations and escapes quotes", () => {    expect(rustString('say "hi"', "    ")).toBe('"say \\"hi\\""');    const long = rustString(Array(30).fill("word").join(" "), "            ");    expect(long.split("\n").length).toBeGreaterThan(1);    expect(long.startsWith('"word')).toBe(true);    expect(long.endsWith('word"')).toBe(true);    for (const line of long.split("\n").slice(0, -1)) expect(line.endsWith(" \\")).toBe(true);  });  it("the CREATE carries the implied columns around the kind's own, and trashed_at only when binnable", () => {    const f = facts(EXAMPLE, 39);    const create = createTable(EXAMPLE, f);    expect(columnsOfCreate(create)).toEqual(["id", "workspace_id", "label", "seconds", "running", "trashed_at", "created_at", "updated_at", "_hlc", "_born"]);    // Receipt folding owns column history; a new kind must use the current baseline.    expect(create).toContain("_born TEXT,");    expect(create).not.toMatch(/_hlc0|_chlc/);    expect(create).toContain("CHECK (running IN (0, 1)),");    expect(create).toContain("FOREIGN KEY (workspace_id) REFERENCES cotton_workspaces(id) ON DELETE CASCADE");    const unbinnable = { ...EXAMPLE, facilities: { ...EXAMPLE.facilities, binnable: "A timer that is gone is gone; there is nothing to restore." } };    expect(columnsOfCreate(createTable(unbinnable, facts(unbinnable, 39)))).not.toContain("trashed_at");  });  it("the SHAPE ledger line names the table, every column in CREATE order, and leaves the PR to fill when none is given", () => {    const f = facts(EXAMPLE, 49);    expect(shapeLine(f, { date: "2026-10-03" })).toBe(      "SHAPE 2026-10-03 #<pr> — cotton_timers: absent → id, workspace_id, label, seconds, running, trashed_at, created_at, updated_at, _hlc, _born, an old file has no rows",    );  });  it("numbers become the words the schema snapshot test spells its counts with", () => {    expect(numberWords(39)).toBe("thirty_nine");    expect(numberWords(40)).toBe("forty");    expect(numberWords(101)).toBe("one_hundred_one");  });});describe("a run over a copy of the real tree", () => {  // RULE: Adding a searchable engine kind keeps the open table-id search schema unchanged, so user tables remain searchable and generation cannot depend on a closed enum.  it("adds a searchable kind without editing the open search catalogue", () => {    const root = scratchTree();    const catalogue = "crates/cotton-tools/src/mcp/catalogue.rs";    const before = readFileSync(join(root, catalogue), "utf8");    expect(before).toContain('"pattern":"^[a-z][a-z0-9_]*$"');    const result = runGenKind(EXAMPLE, root);    expect(result.written).not.toContain(catalogue);    expect(readFileSync(join(root, catalogue), "utf8")).toBe(before);    expect(readFileSync(join(root, "crates/cotton-tools/src/mcp/handlers/records_2/search.rs"), "utf8")).toContain('    "timer",');  });  it("puts the kind in every seam its facilities name, bumps the counts and the version, keeps the anchors, writes no rung", () => {    const root = scratchTree();    const before = Object.fromEntries(FILES.map((file) => [file, readFileSync(join(root, file), "utf8")]));    const version = currentSchemaVersion(before[DDL]);    const result = runGenKind(EXAMPLE, root, { date: "2026-10-03", pr: "#1400" });    expect(result.version).toBe(version + 1);    expect(result.shapeLine).toBe(      "SHAPE 2026-10-03 #1400 — cotton_timers: absent → id, workspace_id, label, seconds, running, trashed_at, created_at, updated_at, _hlc, _born, an old file has no rows",    );    const after = Object.fromEntries(FILES.map((file) => [file, readFileSync(join(root, file), "utf8")]));    // Every seam ran (the example is in every facility the generator scaffolds).    for (const seam of SEAMS) expect(result.written, seam.file).toContain(seam.file);    // …and every anchor is still there for the next kind.    for (const seam of SEAMS) {      for (const anchor of seam.anchors) {        expect(anchorLines(after[seam.file], anchor), `${seam.file}#${anchor}`).toBe(1);      }    }    const constants = after["crates/cotton-core/src/constants.rs"];    expect(existingKinds(constants)).toContain("timer");    expect(count(constants, '        Timer => "timer",')).toBe(6); // PrimitiveKind, RecordKind, CommentRecordKind, VersionRecordKind, BinKind, LinkKind    expect(constants).toContain(`/// v${version + 1}. A timer is a span the phone counts down`);    const primitives = after["crates/cotton-core/src/primitives.rs"];    expect(primitives).toContain("PrimitiveKind::Timer => PrimitiveSpec {");    expect(primitives).toContain('table: "cotton_timers",');    expect(primitives).toContain("search: SearchLane::Fts,");    expect(primitives).toMatch(/embedded: No\("A label of three words/);    const ddl = after[DDL];    expect(ddl).toContain(`pub const SCHEMA_VERSION: u32 = ${version + 1};`);    expect(ddl).toContain("pub const TIMERS_TABLE: &str = r#\"CREATE TABLE IF NOT EXISTS cotton_timers (");    // No per-version statement list: a fresh file is the flat DDL.    expect(ddl).not.toContain("TIMERS_DDL");    expect(ddl).toContain("pub const FTS_TIMERS_AU: &str");    // History is the act's cotton_changes row (schema 89): no trigger pair.    expect(ddl).not.toContain("TIMERS_VERSION_AD");    // The CHECKs widened in the constants a fresh file is built from…    for (const constant of ["COMMENTS_TABLE", "LINKS_TABLE"]) {      const start = ddl.indexOf(`pub const ${constant}: &str = r#"`);      expect(ddl.slice(start, ddl.indexOf('"#;', start)), constant).toContain(", 'timer'))");    }    // …and nothing rebuilds them: there is no rung to carry an old file's rows.    expect(count(ddl, "_carry"), "the run wrote a carry").toBe(count(before[DDL], "_carry"));    expect(ddl).not.toContain("DROP TRIGGER IF EXISTS fts_timers_au");    expect(ddl).not.toContain("INSERT INTO fts_timers(fts_timers) VALUES ('rebuild')");    // The fresh-file list carries the CREATEs, by phase.    const phase = (name: string) => ddl.slice(ddl.lastIndexOf(`// gen-kind: schema-ddl-${name}`) - 300, ddl.lastIndexOf(`// gen-kind: schema-ddl-${name}`));    expect(phase("tables")).toContain("TIMERS_TABLE,");    expect(phase("fts")).toContain("FTS_TIMERS_TABLE,");    expect(phase("indexes")).toContain("AUTHOR_INDEX_COTTON_TIMERS,");    expect(phase("triggers")).toContain("FTS_TIMERS_AI,");    expect(ddl.slice(ddl.indexOf("pub static SCHEMA_DDL"))).not.toContain("cotton_timers_carry");    for (const name of ["tables", "fts", "indexes", "triggers"]) expect(phase(name)).not.toContain("carry");    // migrate.rs is not a seam any more: the one rung is at SCHEMA_VERSION already.    expect(result.written).not.toContain("crates/cotton-store/src/migrate.rs");    expect(result.written.filter((file) => /migrate/.test(file))).toEqual([]);    expect(after["crates/cotton-store/src/schema/table_specs.rs"]).toContain('name: "cotton_timers",');    expect(after["crates/cotton-store/src/schema/table_specs.rs"]).toContain('("running", Codec::Bool),');    expect(after["crates/cotton-store/src/schema/table_specs.rs"]).toContain('fts_into: Some("fts_timers"),');    expect(after["crates/cotton-store/src/schema/fts.rs"]).toContain('fts: "fts_timers",');    expect(after["crates/cotton-store/src/schema/versioned.rs"]).toContain('VersionedTable { table: "cotton_timers", kind: "timer", redact: &[], omit: &[] },');    const search = after["crates/cotton-core/src/rules/search_everything.rs"];    expect(search).toContain('#[serde(rename = "timer")]\n    Timer,');    expect(search).toContain("EverythingKind::Timer => EverythingSection::Timer,");    expect(search).toContain('fts: "fts_timers",');    expect(search).toContain('where_clause: Some("t.trashed_at IS NULL"),');    expect(search).toContain("EverythingKind::Timer => HitExtra {");    const history = after["crates/cotton-core/src/rules/history/fields.rs"];    expect(history).toContain("const TIMER: HistoryKindSpec = HistoryKindSpec {");    expect(history).toContain('ff("seconds", "Seconds", Number),');    expect(history).toContain('restore: Restore::Columns(&["label", "seconds", "running"]),');    expect(history).toContain("VersionRecordKind::Timer => &TIMER,");    expect(after["crates/cotton-core/src/rules/bin.rs"]).toContain("BinKind::Timer => BinSource {");    expect(after["crates/cotton-core/src/design/sections.rs"]).toMatch(/SectionKey::Calendar => &\[[^\]]*PrimitiveKind::Timer/s);    expect(after["crates/cotton-core/src/primitives/words.rs"]).toContain("Timer => {");    const surface = after["crates/cotton-tools/src/mcp/surface.rs"];    expect(surface).toContain('    "timer",\n');    expect(surface).toContain('("timer", VerbSet {');    expect(surface).toContain('list: VerbCell::Tool("list_timers"),');    expect(surface).toMatch(/remove: VerbCell::Not\(r#"A timer is binned/);    expect(after["crates/cotton-tools/src/mcp/catalogue.rs"]).toBe(before["crates/cotton-tools/src/mcp/catalogue.rs"]);    expect(after["crates/cotton-tools/src/mcp/handlers/records_2/search.rs"]).toMatch(/\n    "timer",\n    \/\/ gen-kind: /);    const routes = after["crates/cotton-ffi/src/phone/routes.rs"];    expect(routes).toContain('    "/timers",\n    "/timers/[id]",\n');    expect(after["crates/cotton-ffi/src/phone/reads.rs"]).toContain('name: "timer_list",');    expect(after["crates/cotton-ffi/src/phone/reads.rs"]).toContain('source: ReadSource::ToolWholeSet("list_timers"),');    expect(after["crates/cotton-ffi/src/phone/reads_tests.rs"]).toContain('("timer_list", ListScale::WholeSet),\n    ("timer", ListScale::Record),');    expect(after["crates/cotton-ffi/src/phone/reads.rs"]).toContain('source: ReadSource::Tool("get_timer"),');    const swift = after["apps/cotton/Sources/CottonKit/InvalidationMap.swift"];    expect(swift).toContain("    case timer\n");    expect(swift).toContain('tables: ["cotton_timers"],\n            families: [.timer]');    // Every pinned count moved by exactly one.    const bumped: [string, RegExp][] = [      ["crates/cotton-core/src/rules/search_everything.rs", /EVERYTHING_KINDS: \[EverythingKind; (\d+)\]/],      ["crates/cotton-core/src/rules/search_everything.rs", /EVERYTHING_SECTIONS: \[EverythingSection; (\d+)\]/],      ["crates/cotton-core/src/rules/search_everything.rs", /FTS_LANES: \[FtsLane; (\d+)\]/],      ["crates/cotton-tools/src/mcp/surface.rs", /^\/\/! (\d+) primitives, /m],    ];    for (const [file, pattern] of bumped) {      const was = Number(before[file].match(pattern)?.[1]);      const now = Number(after[file].match(pattern)?.[1]);      const step = 1;      expect(now, `${file} ${pattern}`).toBe(was + step);    }    // …and the facility rows are not counts any more, so there is nothing    // there that must stay put (summarized is still refused by the generator's    // own check).    // No migrator test is written: an old file is refused, never climbed.    expect(result.written.filter((file) => file.startsWith("crates/cotton-store/tests/"))).toEqual(      FILES.filter((file) => file.startsWith("crates/cotton-store/tests/")),    );    // What stays by hand is said, not skipped.    expect(result.handSeams.join("\n")).toContain("schema_snapshot");    expect(result.handSeams.join("\n")).toContain("shape ledger");    expect(result.handSeams.join("\n")).toContain("ToolDef named create_timer");    expect(result.handSeams.join("\n")).toContain("Route.swift");    expect(result.handSeams.join("\n")).toContain("search_everything_tests.rs");  });  it("a machinery kind with no search, history, bin or routes touches only the seams it must", () => {    const root = scratchTree();    const decl: KindDeclaration = {      kind: "sync_lease",      table: "cotton_sync_leases",      why: "A sync lease is the row one Mac holds while it is the one that writes for a workspace, so two never do.",      columns: [{ name: "holder", sql: "TEXT NOT NULL", codec: "Text" }, { name: "until", sql: "TEXT NOT NULL", codec: "Timestamp" }],      title_column: "holder",      facilities: {        fts: "A lease is machinery; nobody searches for one by its holder's name.",        embedded: "Machinery is never embedded.",        search: "A lease is never a search hit.",        versioned: "A lease is overwritten, never edited, so there is no history to keep.",        commentable: "Nobody comments on a lease.",        summarized: "There is nothing to summarise.",        project_linkable: "A lease belongs to a workspace, not a project.",        linkable: "A lease is not a record a person links to.",        route_target: "A capture never becomes a lease.",        addressable: "A lease has no page and no comment thread, so no address.",        binnable: "A lease that lapses is deleted, not binned.",        shareable: "A lease is one Mac's own.",      },      words: {        meaning: "A sync lease is the row one Mac holds while it is the one that writes for a workspace.",        feeds: "The sync worker takes a lease when it starts writing and lets it lapse when it stops.",      },      section: { machinery: "A lease is a fact about the machines, not about the person's life, so it is never a navigator section." },      verbs: {        create: { not: "A lease is taken by the sync worker, never over MCP." },        list: { not: "The Mac's own status screen shows the lease; there is nothing an assistant would list." },        get: { not: "Nothing to get: a lease is a holder and an instant." },        update: { not: "A lease is taken or lapsed, never edited." },        remove: { not: "A lease lapses on its own." },      },    };    expect(validate(decl)).toEqual([]);    const result = runGenKind(decl, root);    expect(result.written).not.toContain("crates/cotton-core/src/rules/bin.rs");    expect(result.written).not.toContain("crates/cotton-core/src/rules/search_everything.rs");    expect(result.written).not.toContain("crates/cotton-core/src/rules/history/fields.rs");    expect(result.written).not.toContain("crates/cotton-store/src/schema/fts.rs");    expect(result.written).not.toContain("crates/cotton-store/src/schema/versioned.rs");    expect(result.written).not.toContain("crates/cotton-ffi/src/phone/routes.rs");    expect(result.written).not.toContain("crates/cotton-tools/src/mcp/catalogue.rs");    const constants = readFileSync(join(root, "crates/cotton-core/src/constants.rs"), "utf8");    expect(count(constants, '        SyncLease => "sync_lease",')).toBe(1);    const sections = readFileSync(join(root, "crates/cotton-core/src/design/sections.rs"), "utf8");    expect(sections).toContain("PrimitiveKind::SyncLease,");    expect(sections).toMatch(/MACHINERY_KINDS: \[\(PrimitiveKind, &str\); 3\]/);    const ddl = readFileSync(join(root, DDL), "utf8");    expect(ddl).toContain("pub const SYNC_LEASES_TABLE: &str");    expect(ddl).not.toContain("SYNC_LEASES_DDL");    expect(ddl).not.toContain("SYNC_LEASES_VERSION_AU");    // No facility CHECK widens for a kind with none of those facilities.    for (const constant of ["COMMENTS_TABLE", "LINKS_TABLE"]) {      const start = ddl.indexOf(`pub const ${constant}: &str = r#"`);      expect(ddl.slice(start, ddl.indexOf('"#;', start)), constant).not.toContain("'sync_lease'");    }    expect(readFileSync(join(root, "apps/cotton/Sources/CottonKit/InvalidationMap.swift"), "utf8")).toContain("    case syncLease\n");    expect(result.shapeLine).toMatch(/^SHAPE \d{4}-\d{2}-\d{2} #<pr> — cotton_sync_leases: absent → id, workspace_id, holder, until, created_at, updated_at, _hlc, _born, an old file has no rows$/);    expect(result.handSeams.join("\n")).not.toContain("ToolDef");    expect(result.handSeams.join("\n")).not.toContain("Route.swift");  });  it("refuses a kind or a table that already exists, and writes nothing", () => {    const root = scratchTree();    const before = readFileSync(join(root, DDL), "utf8");    expect(() => runGenKind({ ...EXAMPLE, kind: "alarm", variant: "Alarm" }, root)).toThrow("alarm is already a record kind");    expect(() => runGenKind({ ...EXAMPLE, table: "cotton_alarms" }, root)).toThrow("cotton_alarms is already a synced table");    expect(() => runGenKind({ ...EXAMPLE, section: "no_such_section" }, root)).toThrow("no section arm for SectionKey::NoSuchSection");    expect(readFileSync(join(root, DDL), "utf8")).toBe(before);  });  it("refuses a declaration with problems before reading a file", () => {    expect(() => runGenKind({ ...EXAMPLE, why: "TODO" }, "/nonexistent")).toThrow("the declaration is refused");  });});