// `archilyzer housekeeping [--dry-run] [--json] [--idle 3d] [--skip takes,work,worktrees]` // — FREE DISK, the weekly way (2026-11-06). // // On 6 Nov /home was at 37 GB free and the orchestrator freed 83 GB by hand // (reports/CLEANUP-2026-11-06.md). The operator: "We should build a regularly // run command for this after we're done." This is it, over the apps' own // commands, each with --json — no logic of its own beyond the order, the gate // and the record: // // takes `umtool prune --all --versions --idle ` — whole superseded // takes (umtool/lib/report/takeVersions.mjs); // work `… --idle-work ` in the same run — every project's takes' // work files by its prune policy, and an idle project's newest and // picked takes' work too (takePrune.mjs); // worktrees `node scripts/worktree.mjs prune` — merged, clean, idle // worktrees nobody works in (`git worktree remove`, branches kept). // // THE GATE. Deleting is light, but never beside a render or an e2e/heavy job: // with render mode on, a job running in the heavy slot, or an e2e suite holding // its queue (common/lib/heavyQueue.mjs reads the slot's own files), the run is // SKIPPED — not queued — and the record says why; it exits 75, and the // timer's unit tries again an hour later (for a day). // // THE RECORD: `$XDG_STATE_HOME/archilyzer/housekeeping.json` (default // `~/.local/state/archilyzer/`; ARCHILYZER_HOUSEKEEPING_RECORD overrides), the // runs newest last, the last 52 kept (a year of weekly runs): when, what each // part freed and kept (by reason), what was skipped and why, /home's free bytes // before and after. A dry run deletes nothing and records nothing. // // `archilyzer service install` (host mode) installs archilyzer-housekeeping.timer // to run it weekly (lib/service/units.ts). import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { formatBytes } from "../lib/format"; export const RECORD_FORMAT = "archilyzer-housekeeping"; export const RECORD_KEEP = 52; export const PARTS = ["takes", "work", "worktrees"] as const; export type Part = (typeof PARTS)[number]; export type HousekeepingOptions = { dryRun?: boolean; json?: boolean; idle?: string; // How old the take superseding another must be before that one goes (umtool --grace). grace?: string; skip?: string; // Who ran it: "cli" (default) or "timer" (the unit passes --by timer). by?: string; }; type Out = { log: (s: string) => void; error: (s: string) => void }; type RunResult = { status: number | null; stdout: string; stderr: string }; /** The heavy slot as heavyQueue.mjs reads it — only what the gate asks. */ export type SlotState = { render: { held: boolean; what?: string }; running: { what: string; pid: number }[]; suites: { suite: string; pid: number }[]; }; /** The slot, or why it could not be read (the gate then fails closed). */ export type SlotRead = SlotState | { error: string } | null; export type HousekeepingDeps = { env: NodeJS.ProcessEnv; out: Out; repoRoot: string; now: () => Date; run: (cmd: string, args: string[], cwd: string) => RunResult; freeBytes: (dir: string) => number | null; slot: () => SlotRead; // The repository whose worktrees `wt prune` judges (the checkout itself). worktreeRepo: string; // Where /home's free space is read (the user's home). home: string; recordFile: string; }; /** The record's path: ARCHILYZER_HOUSEKEEPING_RECORD, else $XDG_STATE_HOME (or ~/.local/state)/archilyzer/housekeeping.json. */ export function recordFileFor(env: NodeJS.ProcessEnv, home = os.homedir()): string { if (env.ARCHILYZER_HOUSEKEEPING_RECORD) return env.ARCHILYZER_HOUSEKEEPING_RECORD; const state = env.XDG_STATE_HOME || path.join(home, ".local", "state"); return path.join(state, "archilyzer", "housekeeping.json"); } export async function defaultDeps(): Promise { const { REPO_ROOT } = await import("./_spawnBin"); const { readHeavyQueue } = await import("../lib/heavyQueue.mjs"); const { heavyLockFile, renderPriorityFile } = await import("../lib/renderPriority.mjs"); const home = os.homedir(); return { env: process.env, out: console, repoRoot: REPO_ROOT, worktreeRepo: REPO_ROOT, now: () => new Date(), run: (cmd, args, cwd) => runToFile(cmd, args, cwd, path.dirname(recordFileFor(process.env, home))), freeBytes: (dir) => { try { const s = fs.statfsSync(dir); return Number(s.bavail) * Number(s.bsize); } catch { return null; } }, slot: () => { try { if (!process.env.HEAVY_LOCK_FILE && !gitCommonDirOf(REPO_ROOT)) throw new Error(`${REPO_ROOT} is not a git checkout: the heavy slot's lock cannot be found`); const heavyLock = heavyLockFile(process.env, { root: REPO_ROOT }); const renderFile = renderPriorityFile(process.env, { heavyLock }); checkSlotFiles(heavyLock, renderFile); return readHeavyQueue({ heavyLock, renderFile }) as SlotState; } catch (e) { return { error: e instanceof Error ? e.message : String(e) }; } }, home, recordFile: recordFileFor(process.env, home), }; } /** * Run a command with its stdout in a FILE, read back after. The apps' CLIs * exit right after printing their JSON (`process.exit(await …)`), and a large * write to a pipe is cut off by the exit; a write to a file is synchronous. */ export function runToFile(cmd: string, args: string[], cwd: string, dir: string, env: NodeJS.ProcessEnv = process.env): RunResult { fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, `.housekeeping-${process.pid}-${Date.now()}.out`); const fd = fs.openSync(file, "w"); try { const r = spawnSync(cmd, args, { cwd, env, encoding: "utf8", stdio: ["ignore", fd, "pipe"], maxBuffer: 64 * 1024 * 1024 }); fs.closeSync(fd); return { status: r.status, stdout: fs.readFileSync(file, "utf8"), stderr: r.stderr ?? (r.error ? String(r.error.message) : "") }; } finally { try { fs.closeSync(fd); } catch { /* closed */ } fs.rmSync(file, { force: true }); } } function gitCommonDirOf(root: string): string | null { const r = spawnSync("git", ["-C", root, "rev-parse", "--path-format=absolute", "--git-common-dir"], { encoding: "utf8" }); return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null; } /** * The slot's own files, checked before they are believed: the lock's directory * is there; the running and waiting ticket directories, when present, can be * listed and every ticket in them parses; every e2e suite's holder file * parses; render mode's state file, when present, parses as one. Throws the * first that does not -- heavyQueue.mjs reads an unreadable file as "nothing * there", which for a deleter would be "go". */ export function checkSlotFiles(heavyLock: string, renderFile: string): void { const dir = path.dirname(heavyLock); if (!fs.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) throw new Error(`the heavy slot's directory ${dir} is not there`); const parses = (file: string, what: string) => { let text: string; try { text = fs.readFileSync(file, "utf8"); } catch (e) { if ((e as NodeJS.ErrnoException).code === "ENOENT") return; // gone since it was listed: its job ended throw new Error(`${what} ${file} cannot be read (${(e as Error).message})`); } try { JSON.parse(text); } catch { throw new Error(`${what} ${file} does not parse`); } }; for (const [d, what] of [[`${heavyLock}.jobs`, "a running job's ticket"], [`${heavyLock}.waiting`, "a waiting job's ticket"]] as const) { if (!fs.existsSync(d)) continue; let names: string[]; try { names = fs.readdirSync(d); } catch (e) { throw new Error(`${d} cannot be listed (${(e as Error).message})`); } for (const n of names) if (n.endsWith(".json")) parses(path.join(d, n), what); } for (const n of fs.readdirSync(dir)) { if (/^e2e(-[a-z0-9-]+)?-queue\.lock\.holder\.json$/.test(n) || n === `${path.basename(heavyLock)}.holder.json`) parses(path.join(dir, n), "a queue's holder file"); } if (fs.existsSync(renderFile)) { parses(renderFile, "render mode's state"); const j = JSON.parse(fs.readFileSync(renderFile, "utf8")); if (!j || typeof j !== "object" || typeof j.token !== "string") throw new Error(`render mode's state ${renderFile} is not one`); } } /** Why the slot says not now, or null. A slot that cannot be read says not now too (fail closed). */ export function slotBusy(s: SlotRead): string | null { if (!s) return "the heavy slot's state could not be read: not deleting blind"; if ("error" in s) return `the heavy slot's state could not be read (${s.error}): not deleting blind`; if (s.render?.held) return `render mode is on${s.render.what ? ` (${s.render.what})` : ""}`; if (s.running?.length) return `the heavy slot is busy: ${s.running.map((r) => `${r.what} (pid ${r.pid})`).join("; ")}`; if (s.suites?.length) return `an e2e suite is running: ${s.suites.map((x) => `${x.suite} (pid ${x.pid})`).join("; ")}`; return null; } /** An age as the apps take it: 3d, 12h, 90m, or a number of days. */ export function checkAge(v: string, flag = "--idle"): string { if (!/^\d+(\.\d+)?(d|h|m)?$/.test(v)) throw new Error(`${flag}: "${v}" is not an age (3d, 12h, 90m)`); return v; } function parseSkip(v: string | undefined): Set { const out = new Set(); for (const s of (v ?? "").split(",").map((x) => x.trim()).filter(Boolean)) { if (!(PARTS as readonly string[]).includes(s)) throw new Error(`--skip takes ${PARTS.join(", ")} — not "${s}"`); out.add(s as Part); } return out; } const tally = (codes: string[]) => { const t: Record = {}; for (const c of codes) t[c] = (t[c] ?? 0) + 1; return t; }; // The umtool JSON, as much of it as the summary reads. type VersionTake = { id: string; action: "keep" | "delete"; keep: { code: string }[]; bytes: number }; type VersionProject = { project: { id: string }; skipped?: string | null; error?: string; lines?: { takes: VersionTake[] }[]; deleted?: { id: string; bytes: number }[]; failed?: { id: string; error: string }[]; raced?: { id: string; why: string }[]; }; type WorkTake = { id: string; status: string; keep: { code: string }[]; freedBytes: number | null }; type WorkProject = { project: { id: string }; error?: string; idle?: { idle: boolean }; takes?: WorkTake[]; pruned?: { id: string; freedBytes: number }[]; failed?: { path: string; error: string; raced?: boolean }[]; freedBytes?: number; }; type PruneJson = { versions?: { totals: Record; projects: VersionProject[] }; projects?: WorkProject[]; versionsFreedBytes: number; workFreedBytes: number }; type WorktreeJson = { remove: { path: string; branch: string; bytes: number | null }[]; removed: { path: string; branch: string; bytes: number | null }[]; failed: { path: string; error: string }[]; kept: { path: string; branch: string | null; code?: string; why: string }[]; pinned: unknown[]; bytes: number; freedBytes: number; }; export type PartSummary = { ran: boolean; skipped?: string; error?: string; bytes: number; // freed, or (dry run) what it would free items: { what: string; bytes: number | null }[]; // what went (or would) kept: Record; // by reason code notes: string[]; }; const blank = (): PartSummary => ({ ran: false, bytes: 0, items: [], kept: {}, notes: [] }); /** The takes and work parts, from `umtool prune --json`. */ export function summarizePrune(j: PruneJson, dryRun: boolean): { takes: PartSummary; work: PartSummary } { const takes = blank(); const work = blank(); if (j.versions) { takes.ran = true; takes.bytes = j.versionsFreedBytes ?? 0; const all: VersionTake[] = []; for (const p of j.versions.projects) { if (p.error) { takes.notes.push(`${p.project.id}: ${p.error}`); continue; } if (p.skipped) { takes.notes.push(`${p.project.id}: skipped, ${p.skipped}`); continue; } const ts = (p.lines ?? []).flatMap((l) => l.takes); all.push(...ts); const gone = dryRun ? ts.filter((t) => t.action === "delete").map((t) => ({ id: t.id, bytes: t.bytes })) : p.deleted ?? []; for (const d of gone) takes.items.push({ what: `${p.project.id}/takes/${d.id}`, bytes: d.bytes }); for (const r of p.raced ?? []) takes.notes.push(`${p.project.id}/takes/${r.id} kept: ${r.why}`); for (const f of p.failed ?? []) takes.notes.push(`${p.project.id}/takes/${f.id} not deleted: ${f.error}`); } takes.kept = tally(all.filter((t) => t.action === "keep").flatMap((t) => t.keep.map((r) => r.code))); } if (j.projects) { work.ran = true; work.bytes = j.workFreedBytes ?? 0; const kept: string[] = []; let idle = 0; for (const p of j.projects) { if (p.error) { work.notes.push(`${p.project.id}: ${p.error}`); continue; } if (p.idle?.idle) idle += 1; const gone = dryRun ? (p.takes ?? []).filter((t) => t.status === "prunable").map((t) => ({ id: t.id, freedBytes: t.freedBytes ?? 0 })) : p.pruned ?? []; for (const g of gone) work.items.push({ what: `${p.project.id}/takes/${g.id} (work files${p.idle?.idle ? ", an idle project" : ""})`, bytes: g.freedBytes }); for (const t of p.takes ?? []) if (t.status === "kept") kept.push(...t.keep.map((r) => r.code)); for (const f of p.failed ?? []) work.notes.push(f.raced ? `${p.project.id}/${f.path} kept: ${f.error}` : `${p.project.id}/${f.path} not removed: ${f.error}`); } work.kept = tally(kept); if (idle) work.notes.push(`${idle} idle project(s): their newest and picked takes' work goes too`); } return { takes, work }; } /** The worktrees part, from `wt prune --json`. */ export function summarizeWorktrees(j: WorktreeJson, dryRun: boolean): PartSummary { const s = blank(); s.ran = true; s.bytes = dryRun ? j.bytes : j.freedBytes; for (const r of dryRun ? j.remove : j.removed) s.items.push({ what: `${r.path} (${r.branch})`, bytes: r.bytes }); s.kept = tally(j.kept.map((k) => k.code ?? "kept")); for (const f of j.failed) s.notes.push(`${f.path} not removed: ${f.error}`); return s; } export type HousekeepingRun = { at: string; finishedAt: string; by: string; dryRun: boolean; idle: string; grace: string; skipped: string | null; free: { path: string; before: number | null; after: number | null }; parts: Record; freedBytes: number; errors: string[]; // Consecutive skipped runs, folded into one entry. skips?: number; firstSkippedAt?: string; }; /** What a run the heavy slot turned away exits with (EX_TEMPFAIL): the timer's unit tries again. */ export const SKIPPED_EXIT = 75; /** Read the record's runs, oldest first ([] when there is none, or it is not one). */ export function readRecord(file: string): HousekeepingRun[] { try { const j = JSON.parse(fs.readFileSync(file, "utf8")); return j?.format === RECORD_FORMAT && Array.isArray(j.runs) ? j.runs : []; } catch { return []; } } /** * Append a run to the record (newest last, the last RECORD_KEEP), tmp + rename. * A skipped run after a skipped run replaces it (counting `skips`), so a day * of hourly retries behind a long render is one entry, not 24. */ export function appendRecord(file: string, run: HousekeepingRun): void { let runs = readRecord(file); const last = runs[runs.length - 1]; if (run.skipped && last?.skipped) { run = { ...run, skips: (last.skips ?? 1) + 1, firstSkippedAt: last.firstSkippedAt ?? last.at }; runs = runs.slice(0, -1); } fs.mkdirSync(path.dirname(file), { recursive: true }); const doc = { format: RECORD_FORMAT, version: 1, runs: [...runs, run].slice(-RECORD_KEEP) }; const tmp = `${file}.${process.pid}.tmp`; fs.writeFileSync(tmp, JSON.stringify(doc, null, 2) + "\n"); fs.renameSync(tmp, file); } function parseJson(r: RunResult, what: string): T { try { return JSON.parse(r.stdout) as T; } catch { const why = (r.stderr || r.stdout || `exit ${r.status}`).trim().split("\n").slice(-3).join(" / "); throw new Error(`${what} gave no JSON (exit ${r.status}): ${why}`); } } /** HOUSEKEEPING: the gate, the parts in order, the summary, the record. */ export async function housekeeping(opts: HousekeepingOptions, deps: HousekeepingDeps): Promise<{ code: number; run: HousekeepingRun }> { const dryRun = opts.dryRun === true; const idle = checkAge(opts.idle ?? "3d"); const grace = checkAge(opts.grace ?? "7d", "--grace"); const skip = parseSkip(opts.skip); const at = deps.now(); const parts = { takes: blank(), work: blank(), worktrees: blank() } as Record; const errors: string[] = []; const before = deps.freeBytes(deps.home); const busy = slotBusy(deps.slot()); const node = process.execPath; const skipped = busy && !dryRun ? `skipped: ${busy}` : null; if (busy && dryRun) errors.push(`a real run would be skipped now: ${busy}`); for (const p of skip) parts[p].skipped = "--skip"; if (!skipped) { // takes + work: one umtool run (versions first, then the work files). if (!skip.has("takes") || !skip.has("work")) { const args = [path.join(deps.repoRoot, "umtool", "bin", "umtool.mjs"), "prune", "--all", "--json", dryRun ? "--dry-run" : "--yes"]; if (!skip.has("takes")) args.push("--versions", "--idle", idle, "--grace", grace); if (!skip.has("work")) args.push("--idle-work", idle); try { const r = deps.run(node, args, deps.repoRoot); const j = parseJson(r, "umtool prune"); const s = summarizePrune(j, dryRun); if (!skip.has("takes")) parts.takes = s.takes; if (!skip.has("work")) parts.work = s.work; if (r.status !== 0) errors.push(`umtool prune exited ${r.status}: ${(r.stderr || "").trim().split("\n").slice(-2).join(" / ")}`); } catch (e) { const msg = e instanceof Error ? e.message : String(e); errors.push(msg); for (const p of ["takes", "work"] as const) if (!skip.has(p)) parts[p].error = msg; } } if (!skip.has("worktrees")) { try { const r = deps.run(node, [path.join(deps.repoRoot, "scripts", "worktree.mjs"), "prune", "--json", ...(dryRun ? ["--dry-run"] : []), "--idle", idle], deps.worktreeRepo); parts.worktrees = summarizeWorktrees(parseJson(r, "wt prune"), dryRun); if (r.status !== 0) errors.push(`wt prune exited ${r.status}`); } catch (e) { const msg = e instanceof Error ? e.message : String(e); errors.push(msg); parts.worktrees.error = msg; } } } const run: HousekeepingRun = { at: at.toISOString(), finishedAt: deps.now().toISOString(), by: opts.by ?? "cli", dryRun, idle, grace, skipped, free: { path: deps.home, before, after: deps.freeBytes(deps.home) }, parts, freedBytes: PARTS.reduce((n, p) => n + (parts[p].bytes ?? 0), 0), errors, }; if (!dryRun) { try { appendRecord(deps.recordFile, run); } catch (e) { errors.push(`the record ${deps.recordFile} was not written: ${e instanceof Error ? e.message : e}`); } } const failed = PARTS.some((p) => parts[p].error) || errors.some((e) => !e.startsWith("a real run would be skipped")); return { code: skipped ? SKIPPED_EXIT : failed ? 1 : 0, run }; } const WORDS: Record = { takes: "superseded takes", work: "work files", worktrees: "worktrees" }; /** The run as lines for a person. */ export function summaryLines(run: HousekeepingRun, recordFile: string | null): string[] { const b = (n: number | null) => (n === null ? "?" : formatBytes(n)); const out = [`housekeeping ${run.at.slice(0, 16).replace("T", " ")}${run.dryRun ? " — dry run, nothing deleted" : ""} (idle ${run.idle}, grace ${run.grace})`]; out.push(`${run.free.path}: ${b(run.free.before)} free`); if (run.skipped) out.push(run.skipped); for (const p of PARTS) { const s = run.parts[p]; if (s.skipped) { out.push(`${WORDS[p]}: skipped (${s.skipped})`); continue; } if (s.error) { out.push(`${WORDS[p]}: FAILED — ${s.error}`); continue; } if (!s.ran) continue; const kept = Object.entries(s.kept).sort((x, y) => y[1] - x[1]).map(([k, n]) => `${k} ${n}`).join(", "); out.push(`${WORDS[p]}: ${s.items.length} ${run.dryRun ? "would go" : "gone"}, ${b(s.bytes)}${kept ? ` · kept: ${kept}` : ""}`); for (const i of s.items) out.push(` ${i.what}${i.bytes !== null ? ` — ${b(i.bytes)}` : ""}`); for (const n of s.notes) out.push(` note: ${n}`); } for (const e of run.errors) out.push(`! ${e}`); const delta = run.free.before !== null && run.free.after !== null ? run.free.after - run.free.before : null; out.push(`${run.free.path}: ${b(run.free.after)} free${delta !== null && delta !== 0 ? ` (${delta > 0 ? "+" : "−"}${b(Math.abs(delta))})` : ""}; ${run.dryRun ? "would free" : "freed"} about ${b(run.freedBytes)}`); if (recordFile) out.push(`record: ${recordFile}`); return out; } export async function main(opts: HousekeepingOptions, deps?: HousekeepingDeps): Promise { const d = deps ?? (await defaultDeps()); try { const { code, run } = await housekeeping(opts, d); if (opts.json) d.out.log(JSON.stringify({ ...run, record: run.dryRun ? null : d.recordFile }, null, 2)); else for (const l of summaryLines(run, run.dryRun ? null : d.recordFile)) d.out.log(l); return code; } catch (e) { d.out.error(e instanceof Error ? e.message : String(e)); return 2; } }