Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit ee38bba035376071aa6c6c23c00bbdd66871d09e
parent f2e7d2fe3d2d8976b025a105176afe62485f21e9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 13:49:01 -0500

common: `archilyzer housekeeping` frees disk weekly over the apps' own commands; service install adds its timer

The 6 Nov cleanup, as a command a cheaper model or a timer can run
(operator: "We should build a regularly run command for this after we're
done"). bin/housekeeping.ts runs, in order and each with --json:
- `umtool prune --all --versions --idle D --idle-work D` (superseded takes,
  then every project's work files, an idle one's newest and picked too);
- `node scripts/worktree.mjs prune --idle D` (merged, clean, idle worktrees
  nobody works in; branches kept).
It prints what each part freed and kept, by reason, and the home
filesystem's free space before and after, and appends the run to
$XDG_STATE_HOME/archilyzer/housekeeping.json (the last 52, newest last;
ARCHILYZER_HOUSEKEEPING_RECORD overrides; a dry run records nothing).
The gate: with render mode on, a job in the heavy slot or an e2e suite
holding its queue (heavyQueue.mjs), the run is skipped, not queued, exit 75,
and consecutive skips fold into one record entry. --skip takes,work,worktrees
leaves parts out. A child's stdout goes to a file: the apps exit right after
printing, and a large JSON written to a pipe was cut off.

`archilyzer service install` (host mode) writes archilyzer-housekeeping.timer
(OnCalendar=weekly, Persistent=true, RandomizedDelaySec=30m) and the oneshot
archilyzer-housekeeping.service (node --import tsx from common/, Nice=10,
idle I/O, MemoryMax=2G; exit 75 forces a restart an hour later, at most 24 a
day); only the timer is enabled. --no-housekeeping leaves the pair out; not
in docker mode. `service status` shows the timer's next and last trigger and
the last recorded run; `service restart` never touches the pair (restarting
the oneshot would run it); uninstall disables the timer and removes both.

Docs: OPERATING.md "Free disk", COMMANDS.md and ENVIRONMENT.md regenerated
(XDG_STATE_HOME, ARCHILYZER_HOUSEKEEPING_RECORD), the changelog. Tests: the
gate, the skip and its folding, a dry run beside a busy slot, the parts'
arguments and --skip, the summaries, a part with no JSON, the record's cap
and place, main's output, and one run end to end over a temp reports root and
a temp repository with real worktrees; the units byte for byte, and install,
status, restart and uninstall with the pair against a fake systemctl.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 7++++---
MENVIRONMENT.md | 2++
MOPERATING.md | 38++++++++++++++++++++++++++++++++++++++
Mcommon/bin/archilyzer.ts | 23++++++++++++++++++++---
Acommon/bin/housekeeping.test.ts | 306+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/housekeeping.ts | 443+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/bin/service.test.ts | 48++++++++++++++++++++++++++++++++++++++++++------
Mcommon/bin/service.ts | 47+++++++++++++++++++++++++++++++++++++++--------
Mcommon/lib/envVars.ts | 2++
Mcommon/lib/service/units.test.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/service/units.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 1+
Mscripts/worktree.mjs | 24++++++++++++------------
13 files changed, 1022 insertions(+), 32 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -104,12 +104,13 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer settings example` | `[--check]` | write settings.json.example + SETTINGS.md from the schema | | `archilyzer tts setup` | `[--engine kokoro\|orpheus\|espeak-ng] [--from <dir>] [--python <py>] [--check]` | install a text-to-speech engine under settings.tts.home/&lt;engine&gt; (default ~/.local/share/archilyzer/tts/&lt;engine&gt;): a python venv with its pinned packages (uv venv --python 3.12 when uv is on PATH, else --python &lt;py&gt; -m venv) — kokoro-onnx for kokoro, onnxruntime and numpy for orpheus — and its model files, downloaded once (kokoro: the kokoro-onnx model-files-v1.0 release; orpheus: the Q8\_0 GGUF and the SNAC decoder from Hugging Face, 3.5 GB) one stream at a time with no retries, verified by size and sha256; --from &lt;dir&gt; takes already-downloaded model files from &lt;dir&gt; instead (hard links where it can, else copies; verified the same way); orpheus's llama-server is not installed here (settings.tts.orpheus.serverBin) but is checked; --check installs nothing, lists what is missing and exits 1 when anything is | | `archilyzer voice setup` | `--engine deepfilternet\|openvoice\|seed-vc\|rnnoise [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check]` | install a voice engine under settings.voice.home/&lt;engine&gt; (default ~/.local/share/archilyzer/voice/&lt;engine&gt;), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python &lt;py&gt; -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from &lt;dir&gt; takes already-downloaded files from &lt;dir&gt;/&lt;name&gt; (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is | -| `archilyzer service install` | `[--mode docker\|host] [--apps <a,b>] [--sites <id>:<port>,…] [--overlays <name,…>\|none] [--bind <host>] [--editor-port <n>] [--umtool-port <n>] [--editor-memory <N>G] [--umtool-memory <N>G] [--idle-boot] [--linger] [--no-start] [--force] [--dry-run]` | install the apps as systemd USER units and start them: docker mode (the default when `docker compose` answers) is ONE unit, archilyzer.service, running `docker compose up` in the foreground with a profile per --apps (editor, umtool, site, homepage, ollama; default editor) and the overlays given or found (anthropic when the key file exists, storage when docker-compose.storage.yml does); host mode is archilyzer-editor.service and archilyzer-umtool.service (node running `next start` from the app dir, -H --bind default 0.0.0.0, ports 3001/3050, MemoryHigh/Max sized from MemTotal) plus archilyzer-site-&lt;id&gt;.service per --sites (a built bundle on 127.0.0.1); each unit refuses to start while its build or image is missing. A unit already installed under the same name is ADOPTED when identical and shown as a diff and refused when not (--force replaces it; a running unit is not restarted); --no-start enables without starting; --linger runs loginctl enable-linger (start at boot with nobody logged in); --dry-run prints the units and commands and writes nothing. Linux and systemd only | -| `archilyzer service status` | | read-only: each installed archilyzer unit's state, enablement and pid; for an app its build id, its port and what / answers; the transcription lane's held state; in docker mode each container | +| `archilyzer service install` | `[--mode docker\|host] [--apps <a,b>] [--sites <id>:<port>,…] [--overlays <name,…>\|none] [--bind <host>] [--editor-port <n>] [--umtool-port <n>] [--editor-memory <N>G] [--umtool-memory <N>G] [--idle-boot] [--no-housekeeping] [--linger] [--no-start] [--force] [--dry-run]` | install the apps as systemd USER units and start them: docker mode (the default when `docker compose` answers) is ONE unit, archilyzer.service, running `docker compose up` in the foreground with a profile per --apps (editor, umtool, site, homepage, ollama; default editor) and the overlays given or found (anthropic when the key file exists, storage when docker-compose.storage.yml does); host mode is archilyzer-editor.service and archilyzer-umtool.service (node running `next start` from the app dir, -H --bind default 0.0.0.0, ports 3001/3050, MemoryHigh/Max sized from MemTotal) plus archilyzer-site-&lt;id&gt;.service per --sites (a built bundle on 127.0.0.1) and archilyzer-housekeeping.timer, weekly and Persistent, starting the oneshot archilyzer-housekeeping.service (`archilyzer housekeeping --by timer`; a run the heavy slot turns away exits 75 and is retried hourly for a day; --no-housekeeping leaves the pair out); each unit refuses to start while its build or image is missing. A unit already installed under the same name is ADOPTED when identical and shown as a diff and refused when not (--force replaces it; a running unit is not restarted); --no-start enables without starting; --linger runs loginctl enable-linger (start at boot with nobody logged in); --dry-run prints the units and commands and writes nothing. Linux and systemd only | +| `archilyzer service status` | | read-only: each installed archilyzer unit's state, enablement and pid; for an app its build id, its port and what / answers; the transcription lane's held state; in docker mode each container; for archilyzer-housekeeping.timer its next and last trigger and the last recorded run | | `archilyzer service logs` | `[--apps <a,b>] [--lines <n>] [--follow]` | the units' journal (journalctl --user), the last 200 lines by default | -| `archilyzer service restart` | `[--apps <a,b>] [--dry-run]` | restart the installed units (all, or the named apps: editor, umtool, site-&lt;id&gt;, docker) — the editor's running jobs are stopped by its shutdown reaper | +| `archilyzer service restart` | `[--apps <a,b>] [--dry-run]` | restart the installed units (all, or the named apps: editor, umtool, site-&lt;id&gt;, docker) — the editor's running jobs are stopped by its shutdown reaper; never the housekeeping pair (restarting its oneshot would run it) | | `archilyzer service uninstall` | `[--mode docker\|host] [--apps <a,b>] [--dry-run]` | stop, disable and remove the units (volumes, builds and the corpus are untouched) | | `archilyzer service storage-overlay` | `[--corpus <dir>] [--out <file>] [--check] [--dry-run]` | write docker-compose.storage.yml: every storage location's root, and every channel media link or saved-video store link no location covers, bind-mounted into the editor and umtool at the SAME absolute path (the links are absolute); --corpus also mounts a host corpus at /data/transcripts in place of the volume; read off the corpus disk only (no media drive is touched) | +| `archilyzer housekeeping` | `[--dry-run] [--json] [--idle 3d] [--skip takes,work,worktrees] [--by cli\|timer]` | free disk over the apps' own commands: whole superseded takes (`umtool prune --all --versions`: per version line — the take id, digits folded, letters never — the newest built is kept, and any take picked, pinned, rendering, a base, noted on or refused by `umtool takes delete`), every project's takes' work files by its prune policy and an idle project's newest and picked takes' too (`--idle-work`), and merged, clean, idle worktrees nobody works in (`pnpm wt prune`: `git worktree remove`, branches kept); a project or worktree touched within --idle is left alone. SKIPPED, not queued, while render mode is on, a job runs in the heavy slot or an e2e suite holds its queue. Prints what each part freed and kept (by reason) and the home filesystem's free space before and after, and appends the run to $XDG\_STATE\_HOME/archilyzer/housekeeping.json (the last 52; ARCHILYZER\_HOUSEKEEPING\_RECORD overrides). --dry-run deletes nothing and records nothing. `archilyzer service install` runs it weekly (archilyzer-housekeeping.timer) | | `archilyzer doctor` | `[--json]` | read-only report: node, the checkout, the corpus, settings, every tool, the port block; exit 1 on a failure | | `archilyzer release show` | `[editor\|export]` | latest release, its date, how many bullets wait under \[Unreleased\] | | `archilyzer release cut` | `<editor\|export\|all> <X.Y.Z\|next\|next-minor> [--commit] [--date YYYY-MM-DD]` | \[Unreleased\] -&gt; a dated heading; all = both, one version, two commits | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -74,6 +74,8 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `ARCHILYZER_SOURCE_REPO` | this checkout's git common dir | The git DIR `archilyzer source publish` mirrors `main` from, when the checkout has none: in Docker, `/data/source.git`, the host's git common dir mounted read-only by docker-compose.source.yml. A value that names nothing refuses the publish. | common/publish/source.ts, common/bin/doctor.ts, docker/entrypoint.sh | | `YTDLP_SOURCE_HOST_DIR` | — (required by the overlay) | Docker: the HOST path of a yt-dlp source checkout (the directory holding `yt_dlp/`), mounted read-only at `/opt/yt-dlp-src` by docker-compose.ytdlp.yml. See [RUNNING_IN_DOCKER.md](RUNNING_IN_DOCKER.md), "Substituting yt-dlp". | docker-compose.ytdlp.yml | | `YTDLP_AUTO_UPDATE` | off | Docker: `1` runs `yt-dlp -U` on every editor boot — on the image's yt-dlp only; an override (`YTDLP_BIN` naming another) is left alone, with a warning. | docker/entrypoint.sh, common/bin/doctor.ts | +| `XDG_STATE_HOME` | `~/.local/state` | The state root: `archilyzer housekeeping` keeps its record of runs in `<it>/archilyzer/housekeeping.json`. | common/bin/housekeeping.ts | +| `ARCHILYZER_HOUSEKEEPING_RECORD` | `$XDG_STATE_HOME/archilyzer/housekeeping.json` | Where `archilyzer housekeeping` appends each run (what each part freed and kept, why a run was skipped, the home filesystem's free space before and after; the last 52 runs). | common/bin/housekeeping.ts | | `XDG_CONFIG_HOME` | `~/.config` | Where `wrangler login` keeps its config (`<it>/.wrangler/config/default.toml`); the doctor looks for it there, by path, never reading it. Also where a Linux Firefox may keep its profiles (`<it>/mozilla/firefox`), whose `compatibility.ini` gives the derived Firefox user agent. | common/bin/doctor.ts, common/lib/pagesDeploy.ts, common/lib/browserUserAgent-server.ts | | `APPDATA` | `~/AppData/Roaming` | Windows: where Firefox keeps its profiles (`<it>/Mozilla/Firefox`), whose `compatibility.ini` gives the derived Firefox user agent. Set by Windows itself. | common/lib/browserUserAgent-server.ts | | `YTDLP_SOURCE_DIR` | `/opt/yt-dlp-src` | Docker: where `/usr/local/bin/yt-dlp-from-source` finds the yt-dlp source tree it runs with the image's python. | docker/yt-dlp-from-source.sh | diff --git a/OPERATING.md b/OPERATING.md @@ -955,6 +955,44 @@ pnpm ops delete-iteration --json '{"id":"example-article","n":3}' history of `transcripts/`, a deployed site until it is rebuilt. Nothing outside the known roots is touched; a link is removed as a link. +## Free disk + +```sh +pnpm archilyzer housekeeping --dry-run # what would go, what stays and why; deletes and records nothing +pnpm archilyzer housekeeping # do it (skipped while a render or an e2e/heavy job runs) +pnpm archilyzer housekeeping --json --idle 7d --skip worktrees +pnpm archilyzer service status # the weekly timer: next and last run, the last run's result +# one part at a time, each a dry run unless --yes: +node umtool/bin/umtool.mjs prune --all --versions [--idle 3d] [--json] # superseded takes +node umtool/bin/umtool.mjs prune --all --idle-work 3d [--json] # takes' work files +pnpm wt prune --dry-run [--json] # worktrees that are done +``` + +- **Weekly, on its own.** `archilyzer service install` (host mode) installs `archilyzer-housekeeping.timer` + (`OnCalendar=weekly`, `Persistent=true`: a week missed while the machine was off runs at the next start), which + starts the oneshot `archilyzer-housekeeping.service`. `--no-housekeeping` leaves them out; `systemctl --user + start archilyzer-housekeeping.service` runs it now. +- **Never beside a render or an e2e/heavy job.** With render mode on, a job in the heavy slot or an e2e suite + holding its queue, a run is skipped (exit 75), not queued; the unit tries again hourly for a day, and the record + folds the skips into one entry. +- **Superseded takes** (whole takes, through `umtool takes delete`): per version line — the take id with its digits + folded (`draft-3` and `draft-4` are `draft-#`); a letter is never folded (`v6c` ≠ `v6d`, `release-6u` ≠ + `release-6`) — the newest built take stays, and so does any take picked, pinned, rendering, a build's or a + render's base, the project's manifest's, with operator notes on it, or refused by `takes delete` (a project + reached through a link). A project touched within `--idle` (default 3 days) is skipped whole. +- **Work files** (segments, chrome frames, crossfade batches, encode chunks, the rail's `prerail` base): every + project by its prune policy, and in a project idle that long the newest and picked takes' work too. Renders, + previews, take.json and the manifests are never touched; a pin in `takes/prune.json` and a running build keep + theirs. umtool's [report-video.md](umtool/docs/report-video.md), "A take's work files, and pruning them". +- **Worktrees**: merged into `main`, clean (no change, no untracked file), no process in them, idle; `git worktree + remove`, never `--force`, branches kept. Every other worktree's port block is recorded first, so no running suite + loses its ports. [WORKTREES.md](WORKTREES.md), "Removing the worktrees that are done". +- **The record**: `~/.local/state/archilyzer/housekeeping.json` (`$XDG_STATE_HOME`; `ARCHILYZER_HOUSEKEEPING_RECORD` + overrides) — each run, newest last, the last 52: what each part freed and kept (by reason), why a run was + skipped, the home filesystem's free space before and after. +- **Not done by it**: the clip-window cache (`evict-clips`: re-fetching is paced), a project's only preview, other + sessions' job directories, anything under `transcripts/`. + ## Publish ```sh diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -1148,7 +1148,7 @@ export const COMMANDS: Command[] = [ { path: ["service", "install"], usage: - "[--mode docker|host] [--apps <a,b>] [--sites <id>:<port>,…] [--overlays <name,…>|none] [--bind <host>] [--editor-port <n>] [--umtool-port <n>] [--editor-memory <N>G] [--umtool-memory <N>G] [--idle-boot] [--linger] [--no-start] [--force] [--dry-run] install the apps as systemd USER units and start them: docker mode (the default when `docker compose` answers) is ONE unit, archilyzer.service, running `docker compose up` in the foreground with a profile per --apps (editor, umtool, site, homepage, ollama; default editor) and the overlays given or found (anthropic when the key file exists, storage when docker-compose.storage.yml does); host mode is archilyzer-editor.service and archilyzer-umtool.service (node running `next start` from the app dir, -H --bind default 0.0.0.0, ports 3001/3050, MemoryHigh/Max sized from MemTotal) plus archilyzer-site-<id>.service per --sites (a built bundle on 127.0.0.1); each unit refuses to start while its build or image is missing. A unit already installed under the same name is ADOPTED when identical and shown as a diff and refused when not (--force replaces it; a running unit is not restarted); --no-start enables without starting; --linger runs loginctl enable-linger (start at boot with nobody logged in); --dry-run prints the units and commands and writes nothing. Linux and systemd only", + "[--mode docker|host] [--apps <a,b>] [--sites <id>:<port>,…] [--overlays <name,…>|none] [--bind <host>] [--editor-port <n>] [--umtool-port <n>] [--editor-memory <N>G] [--umtool-memory <N>G] [--idle-boot] [--no-housekeeping] [--linger] [--no-start] [--force] [--dry-run] install the apps as systemd USER units and start them: docker mode (the default when `docker compose` answers) is ONE unit, archilyzer.service, running `docker compose up` in the foreground with a profile per --apps (editor, umtool, site, homepage, ollama; default editor) and the overlays given or found (anthropic when the key file exists, storage when docker-compose.storage.yml does); host mode is archilyzer-editor.service and archilyzer-umtool.service (node running `next start` from the app dir, -H --bind default 0.0.0.0, ports 3001/3050, MemoryHigh/Max sized from MemTotal) plus archilyzer-site-<id>.service per --sites (a built bundle on 127.0.0.1) and archilyzer-housekeeping.timer, weekly and Persistent, starting the oneshot archilyzer-housekeeping.service (`archilyzer housekeeping --by timer`; a run the heavy slot turns away exits 75 and is retried hourly for a day; --no-housekeeping leaves the pair out); each unit refuses to start while its build or image is missing. A unit already installed under the same name is ADOPTED when identical and shown as a diff and refused when not (--force replaces it; a running unit is not restarted); --no-start enables without starting; --linger runs loginctl enable-linger (start at boot with nobody logged in); --dry-run prints the units and commands and writes nothing. Linux and systemd only", flags: { mode: "string", apps: "string", @@ -1160,6 +1160,7 @@ export const COMMANDS: Command[] = [ "editor-memory": "string", "umtool-memory": "string", "idle-boot": "boolean", + "no-housekeeping": "boolean", linger: "boolean", "no-start": "boolean", force: "boolean", @@ -1177,6 +1178,7 @@ export const COMMANDS: Command[] = [ editorMemory: str(flags["editor-memory"]), umtoolMemory: str(flags["umtool-memory"]), idleBoot: flags["idle-boot"] === true, + noHousekeeping: flags["no-housekeeping"] === true, linger: flags.linger === true, noStart: flags["no-start"] === true, force: flags.force === true, @@ -1186,7 +1188,7 @@ export const COMMANDS: Command[] = [ { path: ["service", "status"], usage: - "read-only: each installed archilyzer unit's state, enablement and pid; for an app its build id, its port and what / answers; the transcription lane's held state; in docker mode each container", + "read-only: each installed archilyzer unit's state, enablement and pid; for an app its build id, its port and what / answers; the transcription lane's held state; in docker mode each container; for archilyzer-housekeeping.timer its next and last trigger and the last recorded run", run: async () => (await import("./service")).main("status", {}), }, { @@ -1199,7 +1201,7 @@ export const COMMANDS: Command[] = [ { path: ["service", "restart"], usage: - "[--apps <a,b>] [--dry-run] restart the installed units (all, or the named apps: editor, umtool, site-<id>, docker) — the editor's running jobs are stopped by its shutdown reaper", + "[--apps <a,b>] [--dry-run] restart the installed units (all, or the named apps: editor, umtool, site-<id>, docker) — the editor's running jobs are stopped by its shutdown reaper; never the housekeeping pair (restarting its oneshot would run it)", flags: { apps: "string", "dry-run": "boolean" }, run: async ({ flags }) => (await import("./service")).main("restart", { apps: str(flags.apps), dryRun: flags["dry-run"] === true }), @@ -1228,6 +1230,21 @@ export const COMMANDS: Command[] = [ dryRun: flags["dry-run"] === true, }), }, + // Free disk, the weekly way (bin/housekeeping.ts; the timer: lib/service/units.ts). + { + path: ["housekeeping"], + usage: + "[--dry-run] [--json] [--idle 3d] [--skip takes,work,worktrees] [--by cli|timer] free disk over the apps' own commands: whole superseded takes (`umtool prune --all --versions`: per version line — the take id, digits folded, letters never — the newest built is kept, and any take picked, pinned, rendering, a base, noted on or refused by `umtool takes delete`), every project's takes' work files by its prune policy and an idle project's newest and picked takes' too (`--idle-work`), and merged, clean, idle worktrees nobody works in (`pnpm wt prune`: `git worktree remove`, branches kept); a project or worktree touched within --idle is left alone. SKIPPED, not queued, while render mode is on, a job runs in the heavy slot or an e2e suite holds its queue. Prints what each part freed and kept (by reason) and the home filesystem's free space before and after, and appends the run to $XDG_STATE_HOME/archilyzer/housekeeping.json (the last 52; ARCHILYZER_HOUSEKEEPING_RECORD overrides). --dry-run deletes nothing and records nothing. `archilyzer service install` runs it weekly (archilyzer-housekeeping.timer)", + flags: { "dry-run": "boolean", json: "boolean", idle: "string", skip: "string", by: "string" }, + run: async ({ flags }) => + (await import("./housekeeping")).main({ + dryRun: flags["dry-run"] === true, + json: flags.json === true, + idle: str(flags.idle), + skip: str(flags.skip), + by: str(flags.by), + }), + }, { path: ["doctor"], usage: diff --git a/common/bin/housekeeping.test.ts b/common/bin/housekeeping.test.ts @@ -0,0 +1,306 @@ +// `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, + SKIPPED_EXIT, + appendRecord, + housekeeping, + main, + readRecord, + recordFileFor, + runToFile, + slotBusy, + summarizePrune, + summarizeWorktrees, + type HousekeepingDeps, + type HousekeepingRun, + 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?: SlotState | null; 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(null), null); + assert.equal(slotBusy(IDLE_SLOT), null); + 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("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", "--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/); +}); + +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 }]); + 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", 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 }); + } +}); diff --git a/common/bin/housekeeping.ts b/common/bin/housekeeping.ts @@ -0,0 +1,443 @@ +// `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 <idle>` — whole superseded +// takes (umtool/lib/report/takeVersions.mjs); +// work `… --idle-work <idle>` 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; + 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 }[]; +}; + +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: () => SlotState | null; + // 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<HousekeepingDeps> { + const { REPO_ROOT } = await import("./_spawnBin"); + const { readHeavyQueue } = await import("../lib/heavyQueue.mjs"); + const { heavyLockFile } = 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 { + return readHeavyQueue({ heavyLock: heavyLockFile(process.env, { root: REPO_ROOT }) }) as SlotState; + } catch { + return null; + } + }, + 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 }); + } +} + +/** Why the slot says not now, or null. */ +export function slotBusy(s: SlotState | null): string | null { + if (!s) return null; + 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): string { + if (!/^\d+(\.\d+)?(d|h|m)?$/.test(v)) throw new Error(`--idle: "${v}" is not an age (3d, 12h, 90m)`); + return v; +} + +function parseSkip(v: string | undefined): Set<Part> { + const out = new Set<Part>(); + 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<string, number> = {}; + 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 }[]; +}; +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 }[]; + freedBytes?: number; +}; +type PruneJson = { versions?: { totals: Record<string, number>; 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<string, number>; // 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 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(`${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; + skipped: string | null; + free: { path: string; before: number | null; after: number | null }; + parts: Record<Part, PartSummary>; + 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<T>(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 skip = parseSkip(opts.skip); + const at = deps.now(); + const parts = { takes: blank(), work: blank(), worktrees: blank() } as Record<Part, PartSummary>; + 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); + if (!skip.has("work")) args.push("--idle-work", idle); + try { + const r = deps.run(node, args, deps.repoRoot); + const j = parseJson<PruneJson>(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<WorktreeJson>(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, + 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<Part, string> = { 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})`]; + 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<number> { + 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; + } +} diff --git a/common/bin/service.test.ts b/common/bin/service.test.ts @@ -75,9 +75,10 @@ test("host install writes both units, reloads, enables and starts them; a second assert.equal(await install({ mode: "host" }, r.deps), 0, r.errors.join("\n")); const planned = planUnits("host", {}, r.deps); for (const u of planned) assert.equal(fs.readFileSync(path.join(r.units, u.name), "utf8"), u.text); - assert.deepEqual(fs.readdirSync(r.units).sort(), ["archilyzer-editor.service", "archilyzer-umtool.service"]); + assert.deepEqual(fs.readdirSync(r.units).sort(), ["archilyzer-editor.service", "archilyzer-housekeeping.service", "archilyzer-housekeeping.timer", "archilyzer-umtool.service"]); assert.ok(r.log().includes("systemctl --user daemon-reload")); - assert.ok(r.log().includes("systemctl --user enable --now archilyzer-editor.service archilyzer-umtool.service")); + // The timer is enabled; its oneshot service has no [Install] and is started by it. + assert.ok(r.log().includes("systemctl --user enable --now archilyzer-editor.service archilyzer-umtool.service archilyzer-housekeeping.timer")); // umtool has no build in the rig: said before anything starts. assert.ok(r.lines.some((l) => l.includes("umtool has no build yet"))); assert.ok(r.lines.some((l) => l.includes("Linger is off for someone"))); @@ -116,7 +117,7 @@ test("--dry-run prints the units and the commands and writes nothing", async () assert.match(text, /archilyzer-site-demo-private\.service/); assert.match(text, /Environment=HOST=127\.0\.0\.1/); assert.match(text, /loginctl enable-linger someone/); - assert.match(text, /systemctl --user enable --now archilyzer-editor\.service archilyzer-umtool\.service archilyzer-site-demo-private\.service/); + assert.match(text, /systemctl --user enable --now archilyzer-editor\.service archilyzer-umtool\.service archilyzer-site-demo-private\.service archilyzer-housekeeping\.timer/); }); test("docker is the default mode when compose answers; one unit, and a missing image is named", async () => { @@ -173,12 +174,47 @@ test("restart, logs and uninstall act on the installed units", async () => { assert.equal(await restart({ apps: "editor" }, r.deps), 0); assert.ok(r.log().includes("systemctl --user restart archilyzer-editor.service")); assert.equal(await logs({ lines: "50" }, r.deps), 0); - assert.ok(r.log().some((l) => l.startsWith("journalctl --user -u archilyzer-editor.service -u archilyzer-umtool.service -n 50"))); + assert.ok(r.log().some((l) => l.startsWith("journalctl --user -u archilyzer-editor.service -u archilyzer-housekeeping.service -u archilyzer-housekeeping.timer -u archilyzer-umtool.service -n 50"))); assert.equal(await uninstall({ dryRun: true }, r.deps), 0); - assert.equal(fs.readdirSync(r.units).length, 2, "a dry run removes nothing"); + assert.equal(fs.readdirSync(r.units).length, 4, "a dry run removes nothing"); assert.equal(await uninstall({}, r.deps), 0); assert.equal(fs.readdirSync(r.units).length, 0); - assert.ok(r.log().includes("systemctl --user disable --now archilyzer-editor.service archilyzer-umtool.service")); + assert.ok(r.log().includes("systemctl --user disable --now archilyzer-editor.service archilyzer-housekeeping.timer archilyzer-umtool.service")); +}); + +test("the housekeeping pair: host mode only, the timer enabled and listed, never restarted, --no-housekeeping leaves it out", async () => { + const r = rig(); + const planned = planUnits("host", {}, r.deps); + const svc = planned.find((u) => u.name === "archilyzer-housekeeping.service"); + const timer = planned.find((u) => u.name === "archilyzer-housekeeping.timer"); + assert.ok(svc && timer); + assert.match(svc.text, /^ExecStart=\/usr\/bin\/node --import tsx bin\/archilyzer\.ts housekeeping --by timer$/m); + assert.match(svc.text, new RegExp(`^WorkingDirectory=${r.deps.repoRoot}/common$`, "m")); + assert.match(timer.text, /^OnCalendar=weekly$/m); + assert.match(timer.text, /^Persistent=true$/m); + assert.equal(planUnits("host", { noHousekeeping: true }, r.deps).some((u) => u.name.includes("housekeeping")), false); + const d = rig({ docker: true }); + assert.equal(planUnits("docker", {}, d.deps).some((u) => u.name.includes("housekeeping")), false); + + await install({ mode: "host", noStart: true }, r.deps); + fs.writeFileSync(path.join(r.root, "calls.log"), ""); + r.lines.length = 0; + assert.equal(await status({}, r.deps), 0); + const text = r.lines.join("\n"); + assert.match(text, /archilyzer-housekeeping\.timer: active, enabled/); + assert.match(text, /no run recorded yet \(.*\/home\/\.local\/state\/archilyzer\/housekeeping\.json\)/); + // A recorded run is shown. + const rec = path.join(r.root, "home", ".local", "state", "archilyzer", "housekeeping.json"); + fs.mkdirSync(path.dirname(rec), { recursive: true }); + fs.writeFileSync(rec, JSON.stringify({ format: "archilyzer-housekeeping", version: 1, runs: [{ at: "2026-11-09T05:12:00Z", skipped: null, freedBytes: 12.3e9, errors: [] }] })); + r.lines.length = 0; + await status({}, r.deps); + assert.match(r.lines.join("\n"), /last run 2026-11-09T05:12:00Z: freed about 12\.3 GB/); + + fs.writeFileSync(path.join(r.root, "calls.log"), ""); + assert.equal(await restart({}, r.deps), 0); + assert.ok(r.log().includes("systemctl --user restart archilyzer-editor.service archilyzer-umtool.service"), r.log().join("\n")); + assert.equal(await restart({ apps: "housekeeping" }, r.deps), 1, "restarting the oneshot would run it: refused"); }); test("the storage overlay mounts every location and every link no location covers, at the same path", () => { diff --git a/common/bin/service.ts b/common/bin/service.ts @@ -27,9 +27,13 @@ import { DOCKER_APPS, DOCKER_UNIT, HOST_APPS, + HOUSEKEEPING_SERVICE, + HOUSEKEEPING_TIMER, hostUnitName, renderDockerUnit, renderHostUnit, + renderHousekeepingService, + renderHousekeepingTimer, renderSiteUnit, siteUnitName, unitDiff, @@ -51,6 +55,8 @@ export type ServiceOptions = { editorMemory?: string; umtoolMemory?: string; idleBoot?: boolean; + // Host mode: leave out archilyzer-housekeeping.timer and its service. + noHousekeeping?: boolean; linger?: boolean; dryRun?: boolean; force?: boolean; @@ -144,9 +150,14 @@ function installedUnits(dir: string): string[] { } catch { return []; } - return names.filter((n) => n === DOCKER_UNIT || /^archilyzer-[a-z0-9-]+\.service$/.test(n)).sort(); + return names.filter((n) => n === DOCKER_UNIT || /^archilyzer-[a-z0-9-]+\.service$/.test(n) || n === HOUSEKEEPING_TIMER).sort(); } +/** The housekeeping pair: run by the timer, never restarted with the apps. */ +const isHousekeeping = (u: string) => u === HOUSEKEEPING_SERVICE || u === HOUSEKEEPING_TIMER; +/** What `systemctl enable` takes: every unit but the housekeeping service (it has no [Install]; the timer starts it). */ +const enableable = (units: string[]) => units.filter((u) => u !== HOUSEKEEPING_SERVICE); + function dockerAvailable(env: NodeJS.ProcessEnv): string | null { const docker = findOnPath("docker", env.PATH); if (!docker) return null; @@ -265,6 +276,12 @@ export function planUnits(mode: ServiceMode, opts: ServiceOptions, deps: Service }), }); } + if (!opts.noHousekeeping) { + planned.push( + { name: HOUSEKEEPING_SERVICE, text: renderHousekeepingService({ repoRoot: deps.repoRoot, home, nodeBin: deps.nodeBin }) }, + { name: HOUSEKEEPING_TIMER, text: renderHousekeepingTimer() }, + ); + } return planned; } @@ -314,7 +331,7 @@ export async function install(opts: ServiceOptions, deps: ServiceDeps): Promise< // What a start would refuse on, said now. for (const w of buildWarnings(mode, planned, opts, deps)) out.log(`note: ${w}`); - const names = planned.map((u) => u.name); + const names = enableable(planned.map((u) => u.name)); const cmds: string[][] = []; if (toWrite.length) cmds.push([systemctl, "--user", "daemon-reload"]); cmds.push([systemctl, "--user", "enable", ...(opts.noStart ? [] : ["--now"]), ...names]); @@ -401,8 +418,8 @@ function buildWarnings(mode: ServiceMode, planned: Planned[], opts: ServiceOptio // --- status -------------------------------------------------------------- -function show(systemctl: string, unit: string, env: NodeJS.ProcessEnv): Record<string, string> { - const r = run(systemctl, ["--user", "show", unit, "--property=LoadState,ActiveState,SubState,MainPID,UnitFileState,ActiveEnterTimestamp"], env); +function show(systemctl: string, unit: string, env: NodeJS.ProcessEnv, which = "LoadState,ActiveState,SubState,MainPID,UnitFileState,ActiveEnterTimestamp"): Record<string, string> { + const r = run(systemctl, ["--user", "show", unit, `--property=${which}`], env); const props: Record<string, string> = {}; for (const line of (r.stdout || "").split("\n")) { const i = line.indexOf("="); @@ -438,6 +455,17 @@ export async function status(opts: ServiceOptions, deps: ServiceDeps): Promise<n const systemctl = need("systemctl", env, "status asks systemd"); for (const unit of units) { const text = fs.readFileSync(path.join(dir, unit), "utf8"); + if (unit === HOUSEKEEPING_TIMER) { + const t = show(systemctl, unit, env, "ActiveState,UnitFileState,NextElapseUSecRealtime,LastTriggerUSec"); + out.log(`${unit}: ${t.ActiveState ?? "?"}, ${t.UnitFileState ?? "?"}${t.NextElapseUSecRealtime ? `, next ${t.NextElapseUSecRealtime}` : ""}${t.LastTriggerUSec ? `, last ${t.LastTriggerUSec}` : ""}`); + const { readRecord, recordFileFor } = await import("./housekeeping"); + const file = recordFileFor(env, env.HOME || os.homedir()); + const last = readRecord(file).at(-1); + if (!last) out.log(` no run recorded yet (${file})`); + else if (last.skipped) out.log(` last run ${last.at}: ${last.skipped}${last.skips ? ` (${last.skips} times since ${last.firstSkippedAt})` : ""}`); + else out.log(` last run ${last.at}: freed about ${(last.freedBytes / 1e9).toFixed(1)} GB${last.errors.length ? `, ${last.errors.length} error(s)` : ""} — ${file}`); + continue; + } const p = show(systemctl, unit, env); const state = `${p.ActiveState ?? "?"} (${p.SubState ?? "?"})`; const enabled = p.UnitFileState ?? "?"; @@ -505,6 +533,7 @@ function selectUnits(opts: ServiceOptions, deps: ServiceDeps): string[] { if (apps.length === 0) return units; const wanted = new Set(apps.flatMap((a) => [hostUnitName(a as HostApp), siteUnitName(a.replace(/^site-/, ""))])); if (apps.includes("docker")) wanted.add(DOCKER_UNIT); + if (apps.includes("housekeeping")) [HOUSEKEEPING_SERVICE, HOUSEKEEPING_TIMER].forEach((u) => wanted.add(u)); return units.filter((u) => wanted.has(u)); } @@ -528,7 +557,8 @@ export async function logs(opts: ServiceOptions, deps: ServiceDeps): Promise<num export async function restart(opts: ServiceOptions, deps: ServiceDeps): Promise<number> { refuseOffLinux(deps); - const units = selectUnits(opts, deps); + // Restarting the oneshot would RUN housekeeping; the timer has nothing to restart. + const units = selectUnits(opts, deps).filter((u) => !isHousekeeping(u)); if (units.length === 0) { deps.out.error("No archilyzer units installed (or none matches --apps)."); return 1; @@ -558,19 +588,20 @@ export async function uninstall(opts: ServiceOptions, deps: ServiceDeps): Promis deps.out.log(`Nothing to uninstall in ${dir}.`); return 0; } + const toDisable = enableable(units); const cmds = [ - ["systemctl", "--user", "disable", "--now", ...units], + ["systemctl", "--user", "disable", "--now", ...toDisable], ["systemctl", "--user", "daemon-reload"], ]; if (opts.dryRun) { deps.out.log("Would run:"); - deps.out.log(` ${cmds[0].join(" ")}`); + if (toDisable.length) deps.out.log(` ${cmds[0].join(" ")}`); for (const u of units) deps.out.log(` rm ${path.join(dir, u)}`); deps.out.log(` ${cmds[1].join(" ")}`); return 0; } const systemctl = need("systemctl", deps.env, "uninstall asks systemd"); - const stop = run(systemctl, cmds[0].slice(1), deps.env); + const stop = toDisable.length ? run(systemctl, cmds[0].slice(1), deps.env) : { status: 0, stderr: "" }; if (stop.status !== 0) { deps.out.error(`systemctl ${cmds[0].slice(1).join(" ")} failed: ${(stop.stderr || "").trim()}`); return 1; diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -110,6 +110,8 @@ const DECLARED: EnvVarDecl[] = [ { name: "ARCHILYZER_SOURCE_REPO", audience: "runtime", default: "this checkout's git common dir", readBy: "common/publish/source.ts, common/bin/doctor.ts, docker/entrypoint.sh", doc: "The git DIR `archilyzer source publish` mirrors `main` from, when the checkout has none: in Docker, `/data/source.git`, the host's git common dir mounted read-only by docker-compose.source.yml. A value that names nothing refuses the publish." }, { name: "YTDLP_SOURCE_HOST_DIR", audience: "runtime", default: "— (required by the overlay)", readBy: "docker-compose.ytdlp.yml", doc: "Docker: the HOST path of a yt-dlp source checkout (the directory holding `yt_dlp/`), mounted read-only at `/opt/yt-dlp-src` by docker-compose.ytdlp.yml. See [RUNNING_IN_DOCKER.md](RUNNING_IN_DOCKER.md), \"Substituting yt-dlp\"." }, { name: "YTDLP_AUTO_UPDATE", audience: "runtime", default: "off", readBy: "docker/entrypoint.sh, common/bin/doctor.ts", doc: "Docker: `1` runs `yt-dlp -U` on every editor boot — on the image's yt-dlp only; an override (`YTDLP_BIN` naming another) is left alone, with a warning." }, + { name: "XDG_STATE_HOME", audience: "runtime", default: "`~/.local/state`", readBy: "common/bin/housekeeping.ts", doc: "The state root: `archilyzer housekeeping` keeps its record of runs in `<it>/archilyzer/housekeeping.json`." }, + { name: "ARCHILYZER_HOUSEKEEPING_RECORD", audience: "runtime", default: "`$XDG_STATE_HOME/archilyzer/housekeeping.json`", readBy: "common/bin/housekeeping.ts", doc: "Where `archilyzer housekeeping` appends each run (what each part freed and kept, why a run was skipped, the home filesystem's free space before and after; the last 52 runs)." }, { name: "XDG_CONFIG_HOME", audience: "runtime", default: "`~/.config`", readBy: "common/bin/doctor.ts, common/lib/pagesDeploy.ts, common/lib/browserUserAgent-server.ts", doc: "Where `wrangler login` keeps its config (`<it>/.wrangler/config/default.toml`); the doctor looks for it there, by path, never reading it. Also where a Linux Firefox may keep its profiles (`<it>/mozilla/firefox`), whose `compatibility.ini` gives the derived Firefox user agent." }, { name: "APPDATA", audience: "runtime", default: "`~/AppData/Roaming`", readBy: "common/lib/browserUserAgent-server.ts", doc: "Windows: where Firefox keeps its profiles (`<it>/Mozilla/Firefox`), whose `compatibility.ini` gives the derived Firefox user agent. Set by Windows itself." }, { name: "YTDLP_SOURCE_DIR", audience: "runtime", default: "`/opt/yt-dlp-src`", readBy: "docker/yt-dlp-from-source.sh", doc: "Docker: where `/usr/local/bin/yt-dlp-from-source` finds the yt-dlp source tree it runs with the image's python." }, diff --git a/common/lib/service/units.test.ts b/common/lib/service/units.test.ts @@ -12,6 +12,8 @@ import { hostUnitPath, renderDockerUnit, renderHostUnit, + renderHousekeepingService, + renderHousekeepingTimer, renderSiteUnit, unitDiff, } from "./units"; @@ -162,3 +164,47 @@ test("unitDiff marks the installed side - and the rendered side +", () => { assert.equal(unitDiff("a\nb\n", "a\nb\n"), ""); assert.equal(unitDiff("a\nb\nc", "a\nB\nc"), " a\n- b\n+ B\n c"); }); + +test("the housekeeping service and its weekly timer render exactly", () => { + assert.equal( + renderHousekeepingService({ repoRoot: "/home/user/archilyzer", home: "/home/user", nodeBin: "/usr/bin/node" }), + `[Unit] +Description=Archilyzer housekeeping (superseded takes, idle work files, merged worktrees) +Documentation=file:///home/user/archilyzer/OPERATING.md +# Started by archilyzer-housekeeping.timer; \`systemctl --user start archilyzer-housekeeping.service\` runs it now. +# A run the heavy slot turns away (a render, an e2e suite) exits 75 and is tried again in an hour, for a day. +StartLimitIntervalSec=1d +StartLimitBurst=24 + +[Service] +Type=oneshot +WorkingDirectory=/home/user/archilyzer/common +Environment=PATH=/home/user/.local/bin:/home/user/.local/share/pnpm:/usr/local/bin:/usr/bin:/bin +# tsx from common's own node_modules, as \`pnpm archilyzer\` runs it. +ExecStart=/usr/bin/node --import tsx bin/archilyzer.ts housekeeping --by timer +RestartForceExitStatus=75 +RestartSec=1h +SuccessExitStatus=75 +# Deleting is light: never in the way of what the machine is doing. +Nice=10 +IOSchedulingClass=idle +MemoryMax=2G +TimeoutStartSec=2h +`, + ); + assert.equal( + renderHousekeepingTimer(), + `[Unit] +Description=Archilyzer housekeeping, weekly + +[Timer] +OnCalendar=weekly +Persistent=true +RandomizedDelaySec=30m +Unit=archilyzer-housekeeping.service + +[Install] +WantedBy=timers.target +`, + ); +}); diff --git a/common/lib/service/units.ts b/common/lib/service/units.ts @@ -24,6 +24,15 @@ // // The host units are the shape the operator's own units took (2026-10-16), so // installing over them is an adopt: identical text, nothing to write. +// +// Host mode also installs HOUSEKEEPING (2026-11-06): archilyzer-housekeeping. +// timer, weekly and Persistent (a week missed while the machine was off runs at +// the next boot), starting the oneshot archilyzer-housekeeping.service, which +// runs `archilyzer housekeeping --by timer` (bin/housekeeping.ts). A run the +// heavy slot turns away (a render, an e2e suite) exits 75 and is tried again an +// hour later, up to a day. Only the timer is enabled; the service has no +// [Install]. Not in docker mode: there the projects live in a volume the host's +// node does not see. export type HostApp = "editor" | "umtool"; export const HOST_APPS: readonly HostApp[] = ["editor", "umtool"]; @@ -243,6 +252,64 @@ export function renderDockerUnit(ctx: DockerUnitContext): string { ].join("\n"); } +export const HOUSEKEEPING_SERVICE = "archilyzer-housekeeping.service"; +export const HOUSEKEEPING_TIMER = "archilyzer-housekeeping.timer"; +/** What a run the heavy slot turned away exits with (EX_TEMPFAIL): the unit tries again. */ +export const HOUSEKEEPING_RETRY_EXIT = 75; + +export type HousekeepingUnitContext = { + repoRoot: string; + home: string; + nodeBin: string; +}; + +/** archilyzer-housekeeping.service: one run of `archilyzer housekeeping`, started by the timer. */ +export function renderHousekeepingService(ctx: HousekeepingUnitContext): string { + return [ + "[Unit]", + "Description=Archilyzer housekeeping (superseded takes, idle work files, merged worktrees)", + `Documentation=file://${SPEC(ctx.repoRoot)}/OPERATING.md`, + "# Started by archilyzer-housekeeping.timer; `systemctl --user start archilyzer-housekeeping.service` runs it now.", + "# A run the heavy slot turns away (a render, an e2e suite) exits 75 and is tried again in an hour, for a day.", + "StartLimitIntervalSec=1d", + "StartLimitBurst=24", + "", + "[Service]", + "Type=oneshot", + `WorkingDirectory=${SPEC(ctx.repoRoot)}/common`, + `Environment=PATH=${hostUnitPath(ctx.home, ctx.nodeBin)}`, + "# tsx from common's own node_modules, as `pnpm archilyzer` runs it.", + `ExecStart=${ESC(ctx.nodeBin)} --import tsx bin/archilyzer.ts housekeeping --by timer`, + `RestartForceExitStatus=${HOUSEKEEPING_RETRY_EXIT}`, + "RestartSec=1h", + `SuccessExitStatus=${HOUSEKEEPING_RETRY_EXIT}`, + "# Deleting is light: never in the way of what the machine is doing.", + "Nice=10", + "IOSchedulingClass=idle", + "MemoryMax=2G", + "TimeoutStartSec=2h", + "", + ].join("\n"); +} + +/** archilyzer-housekeeping.timer: weekly; a week missed while the machine was off runs at the next start. */ +export function renderHousekeepingTimer(): string { + return [ + "[Unit]", + "Description=Archilyzer housekeeping, weekly", + "", + "[Timer]", + "OnCalendar=weekly", + "Persistent=true", + "RandomizedDelaySec=30m", + `Unit=${HOUSEKEEPING_SERVICE}`, + "", + "[Install]", + "WantedBy=timers.target", + "", + ].join("\n"); +} + /** * A line diff of two unit texts, `-` for the installed one and `+` for the * rendered one, with unchanged lines as context (` `). Units are a few dozen diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **Free disk, weekly, with one command: `archilyzer housekeeping`.** On 6 Nov /home was at 37 GB free, and a session freed 83 GB by hand. The operator: "We should build a regularly run command for this after we're done." It runs three passes of the apps' own commands. **Superseded takes:** `umtool prune --versions` deletes whole takes through `umtool takes delete`. Per version line it keeps the newest built take; the line is the take id with its digits folded (`draft-3` and `draft-4`), and a letter is never folded (`v6c` is not `v6d`, `release-6u` is not `release-6`). It also keeps any take picked, pinned, rendering, a build's base, the manifest's, with operator notes on it, or refused by `takes delete`. **Work files:** every project's takes' work files by its prune policy; in a project idle 3 days, the newest and picked takes' work goes too (`--idle-work`). **Worktrees:** `pnpm wt prune` removes merged, clean, idle worktrees with no process in them, keeping their branches. A project or worktree touched in the last 3 days is left alone, and a run is skipped while a render, an e2e suite or a heavy job runs. Each run is recorded in `~/.local/state/archilyzer/housekeeping.json`. **Worktree ports no longer move:** a worktree's port block is recorded when it is added, so removing another worktree cannot shift a running suite's ports. **Upgrading:** `archilyzer service install` (host mode) now also installs `archilyzer-housekeeping.timer`, weekly; `--dry-run` shows it first, and `--no-housekeeping` leaves it out. OPERATING.md, "Free disk". - **Sync new and Resume backfill are separate actions for an X or Bluesky channel.** A fetch meant to get new posts could walk old history instead. If an account's full-history walk had stopped part-way, the next plain fetch, from Sync or the schedule too, resumed that walk and skipped the newest posts. On 6 Nov one such fetch read 100 posts the archive already held, stopped as "caught up" with 0 new, and missed 85 newer posts. It then cleared the walk's saved place, so the place was lost as well. The operator: "We should have distinct 'sync new' and 'resume backfill' actions, they are different actions for different purposes". **Sync new** (the channel page's first button; a plain `fetch-posts`, Sync and the scheduler) now always reads from the newest post down to the newest one archived, and never moves or clears the backfill's place. A sync that stops part-way keeps its own place and finishes on the next sync. **Resume backfill** (the button, shown only when a full-history walk is unfinished; `pnpm ops resume-backfill`, or `fetch-posts "backfill": true`; `--backfill` on `archilyzer posts fetch`; `backfill` on the MCP enqueue tool) continues that walk and does nothing else. When one is unfinished, the channel page says so: "backfill unfinished — N archived; Resume backfill continues it". The job log's first line names the mode. Resume backfill is refused when no walk is unfinished, and on a forum thread, which already reads its newest pages before its history. An X search channel has one walk and refuses it too. Re-fetch full history and Fetch older posts are unchanged. **Upgrading:** a `posts-state.json` from before this keeps one `cursor`. It is read as the unfinished backfill's place, so nothing is lost, and the next fetch rewrites it. Needs a restart of the editor. - **Archived posts can be packaged as timestamped evidence.** The operator wanted public evidence that Mr. Obvious's X posts existed, and Save Page Now refuses x.com as a site (HTTP 523); he chose "the timestamped evidence package". `archilyzer evidence pack <channel>[,<channel>…] [--handle <h>] [--since/--until YYYY-MM-DD] [--out <dir>] [--no-media] [--no-stamp] [--dry-run] [--json]` writes, read only over the corpus, a self-contained folder (default `~/reports/evidence/<handle>-<date>/`): `posts.jsonl` (one record a post, deduped across the channels, every archived field kept under `raw`, the capture record and availability check, and the archived record of a post it answers or quotes as `context`), `posts.csv`, the post media copied byte for byte from `posts-media/` (each hash checked against its `capture.json`), `pack.json`, a README saying how to verify, `SHA256SUMS` over every file, and an OpenTimestamps proof of it (`SHA256SUMS.ots`, the official `ots` client, one request to each calendar). `evidence upgrade <dir>` fetches the Bitcoin attestation a few hours later, `evidence verify <dir>` checks every file and the stamp, `evidence stamp <dir>` stamps an unstamped one. Refused inside the corpus or a channel's media, over a non-empty dir, and for a channel whose text is unreadable. OPERATING.md, "Package posts as timestamped evidence". - **Save Page Now works without archive.org keys, and a whole list of pages can be archived politely, with an evidence file.** The operator wanted every Mr. Obvious post on a public archive ("I'm just trying to make sure evidence of the pages exist"), and Save Page Now refused without S3 keys. With no keys configured it now asks archive.org's public endpoint anonymously (`"mode": "anonymous"` in the log and result; with keys, SPN2 as before, `"mode": "keys"`), and the channel page's Save Page Now panel says which. Every save in the editor takes turns through one pacer: one at a time, at least 60 s apart anonymous (10 s with keys), and a 429/503 or archive.org's "slow down" rests it (Retry-After, else 2 min doubling to 1 h). `pnpm ops save-page-now-batch --json '{"file":"/abs/urls.json"}'` runs ONE resumable job over a list: each URL looked up first (the Wayback CDX and archive.today's timemap, paced) and skipped when a copy shows it, else saved; at most 150 saves a day without keys (archive.org allows 200); progress and an ETA on /jobs; cancel, a restart or `{"batch": "<id>"}` continue from the first pending URL. Its evidence JSON + CSV (default `<transcripts>/.spn-batches/<batch>.evidence.*`, or `evidence`) names, per URL, the status, the Wayback and archive.today copy URLs, the capture time and the HTTP status the archive recorded. archive.today and Ghostarchive are looked up only, never asked to save (their forms put a CAPTCHA in front). Save Page Now refuses x.com as a site today (HTTP 523, "limitations when it comes to archiving this site"): a batch asks such a site once, then only looks its other URLs up and records them as not asked. OPERATING.md, "Archive a list of pages politely (evidence)". diff --git a/scripts/worktree.mjs b/scripts/worktree.mjs @@ -536,13 +536,13 @@ export function planWorktreePrune({ cwd = process.cwd(), base = "main", idleMs = const kept = []; list.forEach((t, i) => { const row = { path: t.path, branch: t.branch, offset: t.offset }; - const keep = (why) => kept.push({ ...row, why }); - if (i === 0) return keep("the main worktree"); - if (t.prunable) return keep("its directory is gone: `git worktree prune` clears the entry (not done here)"); - if (t.locked) return keep("locked (git worktree lock)"); - if (!t.branch || t.branch === "(detached)") return keep("detached HEAD: no branch to judge"); - if (t.branch === base) return keep(`it is ${base}`); - if (!gitOk(["merge-base", "--is-ancestor", `refs/heads/${t.branch}`, `refs/heads/${base}`], { cwd })) return keep(`${t.branch} is not merged into ${base}`); + const keep = (code, why) => kept.push({ ...row, code, why }); + if (i === 0) return keep("main", "the main worktree"); + if (t.prunable) return keep("missing", "its directory is gone: `git worktree prune` clears the entry (not done here)"); + if (t.locked) return keep("locked", "locked (git worktree lock)"); + if (!t.branch || t.branch === "(detached)") return keep("detached", "detached HEAD: no branch to judge"); + if (t.branch === base) return keep("base", `it is ${base}`); + if (!gitOk(["merge-base", "--is-ancestor", `refs/heads/${t.branch}`, `refs/heads/${base}`], { cwd })) return keep("unmerged", `${t.branch} is not merged into ${base}`); // Read before `git status`, which may refresh the index (and its mtime). const touched = touchedMs(t.path); let status; @@ -550,18 +550,18 @@ export function planWorktreePrune({ cwd = process.cwd(), base = "main", idleMs = // --no-optional-locks: a dry run writes nothing, not even a refreshed index. status = git(["--no-optional-locks", "status", "--porcelain=v1", "--untracked-files=normal"], { cwd: t.path }); } catch (e) { - return keep(`git status failed: ${String(e?.message ?? e).split("\n")[0]}`); + return keep("status-failed", `git status failed: ${String(e?.message ?? e).split("\n")[0]}`); } if (status) { const n = status.split("\n").length; - return keep(`not clean: ${n} changed or untracked path${n === 1 ? "" : "s"} (${status.split("\n")[0].trim()}${n > 1 ? ", …" : ""})`); + return keep("dirty", `not clean: ${n} changed or untracked path${n === 1 ? "" : "s"} (${status.split("\n")[0].trim()}${n > 1 ? ", …" : ""})`); } const real = realpath(t.path); const inIt = procs.filter((p) => p.cwd === real || p.cwd.startsWith(real + path.sep) || p.cwd === t.path || p.cwd.startsWith(t.path + path.sep)); - if (inIt.length) return keep(`a process works in it (pid ${inIt.slice(0, 5).map((p) => p.pid).join(", ")}${inIt.length > 5 ? ", …" : ""})`); + if (inIt.length) return keep("process", `a process works in it (pid ${inIt.slice(0, 5).map((p) => p.pid).join(", ")}${inIt.length > 5 ? ", …" : ""})`); if (touched && now - touched < idleMs) { const h = (now - touched) / 3600000; - return keep(`touched ${h < 48 ? `${Math.round(h)} h` : `${(h / 24).toFixed(1)} d`} ago (idle needs ${(idleMs / 86400000).toFixed(1)} d): a branch just made from ${base} is merged too`); + return keep("active", `touched ${h < 48 ? `${Math.round(h)} h` : `${(h / 24).toFixed(1)} d`} ago (idle needs ${(idleMs / 86400000).toFixed(1)} d): a branch just made from ${base} is merged too`); } remove.push({ ...row, index: i }); }); @@ -574,7 +574,7 @@ export function planWorktreePrune({ cwd = process.cwd(), base = "main", idleMs = const go = []; for (const r of remove) { const { index, ...row } = r; - if (index < last) kept.push({ ...row, why: `removing it would move ${list[last].branch ?? list[last].path}'s ports: that checkout's scripts/worktree.mjs predates recorded port blocks (merge main into it, or wait until it is gone)` }); + if (index < last) kept.push({ ...row, code: "old-checkout", why: `removing it would move ${list[last].branch ?? list[last].path}'s ports: that checkout's scripts/worktree.mjs predates recorded port blocks (merge main into it, or wait until it is gone)` }); else go.push({ ...row, bytes: measure ? freeableBytes(row.path) : null }); } return { base, idleMs, remove: go, kept, bytes: go.reduce((s, r) => s + (r.bytes ?? 0), 0) };