import { test } from "node:test"; import assert from "node:assert/strict"; import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test lib/doNotCleanGate.test.ts // // THE ONE WRITER OF do-not-clean.json, ENFORCED (lane mark-provenance). Every // mark says who set it only if every write goes through lib/doNotClean-server.ts // (setDoNotClean, which requires the writer's provenance, and the backfill's // relabel and the opt-in's audioRemoved note beside it). A context-blind grep // over every source file of the workspace, tests and e2e specs excepted (they // build fixtures): no other file may name the sidecar's handle, its file-name // constant or its file name on a code line. Comments may. const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const ROOTS = ["common", "editor", "umtool", "mcp", "scripts", "export", "homepage", "plans"]; // Build and test output, never source. `out-private` is the homepage's private // build (gitignored): it holds the published source tree — a copy of every // file this gate reads, the one writer and its allow-list among them. const SKIP_DIRS = new Set(["node_modules", ".next", "out", "out-private", "dist", "public", "e2e", ".e2e-song", "test-results", ".git", "coverage"]); const EXT = /\.(ts|tsx|mts|cts|js|mjs|cjs)$/; const TEST = /\.(test|spec)\.[cm]?[jt]sx?$|\.unit\.ts$/; // The files that may name it, and why. const ALLOWED = new Map([ ["common/lib/doNotClean.ts", "declares the file name"], ["common/lib/doNotClean-server.ts", "THE writer"], ["plans/tools/phase3-files-numbers.ts", "a read-only count of sidecars (loads through loadDoNotClean)"], ]); export const FORBIDDEN = [/do-not-clean\.json/, /\bdoNotCleanSidecar\b/, /\bDO_NOT_CLEAN_FILENAME\b/]; // A line's code, with `//` comments and block-comment lines dropped. export function codeOf(line: string): string { const t = line.trim(); if (t.startsWith("//") || t.startsWith("*") || t.startsWith("/*")) return ""; const i = line.indexOf("//"); // A `//` inside a string (a URL) is rare in these files; good enough for a gate. return i >= 0 && !/["'`][^"'`]*\/\//.test(line.slice(0, i + 2)) ? line.slice(0, i) : line; } export function offendingLines(text: string): number[] { const out: number[] = []; text.split("\n").forEach((line, i) => { const code = codeOf(line); if (FORBIDDEN.some((re) => re.test(code))) out.push(i + 1); }); return out; } async function* walk(dir: string): AsyncGenerator { const entries = await readdir(dir, { withFileTypes: true }).catch(() => []); for (const e of entries) { if (e.isDirectory()) { if (SKIP_DIRS.has(e.name) || e.name.startsWith(".")) continue; yield* walk(path.join(dir, e.name)); } else if (e.isFile() && EXT.test(e.name) && !TEST.test(e.name)) { yield path.join(dir, e.name); } } } test("the gate itself: a write outside the writer is caught; a comment is not", () => { assert.deepEqual(offendingLines(`// do-not-clean.json is set by the toggle\nawait writeFile(path.join(dir, "do-not-clean.json"), "{}");`), [2]); assert.deepEqual(offendingLines(`await doNotCleanSidecar.write(dir, {});`), [1]); assert.deepEqual(offendingLines(`const f = path.join(dir, DO_NOT_CLEAN_FILENAME);`), [1]); assert.deepEqual(offendingLines(` * the do-not-clean.json marker`), []); }); test("nothing but lib/doNotClean-server.ts writes do-not-clean.json", async () => { const offenders: string[] = []; const seen = new Set(); for (const root of ROOTS) { for await (const file of walk(path.join(REPO, root))) { const rel = path.relative(REPO, file).split(path.sep).join("/"); const lines = offendingLines(await readFile(file, "utf8")); if (lines.length === 0) continue; seen.add(rel); if (!ALLOWED.has(rel)) offenders.push(`${rel}:${lines.join(",")}`); } } assert.deepEqual(offenders, [], "write a do-not-clean mark through lib/doNotClean-server.ts (setDoNotClean, with its writer)"); // The allow-list cannot rot: every entry still names it. for (const rel of ALLOWED.keys()) assert.ok(seen.has(rel), `${rel} no longer names it: drop it from ALLOWED`); });