#!/usr/bin/env tsx /** * dev:defects — the reports shaken out of Cotton Dev, turned into folders an * agent can open and one ledger line each. * * pnpm dev:defects one pass over ~/CottonDevHousehold * pnpm dev:defects --watch [--interval 30] keep looking, every S seconds * pnpm dev:defects --data-dir DIR --ledger FILE * * WHERE THE REPORT COMES FROM. Shaking the phone (or Help › Report a problem on * the Mac) writes one `cotton_feedback` row — `body`, `app`, a JSON `context` * with the route, device, OS and the log ring, and `image_sha256` + `image_ext` * (crates/cotton-ffi/src/phone/feedback.rs) — and queues the screenshot into * the content-addressed media store under `{workspace}/walkthroughs/{sha}.{ext}` * (crates/cotton-core/src/media/keys.rs, `walkthrough_image_key`). The serving * Mac keeps each workspace at `/files///life.db` * (crates/cotton-server/src/files.rs, `file_path_for`) and its media store at * `/media` (`Layout::media_dir`, handed to the server as * COTTON_MEDIA_DIR by crates/cotton-ffi/src/shell/controller.rs), keys joined * straight onto it (`object_path_for` in crates/cotton-server/src/media/fs_object_store.rs). * * WHAT IT WRITES, per new row: `/reports//` holding `note.txt`, * `log.txt`, `context.json` (minus the log) and `screen.` — or * `screen.MISSING` naming the path it expected when the picture has not been * uploaded yet; the cursor remembers it and a later pass fills it in without * reporting the row twice. The cursor is `/reports/.cursor.json`. * * READ-ONLY, and NEVER the owner's real folder: every database is opened * `readOnly`, and a data dir that is or sits under the real data folder (or the app's * Application Support folder) is refused after resolving symlinks. */ import { appendFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { basename, dirname, join, resolve, sep } from "node:path"; import { createRequire } from "node:module"; // `node:sqlite` through `require`: the vite inside the scripts' vitest does not // know the module is a builtin and fails to resolve a static import of it. export const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite") as typeof import("node:sqlite"); export interface Args { dataDir: string; ledger: string; watch: boolean; interval: number } export function parseArgs(argv: string[], home = homedir()): Args { // The household server writes `reports/`; not `~/CottonDev`, which is Cotton Dev for Mac's own data folder — one Mac runs both. const args: Args = { dataDir: join(home, "CottonDevHousehold"), ledger: join(home, "ready-to-land.md"), watch: false, interval: 30 }; for (let i = 0; i < argv.length; i++) { const flag = argv[i]; const value = (): string => { const next = argv[++i]; if (next === undefined) throw new Error(`${flag} needs a value`); return next; }; if (flag === "--data-dir") args.dataDir = resolve(value().replace(/^~(?=$|\/)/, home)); else if (flag === "--ledger") args.ledger = resolve(value().replace(/^~(?=$|\/)/, home)); else if (flag === "--watch") args.watch = true; else if (flag === "--interval") { args.interval = Number(value()); if (!(args.interval > 0)) throw new Error("--interval takes a positive number of seconds"); } else throw new Error(`unknown argument ${flag}`); } return args; } /** The path with its nearest existing ancestor resolved through symlinks. */ export function canonical(path: string): string { let head = resolve(path); const tail: string[] = []; while (!existsSync(head) && dirname(head) !== head) { tail.unshift(basename(head)); head = dirname(head); } return join(realpathSync(head), ...tail); } /** A sentence saying why `dataDir` is refused, or null when it is Cotton Dev's to read. */ export function refusal(dataDir: string, home = homedir()): string | null { const target = canonical(dataDir); for (const real of [join(home, "CottonDB"), join(home, "Library", "Application Support", "CottonDB")]) { const root = canonical(real); if (target === root || target.startsWith(root + sep)) { return `dev-defects: refusing ${dataDir} — it is the owner's real data folder (${real}); this script reads only the development household's (~/CottonDevHousehold).`; } } return null; } export interface FeedbackRow { id: string; body: string; app: string | null; context: string | null; image_sha256: string | null; image_ext: string | null; created_at: string; } /** `walkthrough_image_key`'s suffix rule: lowercase alphanumerics, at most 12, dot-prefixed, or nothing. */ export function extSuffix(ext: string): string { const cleaned = ext.replace(/^\./, "").replace(/[^A-Za-z0-9]/g, "").toLowerCase().slice(0, 12); return cleaned ? `.${cleaned}` : ""; } export interface ReportPlan { dir: string; files: Record; image: { from: string; to: string } | null; surface: string; } export function planReport(row: FeedbackRow, workspaceId: string, dataDir: string): ReportPlan { let context: Record = {}; try { const parsed: unknown = JSON.parse(row.context ?? "{}"); if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) context = parsed as Record; } catch { /* an unreadable context is reported as empty, not skipped */ } const { log, ...rest } = context; const dir = join(dataDir, "reports", row.id); const surface = String(rest.surface ?? rest.route ?? "unknown"); const image = row.image_sha256 && row.image_ext ? { from: join(dataDir, "media", workspaceId, "walkthroughs", `${row.image_sha256}${extSuffix(row.image_ext)}`), to: join(dir, `screen${extSuffix(row.image_ext)}`), } : null; return { dir, surface, image, files: { "note.txt": `${row.body}\n`, "log.txt": Array.isArray(log) ? `${log.map(String).join("\n")}\n` : "", "context.json": `${JSON.stringify(rest, null, 2)}\n`, }, }; } export function istClock(at: Date): string { return new Intl.DateTimeFormat("en-GB", { timeZone: "Asia/Kolkata", hour: "2-digit", minute: "2-digit", hour12: false }).format(at); } export function ledgerLine(row: FeedbackRow, surface: string, reportDir: string, now: Date): string { const note = row.body.replace(/\s*[\r\n]+\s*/g, " ").trim(); const cut = note.length > 200 ? `${note.slice(0, 199)}…` : note; return `DEFECT ${row.created_at} cotton-dev ${row.app ?? "unknown"} · ${surface} · "${cut}" · ${reportDir} | ${istClock(now)} IST`; } interface Cursor { workspaces: Record; pending: Record; } function readCursor(path: string): Cursor { try { const parsed = JSON.parse(readFileSync(path, "utf8")) as Partial; return { workspaces: parsed.workspaces ?? {}, pending: parsed.pending ?? {} }; } catch { return { workspaces: {}, pending: {} }; } } /** Every `files///life.db` under the data dir. */ export function workspaceDbs(dataDir: string): Array<{ workspaceId: string; path: string }> { const files = join(dataDir, "files"); if (!existsSync(files)) return []; return readdirSync(files).flatMap((shard) => { const shardDir = join(files, shard); try { return readdirSync(shardDir) .map((workspaceId) => ({ workspaceId, path: join(shardDir, workspaceId, "life.db") })) .filter((each) => existsSync(each.path)); } catch { return []; } }); } /** Copy the picture or leave a `screen.MISSING`; true when the picture landed. */ function placeImage(image: { from: string; to: string }): boolean { const missing = join(dirname(image.to), "screen.MISSING"); if (!existsSync(image.from)) { writeFileSync(missing, `not uploaded yet — expected at ${image.from}\n`); return false; } copyFileSync(image.from, image.to); rmSync(missing, { force: true }); return true; } /** One pass: new rows become report folders and ledger lines; pending pictures are retried. */ export function runPass(args: Pick, now = new Date(), log = console.log): string[] { const reports = join(args.dataDir, "reports"); const cursorPath = join(reports, ".cursor.json"); const cursor = readCursor(cursorPath); const lines: string[] = []; for (const [id, image] of Object.entries(cursor.pending)) { if (placeImage(image)) { delete cursor.pending[id]; log(`picture arrived for ${id}`); } } for (const { workspaceId, path } of workspaceDbs(args.dataDir)) { const db = new DatabaseSync(path, { readOnly: true }); try { const seen = cursor.workspaces[workspaceId] ?? { createdAt: "", id: "" }; const rows = db.prepare( `SELECT id, body, app, context, image_sha256, image_ext, created_at FROM cotton_feedback WHERE parent_id IS NULL AND app IS NOT NULL AND (created_at > ? OR (created_at = ? AND id > ?)) ORDER BY created_at, id`, ).all(seen.createdAt, seen.createdAt, seen.id) as unknown as FeedbackRow[]; for (const row of rows) { const plan = planReport(row, workspaceId, args.dataDir); mkdirSync(plan.dir, { recursive: true }); for (const [name, content] of Object.entries(plan.files)) writeFileSync(join(plan.dir, name), content); if (plan.image && !placeImage(plan.image)) cursor.pending[row.id] = plan.image; const line = ledgerLine(row, plan.surface, plan.dir, now); appendFileSync(args.ledger, `\n${line}\n`); lines.push(line); log(line); cursor.workspaces[workspaceId] = { createdAt: row.created_at, id: row.id }; } } finally { db.close(); } } mkdirSync(reports, { recursive: true }); writeFileSync(cursorPath, `${JSON.stringify(cursor, null, 2)}\n`); const waiting = Object.keys(cursor.pending).length; log(`dev-defects: ${lines.length} new report${lines.length === 1 ? "" : "s"}${waiting ? `, ${waiting} picture${waiting === 1 ? "" : "s"} still to upload` : ""} — ${reports}`); return lines; } async function main(): Promise { const args = parseArgs(process.argv.slice(2)); const refused = refusal(args.dataDir); if (refused) { console.error(refused); process.exit(2); } runPass(args); while (args.watch) { await new Promise((done) => setTimeout(done, args.interval * 1000)); runPass(args); } } // Only run the IO main() when invoked directly, not when imported by a test. const invokedDirectly = process.argv[1] !== undefined && /dev-defects\.ts$/.test(process.argv[1]); if (invokedDirectly) { main().catch((err: unknown) => { console.error(`dev-defects: ${(err as Error).message}`); process.exit(1); }); }