Cotton code
128 lines · 6.4 KB · TypeScriptRaw
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { DatabaseSync, ledgerLine, parseArgs, planReport, refusal, runPass, type FeedbackRow } from "../dev-defects";/** * `dev:defects` — the shake reports of Cotton Dev, read off a serving Mac's * data dir into report folders and one ledger line each. * * The data dir here is a temp directory shaped like a real one: a workspace at * `files/<shard>/<workspace>/life.db` holding a `cotton_feedback` table with * only the columns the script reads, and the screenshot at its media key. The * home folder is a temp directory too, so the refusal is tested without ever * touching the owner's real data folder. */const WORKSPACE = "ws_test";const SHA = "ab".repeat(32);const made: string[] = [];function temp(): string {  const dir = mkdtempSync(join(tmpdir(), "dev-defects-"));  made.push(dir);  return dir;}afterEach(() => {  for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true });});function dataDirWith(rows: Array<Partial<FeedbackRow> & { id: string; parent_id?: string | null }>): string {  const dataDir = temp();  const wsDir = join(dataDir, "files", "3f", WORKSPACE);  mkdirSync(wsDir, { recursive: true });  const db = new DatabaseSync(join(wsDir, "life.db"));  db.exec(`CREATE TABLE cotton_feedback (id TEXT PRIMARY KEY, body TEXT NOT NULL, app TEXT, context TEXT,    image_sha256 TEXT, image_ext TEXT, parent_id TEXT, created_at TEXT NOT NULL)`);  const insert = db.prepare("INSERT INTO cotton_feedback VALUES (?, ?, ?, ?, ?, ?, ?, ?)");  for (const row of rows) {    insert.run(row.id, row.body ?? "it broke", row.app ?? "cotton-ios", row.context ?? null, row.image_sha256 ?? null,      row.image_ext ?? null, row.parent_id ?? null, row.created_at ?? "2026-10-03T08:00:00.000Z");  }  db.close();  return dataDir;}const CONTEXT = JSON.stringify({ env: "dev", platform: "ios", route: "todos/list", device: "iPhone17,1", log: ["boot", "tap todo"] });const quiet = (): void => {};describe("dev:defects", () => {  it("turns one new shake report into a report folder and one ledger line, and a second pass adds nothing", () => {    const dataDir = dataDirWith([      { id: "fb_1", body: "the list\nscrolls under the tab bar", context: CONTEXT, image_sha256: SHA, image_ext: "png" },      { id: "fb_reply", body: "a reply", parent_id: "fb_1" },    ]);    const media = join(dataDir, "media", WORKSPACE, "walkthroughs");    mkdirSync(media, { recursive: true });    writeFileSync(join(media, `${SHA}.png`), "PNGBYTES");    const ledger = join(temp(), "ledger.md");    const first = runPass({ dataDir, ledger }, new Date("2026-10-03T08:30:00Z"), quiet);    expect(first).toHaveLength(1);    const text = readFileSync(ledger, "utf8");    expect(text.match(/^DEFECT /gm)).toHaveLength(1);    const dir = join(dataDir, "reports", "fb_1");    expect(text).toContain(      `DEFECT 2026-10-03T08:00:00.000Z cotton-dev cotton-ios · todos/list · "the list scrolls under the tab bar" · ${dir} | 14:00 IST`,    );    expect(readFileSync(join(dir, "note.txt"), "utf8")).toBe("the list\nscrolls under the tab bar\n");    expect(readFileSync(join(dir, "log.txt"), "utf8")).toBe("boot\ntap todo\n");    const context = JSON.parse(readFileSync(join(dir, "context.json"), "utf8")) as Record<string, unknown>;    expect(context.route).toBe("todos/list");    expect(context).not.toHaveProperty("log");    expect(readFileSync(join(dir, "screen.png"), "utf8")).toBe("PNGBYTES");    expect(runPass({ dataDir, ledger }, new Date(), quiet)).toHaveLength(0);    expect(readFileSync(ledger, "utf8")).toBe(text);  });  it("leaves screen.MISSING for a picture not yet uploaded, and fills it on a later pass without reporting again", () => {    const dataDir = dataDirWith([{ id: "fb_2", context: CONTEXT, image_sha256: SHA, image_ext: "png" }]);    const ledger = join(temp(), "ledger.md");    runPass({ dataDir, ledger }, new Date(), quiet);    const dir = join(dataDir, "reports", "fb_2");    expect(readFileSync(join(dir, "screen.MISSING"), "utf8")).toContain(join("media", WORKSPACE, "walkthroughs", `${SHA}.png`));    const media = join(dataDir, "media", WORKSPACE, "walkthroughs");    mkdirSync(media, { recursive: true });    writeFileSync(join(media, `${SHA}.png`), "LATE");    expect(runPass({ dataDir, ledger }, new Date(), quiet)).toHaveLength(0);    expect(readFileSync(join(dir, "screen.png"), "utf8")).toBe("LATE");    expect(existsSync(join(dir, "screen.MISSING"))).toBe(false);    expect(readFileSync(ledger, "utf8").match(/^DEFECT /gm)).toHaveLength(1);  });  it("collapses newlines and cuts a long note at 200 characters", () => {    const row: FeedbackRow = {      id: "fb_3", body: `${"x".repeat(150)}\n\n${"y".repeat(150)}`, app: "cotton-mac", context: null,      image_sha256: null, image_ext: null, created_at: "2026-10-03T00:00:00Z",    };    const plan = planReport(row, WORKSPACE, "/d");    expect(plan.image).toBeNull();    expect(plan.surface).toBe("unknown");    const line = ledgerLine(row, plan.surface, plan.dir, new Date("2026-10-03T00:00:00Z"));    const quoted = /"([^"]*)"/.exec(line)?.[1] ?? "";    expect(quoted).toHaveLength(200);    expect(quoted).not.toContain("\n");    expect(line.endsWith("| 05:30 IST")).toBe(true);  });  // RULE: The defects script never reads the owner's real data folder (the real app's); it reads only Cotton Dev's.  it("refuses the real data folder, anything under it, the app's Application Support folder, and a symlink into either", () => {    const home = temp();    mkdirSync(join(home, "CottonDB", "files"), { recursive: true });    mkdirSync(join(home, "Library", "Application Support", "CottonDB"), { recursive: true });    symlinkSync(join(home, "CottonDB"), join(home, "sneaky"));    expect(refusal(join(home, "CottonDB"), home)).toMatch(/refusing .* owner's real data folder/);    expect(refusal(join(home, "CottonDB", "files", "not-yet"), home)).not.toBeNull();    expect(refusal(join(home, "Library", "Application Support", "CottonDB"), home)).not.toBeNull();    expect(refusal(join(home, "sneaky", "media"), home)).not.toBeNull();    expect(refusal(join(home, "CottonDev"), home)).toBeNull();    expect(refusal(join(home, "CottonDBX"), home)).toBeNull();    expect(parseArgs([], home).dataDir).toBe(join(home, "CottonDevHousehold"));  });});