// `archilyzer housekeeping`: the gate (render mode, the heavy slot, an e2e // suite), the parts it runs and their arguments, the summaries, the record // (newest last, capped, skips folded), and one run end to end over a temp // reports root and a temp git repository with real worktrees — nothing here // touches ~/reports, the checkout's worktrees, or the machine's systemd. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test bin/housekeeping.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { RECORD_KEEP, checkSlotFiles, SKIPPED_EXIT, appendRecord, housekeeping, main, readRecord, recordFileFor, runToFile, slotBusy, summarizePrune, summarizeWorktrees, type HousekeepingDeps, type HousekeepingRun, type SlotRead, type SlotState, } from "./housekeeping"; const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const IDLE_SLOT: SlotState = { render: { held: false }, running: [], suites: [] }; const PRUNE_DRY = { dryRun: true, versions: { totals: {}, projects: [ { project: { id: "a/proj" }, skipped: null, lines: [ { takes: [{ id: "draft-2", action: "keep", keep: [{ code: "newest" }], bytes: 0 }, { id: "draft-1", action: "delete", keep: [], bytes: 1000 }] }, { takes: [{ id: "v6c", action: "keep", keep: [{ code: "newest" }, { code: "notes" }], bytes: 0 }] }, ], }, { project: { id: "b/busy" }, skipped: "active: take x modified 5 h ago (--idle 3 d)", lines: [] }, ], }, projects: [ { project: { id: "a/proj" }, idle: { idle: true }, takes: [ { id: "draft-2", status: "prunable", keep: [], freedBytes: 500 }, { id: "pin", status: "kept", keep: [{ code: "pinned" }], freedBytes: 9 }, { id: "v6c", status: "no-work", keep: [], freedBytes: null }, ], }, ], versionsFreedBytes: 1000, workFreedBytes: 500, }; const WT_DRY = { remove: [{ path: "/w/done", branch: "done", bytes: 2000 }], removed: [], failed: [], kept: [ { path: "/r", branch: "main", code: "main", why: "the main worktree" }, { path: "/w/x", branch: "x", code: "unmerged", why: "x is not merged into main" }, { path: "/w/y", branch: "y", code: "unmerged", why: "y is not merged into main" }, ], pinned: [], bytes: 2000, freedBytes: 0, }; type Call = { cmd: string; args: string[]; cwd: string }; function rig(opts: { slot?: SlotRead; prune?: object; wt?: object } = {}) { const root = fs.mkdtempSync(path.join(os.tmpdir(), "housekeeping-test-")); const calls: Call[] = []; const lines: string[] = []; const errors: string[] = []; let free = 100e9; const deps: HousekeepingDeps = { env: {}, out: { log: (s) => lines.push(s), error: (s) => errors.push(s) }, repoRoot: "/repo", worktreeRepo: "/repo", now: () => new Date("2026-11-08T05:00:00Z"), run: (cmd, args, cwd) => { calls.push({ cmd, args, cwd }); free += 1e9; const isWt = args[0].endsWith("worktree.mjs"); return { status: 0, stdout: JSON.stringify(isWt ? opts.wt ?? WT_DRY : opts.prune ?? PRUNE_DRY), stderr: "" }; }, freeBytes: () => free, slot: () => (opts.slot === undefined ? IDLE_SLOT : opts.slot), home: "/home/someone", recordFile: path.join(root, "state", "housekeeping.json"), }; return { root, deps, calls, lines, errors }; } test("the gate: render mode, a job in the heavy slot, an e2e suite — each says why; an idle slot passes", () => { assert.equal(slotBusy(IDLE_SLOT), null); // Fail closed: a slot that cannot be read is a slot that says not now. assert.match(slotBusy(null) ?? "", /could not be read: not deleting blind/); assert.match(slotBusy({ error: "a running job's ticket x does not parse" }) ?? "", /could not be read \(a running job's ticket x does not parse\)/); assert.equal(slotBusy({ ...IDLE_SLOT, render: { held: true, what: "umtool take p --id t" } }), "render mode is on (umtool take p --id t)"); assert.match(slotBusy({ ...IDLE_SLOT, running: [{ what: "render of t (p)", pid: 7 }] }) ?? "", /heavy slot is busy: render of t \(p\) \(pid 7\)/); assert.match(slotBusy({ ...IDLE_SLOT, suites: [{ suite: "e2e-editor", pid: 8 }] }) ?? "", /e2e suite is running: e2e-editor/); }); test("a run the slot turns away is SKIPPED with exit 75: nothing runs, the record says why, and skips fold", async () => { const r = rig({ slot: { ...IDLE_SLOT, render: { held: true, what: "a render" } } }); const one = await housekeeping({}, r.deps); assert.equal(one.code, SKIPPED_EXIT); assert.equal(r.calls.length, 0, "no part runs"); assert.match(one.run.skipped ?? "", /render mode is on/); await housekeeping({}, r.deps); const runs = readRecord(r.deps.recordFile); assert.equal(runs.length, 1, "a skip after a skip replaces it"); assert.equal(runs[0].skips, 2); assert.equal(runs[0].firstSkippedAt, "2026-11-08T05:00:00.000Z"); }); test("an unreadable slot skips the run (exit 75) like a busy one", async () => { const r = rig({ slot: { error: "the heavy slot's directory /x is not there" } }); const { code, run } = await housekeeping({}, r.deps); assert.equal(code, SKIPPED_EXIT); assert.equal(r.calls.length, 0); assert.match(run.skipped ?? "", /could not be read \(the heavy slot's directory \/x is not there\)/); assert.equal(readRecord(r.deps.recordFile)[0].skipped, run.skipped); }); test("checkSlotFiles believes the slot's files only when they read: the directory, the tickets, the holders, render mode", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "housekeeping-slot-")); try { const lock = path.join(root, "heavy-queue.lock"); const render = `${lock}.render.json`; assert.throws(() => checkSlotFiles(path.join(root, "gone", "heavy-queue.lock"), render), /directory .* is not there/); checkSlotFiles(lock, render); // nothing there yet: an idle slot fs.mkdirSync(`${lock}.jobs`); fs.writeFileSync(path.join(`${lock}.jobs`, "1.json"), JSON.stringify({ pid: 1 })); checkSlotFiles(lock, render); fs.writeFileSync(path.join(`${lock}.jobs`, "2.json"), "{ half"); assert.throws(() => checkSlotFiles(lock, render), /a running job's ticket .*2\.json does not parse/); fs.rmSync(path.join(`${lock}.jobs`, "2.json")); fs.writeFileSync(path.join(root, "e2e-editor-queue.lock.holder.json"), "nope"); assert.throws(() => checkSlotFiles(lock, render), /a queue's holder file .* does not parse/); fs.rmSync(path.join(root, "e2e-editor-queue.lock.holder.json")); fs.writeFileSync(render, "{}"); assert.throws(() => checkSlotFiles(lock, render), /render mode's state .* is not one/); fs.writeFileSync(render, JSON.stringify({ token: "t", until: "2099-01-01T00:00:00Z" })); checkSlotFiles(lock, render); } finally { fs.rmSync(root, { recursive: true, force: true }); } }); test("a dry run with the slot busy still plans, says a real run would be skipped, and records nothing", async () => { const r = rig({ slot: { ...IDLE_SLOT, suites: [{ suite: "e2e-umtool", pid: 9 }] } }); const { code, run } = await housekeeping({ dryRun: true }, r.deps); assert.equal(code, 0); assert.equal(r.calls.length, 2); assert.ok(run.errors.some((e) => /a real run would be skipped now: an e2e suite/.test(e))); assert.equal(fs.existsSync(r.deps.recordFile), false); assert.ok(r.calls[0].args.includes("--dry-run") && !r.calls[0].args.includes("--yes")); assert.ok(r.calls[1].args.includes("--dry-run")); }); test("the parts and their arguments: one umtool run (versions, then idle work), then wt prune; --skip leaves each out", async () => { const r = rig(); const { code, run } = await housekeeping({ idle: "5d" }, r.deps); assert.equal(code, 0); assert.deepEqual(r.calls[0].args.slice(1), ["prune", "--all", "--json", "--yes", "--versions", "--idle", "5d", "--grace", "7d", "--idle-work", "5d"]); assert.equal(r.calls[0].args[0], path.join("/repo", "umtool", "bin", "umtool.mjs")); assert.deepEqual(r.calls[1].args.slice(1), ["prune", "--json", "--idle", "5d"]); assert.equal(r.calls[1].cwd, "/repo"); assert.equal(run.by, "cli"); assert.equal(run.free.before, 100e9); assert.equal(run.free.after, 102e9); const s = rig(); await housekeeping({ skip: "takes,worktrees" }, s.deps); assert.equal(s.calls.length, 1); assert.ok(!s.calls[0].args.includes("--versions") && s.calls[0].args.includes("--idle-work")); const w = rig(); const only = await housekeeping({ skip: "takes,work" }, w.deps); assert.equal(w.calls.length, 1); assert.ok(w.calls[0].args[0].endsWith("worktree.mjs")); assert.equal(only.run.parts.takes.skipped, "--skip"); await assert.rejects(housekeeping({ skip: "disk" }, rig().deps), /--skip takes takes, work, worktrees/); await assert.rejects(housekeeping({ idle: "soon" }, rig().deps), /not an age/); await assert.rejects(housekeeping({ grace: "later" }, rig().deps), /--grace: "later" is not an age/); const gr = rig(); await housekeeping({ grace: "14d" }, gr.deps); assert.deepEqual(gr.calls[0].args.slice(gr.calls[0].args.indexOf("--grace"), gr.calls[0].args.indexOf("--grace") + 2), ["--grace", "14d"]); }); test("the summaries: what goes, what is kept by reason, the skipped projects, the idle ones", () => { const { takes, work } = summarizePrune(PRUNE_DRY as never, true); assert.deepEqual(takes.items, [{ what: "a/proj/takes/draft-1", bytes: 1000 }]); assert.deepEqual(takes.kept, { newest: 2, notes: 1 }); assert.equal(takes.bytes, 1000); assert.ok(takes.notes.some((n) => /b\/busy: skipped, active/.test(n))); assert.deepEqual(work.items, [{ what: "a/proj/takes/draft-2 (work files, an idle project)", bytes: 500 }]); assert.deepEqual(work.kept, { pinned: 1 }); assert.ok(work.notes.some((n) => /1 idle project/.test(n))); const wt = summarizeWorktrees(WT_DRY as never, true); assert.deepEqual(wt.items, [{ what: "/w/done (done)", bytes: 2000 }]); assert.deepEqual(wt.kept, { main: 1, unmerged: 2 }); // Applied: the deleted / removed lists, not the plan's. const applied = summarizePrune({ ...PRUNE_DRY, versions: { totals: {}, projects: [{ ...PRUNE_DRY.versions.projects[0], deleted: [{ id: "draft-1", bytes: 999 }], failed: [] }] }, projects: [{ ...PRUNE_DRY.projects[0], pruned: [] }] } as never, false); assert.deepEqual(applied.takes.items, [{ what: "a/proj/takes/draft-1", bytes: 999 }]); const raced = summarizePrune({ ...PRUNE_DRY, versions: { totals: {}, projects: [{ ...PRUNE_DRY.versions.projects[0], deleted: [], failed: [], raced: [{ id: "draft-1", why: "picked since the plan — kept" }] }] }, projects: [{ ...PRUNE_DRY.projects[0], pruned: [], failed: [{ path: "takes/x/", error: "a build started in it (or from it) since the plan: kept", raced: true }] }] } as never, false); assert.ok(raced.takes.notes.includes("a/proj/takes/draft-1 kept: picked since the plan — kept")); assert.ok(raced.work.notes.some((n) => /a\/proj\/takes\/x\/ kept: a build started/.test(n))); assert.deepEqual(applied.work.items, []); }); test("a part that gives no JSON fails the run (exit 1) and says so; the others still run", async () => { const r = rig(); r.deps.run = (cmd, args, cwd) => { r.calls.push({ cmd, args, cwd }); return args[0].endsWith("worktree.mjs") ? { status: 0, stdout: JSON.stringify(WT_DRY), stderr: "" } : { status: 1, stdout: "", stderr: "boom\n" }; }; const { code, run } = await housekeeping({}, r.deps); assert.equal(code, 1); assert.match(run.parts.takes.error ?? "", /umtool prune gave no JSON \(exit 1\): boom/); assert.equal(run.parts.worktrees.ran, true); }); test("the record: newest last, the last 52, at XDG_STATE_HOME unless overridden", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "housekeeping-record-")); const file = path.join(root, "r.json"); const run = (i: number): HousekeepingRun => ({ at: `t${i}`, finishedAt: `t${i}`, by: "timer", dryRun: false, idle: "3d", grace: "7d", skipped: null, free: { path: "/h", before: 1, after: 2 }, parts: {} as never, freedBytes: i, errors: [] }); for (let i = 0; i < RECORD_KEEP + 3; i++) appendRecord(file, run(i)); const runs = readRecord(file); assert.equal(runs.length, RECORD_KEEP); assert.equal(runs[0].at, "t3"); assert.equal(runs.at(-1)?.at, `t${RECORD_KEEP + 2}`); assert.equal(JSON.parse(fs.readFileSync(file, "utf8")).format, "archilyzer-housekeeping"); assert.equal(recordFileFor({}, "/home/u"), "/home/u/.local/state/archilyzer/housekeeping.json"); assert.equal(recordFileFor({ XDG_STATE_HOME: "/s" }, "/home/u"), "/s/archilyzer/housekeeping.json"); assert.equal(recordFileFor({ ARCHILYZER_HOUSEKEEPING_RECORD: "/x.json" }, "/home/u"), "/x.json"); }); test("main prints the summary, or --json, and says where the record is", async () => { const r = rig(); assert.equal(await main({ dryRun: true }, r.deps), 0); const text = r.lines.join("\n"); assert.match(text, /dry run, nothing deleted/); assert.match(text, /superseded takes: 1 would go, 1000 B · kept: newest 2, notes 1/); assert.match(text, /a\/proj\/takes\/draft-1 — 1000 B/); assert.match(text, /worktrees: 1 would go, 2.0 KB · kept: unmerged 2, main 1/); assert.doesNotMatch(text, /record:/, "a dry run records nothing"); r.lines.length = 0; assert.equal(await main({}, r.deps), 0); assert.match(r.lines.join("\n"), /record: .*housekeeping\.json/); r.lines.length = 0; assert.equal(await main({ json: true, dryRun: true }, r.deps), 0); const j = JSON.parse(r.lines.join("\n")); assert.equal(j.dryRun, true); assert.equal(j.record, null); assert.equal(await main({ idle: "x" }, rig().deps), 2); }); // ---- end to end: the real umtool and the real worktree script, on temp data ---- const gitEnv = { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" }; const g = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, env: gitEnv, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); test("end to end: a superseded take and a merged idle worktree go; the newest take and an unmerged worktree stay", async () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "housekeeping-e2e-")); try { const old = new Date("2026-10-01T00:00:00Z"); // A reports root with one project, two takes of one line. const reports = path.join(root, "reports"); const proj = path.join(reports, "proj"); fs.mkdirSync(path.join(proj, "takes"), { recursive: true }); fs.writeFileSync(path.join(proj, "video.manifest.json"), "{}\n"); fs.utimesSync(path.join(proj, "video.manifest.json"), old, old); for (const [id, builtAt] of [["draft-1", "2026-10-01T00:00:00Z"], ["draft-2", "2026-10-02T00:00:00Z"]]) { const t = path.join(proj, "takes", id); fs.mkdirSync(t, { recursive: true }); fs.writeFileSync(path.join(t, "take.json"), JSON.stringify({ id, group: "takes", order: 1, label: id, kind: "different", preview: "preview.mp4", builtAt })); fs.writeFileSync(path.join(t, "preview.mp4"), Buffer.alloc(4096)); for (const f of ["take.json", "preview.mp4"]) fs.utimesSync(path.join(t, f), old, old); } // A repository with a merged, clean worktree (aged) and an unmerged one. const main_ = path.join(root, "repo", "main"); fs.mkdirSync(path.join(main_, "scripts"), { recursive: true }); g(main_, "init", "-q", "-b", "main"); fs.writeFileSync(path.join(main_, "scripts", "worktree.mjs"), "// archilyzer-ports.json\n"); g(main_, "add", "."); g(main_, "commit", "-q", "-m", "base"); const done = path.join(root, "repo", "done"); const open = path.join(root, "repo", "open"); g(main_, "worktree", "add", "-q", "-b", "done", done, "main"); g(main_, "worktree", "add", "-q", "-b", "open", open, "main"); fs.writeFileSync(path.join(open, "f.txt"), "x\n"); g(open, "add", "."); g(open, "commit", "-q", "-m", "open"); const admin = g(done, "rev-parse", "--absolute-git-dir"); for (const f of ["HEAD", "index", "logs/HEAD", "gitdir"]) if (fs.existsSync(path.join(admin, f))) fs.utimesSync(path.join(admin, f), old, old); const env: NodeJS.ProcessEnv = { ...process.env, REPORTS_DIR: reports, UMTOOL_DISK_GUARD: "0" }; delete env.UMTOOL_MEDIA_DIR; const state = path.join(root, "state"); const deps: HousekeepingDeps = { env, out: { log: () => {}, error: () => {} }, repoRoot: REPO, worktreeRepo: main_, now: () => new Date(), run: (cmd, args, cwd) => runToFile(cmd, args, cwd, state, { ...env, ...gitEnv }), freeBytes: () => 1e12, slot: () => IDLE_SLOT, home: root, recordFile: path.join(state, "housekeeping.json"), }; const dry = await housekeeping({ dryRun: true }, deps); assert.equal(dry.code, 0, JSON.stringify(dry.run.errors)); assert.deepEqual(dry.run.parts.takes.items.map((i) => i.what), ["proj/takes/draft-1"]); assert.deepEqual(dry.run.parts.worktrees.items.map((i) => path.basename(i.what.split(" ")[0])), ["done"]); assert.ok(fs.existsSync(path.join(proj, "takes", "draft-1")) && fs.existsSync(done), "a dry run deletes nothing"); const real = await housekeeping({}, deps); assert.equal(real.code, 0, JSON.stringify(real.run.errors)); assert.equal(fs.existsSync(path.join(proj, "takes", "draft-1")), false); assert.ok(fs.existsSync(path.join(proj, "takes", "draft-2", "preview.mp4"))); assert.equal(fs.existsSync(done), false); assert.ok(fs.existsSync(open)); assert.ok(g(main_, "branch", "--list", "done").includes("done"), "the branch is kept"); const runs = readRecord(deps.recordFile); assert.equal(runs.length, 1); assert.equal(runs[0].parts.worktrees.kept.unmerged, 1); assert.equal(runs[0].parts.takes.kept.newest, 1); } finally { fs.rmSync(root, { recursive: true, force: true }); } });