// The systemd units `archilyzer service` installs (release 32): pure text, // rendered from a context the command gathers, so the rendered unit for both // modes is unit-tested byte for byte. Nothing here touches the disk or runs a // process — bin/service.ts does that. // // Two modes, one command: // // docker ONE user unit, archilyzer.service, running `docker compose … up` // in the foreground (its logs in the journal) and `down` on stop. // Compose's own `restart: unless-stopped` already brings containers // back when the Docker daemon starts; the unit adds start/stop/status // and logs through systemctl and journalctl, and a start that refuses // with a sentence when an image was never built. // host one user unit per app — archilyzer-editor.service, // archilyzer-umtool.service, archilyzer-site-.service for a // private site's static server — running node directly (pnpm // swallows SIGTERM, and the editor's shutdown reaper needs it), with // a start that refuses when the app was never built. // // User units, not system ones, in both modes: the apps run as the person who // owns the checkout and the corpus, nothing needs root to install, and // `loginctl enable-linger` (`--linger`) is what starts them at boot with // nobody logged in. // // 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"]; // docker mode's apps: compose profiles, plus the editor (always on — it has no // profile). export type DockerApp = "editor" | "umtool" | "site" | "homepage" | "ollama"; export const DOCKER_APPS: readonly DockerApp[] = ["editor", "umtool", "site", "homepage", "ollama"]; export const DOCKER_UNIT = "archilyzer.service"; export function hostUnitName(app: HostApp): string { return `archilyzer-${app}.service`; } export function siteUnitName(siteId: string): string { return `archilyzer-site-${siteId}.service`; } // A memory limit in whole GiB, as systemd spells it. export type MemoryLimit = { high: number; max: number }; const GIB = 1024 * 1024 * 1024; /** * Default memory limits from the machine's MemTotal: the editor's ceiling is * half the RAM, umtool's three eighths, each rounded UP to a whole GiB, and the * soft limit (MemoryHigh, where the kernel starts reclaiming) one GiB under it. * A 16 GB machine (MemTotal ~15.5 GiB) gets 7G/8G and 5G/6G — what the * operator's units carry. Never under 2G/3G (editor) or 1G/2G (umtool): below * that a transcription or a render cannot run at all. */ export function defaultMemory(app: HostApp, memTotalBytes: number): MemoryLimit { const total = memTotalBytes / GIB; const share = app === "editor" ? 0.5 : 0.375; const floor = app === "editor" ? 3 : 2; const max = Math.max(floor, Math.ceil(total * share)); return { high: max - 1, max }; } /** The PATH a host unit runs with: ~/.local/bin first (yt-dlp, gallery-dl, * parakeet-cli and git-filter-repo live there on a host install), pnpm's * global bin, the system's — and node's own directory first of all when it is * not one of those (a version manager's node). */ export function hostUnitPath(home: string, nodeBin: string): string { const dirs = [`${home}/.local/bin`, `${home}/.local/share/pnpm`, "/usr/local/bin", "/usr/bin", "/bin"]; const nodeDir = nodeBin.includes("/") ? nodeBin.slice(0, nodeBin.lastIndexOf("/")) || "/" : ""; if (nodeDir && !dirs.includes(nodeDir)) dirs.unshift(nodeDir); return dirs.join(":"); } export type HostUnitContext = { repoRoot: string; // the checkout, absolute home: string; nodeBin: string; // absolute bind: string; // next start -H port: number; memory: MemoryLimit; idleBoot?: boolean; // editor only: ARCHILYZER_IDLE_BOOT=1 }; // systemd expands `%` specifiers in every path it reads and `$` variables in // Exec lines; a path carrying either is spelled `%%` / `$$` so it arrives as // written. const SPEC = (s: string) => s.replace(/%/g, "%%"); const ESC = (s: string) => SPEC(s).replace(/\$/g, "$$$$"); /** archilyzer-editor.service / archilyzer-umtool.service. */ export function renderHostUnit(app: HostApp, ctx: HostUnitContext): string { const dir = `${ctx.repoRoot}/${app}`; const unit = `archilyzer-${app}`; const editor = app === "editor"; const env = ["NODE_ENV=production", "NEXT_TELEMETRY_DISABLED=1"]; if (editor) env.push("UV_THREADPOOL_SIZE=16"); if (editor && ctx.idleBoot) env.push("ARCHILYZER_IDLE_BOOT=1"); const lines = [ "[Unit]", `Description=Archilyzer ${app} (:${ctx.port})`, `Documentation=file://${SPEC(ctx.repoRoot)}/RUNNING_IN_DOCKER.md`, editor ? "After=network-online.target" : "After=network-online.target archilyzer-editor.service", "Wants=network-online.target", ...(editor ? ["# A crash-loop stops after 5 tries in 5 minutes instead of spinning."] : []), "StartLimitIntervalSec=300", "StartLimitBurst=5", "", "[Service]", "Type=simple", `WorkingDirectory=${SPEC(dir)}`, editor ? "# Next reads editor/.env itself (WORKER_TOKEN and the rest)." : "# Next reads umtool/.env.local itself.", `Environment=${env.join(" ")}`, ...(editor ? ["# yt-dlp, gallery-dl, parakeet-cli and git-filter-repo live in ~/.local/bin."] : []), `Environment=PATH=${hostUnitPath(ctx.home, ctx.nodeBin)}`, `ExecStartPre=/bin/sh -c 'test -s .next/BUILD_ID || { echo "${unit}: no build in ${ESC(dir)}/.next - build it first (pnpm --filter ${app} exec next build)" >&2; exit 1; }'`, ...(editor ? ["# node directly, not pnpm: pnpm swallows SIGTERM."] : []), `ExecStart=${ESC(ctx.nodeBin)} node_modules/next/dist/bin/next start -H ${ctx.bind} -p ${ctx.port}`, "Restart=on-failure", "RestartSec=5", ...(editor ? [ "# SIGTERM to the editor first; its shutdown reaper stops the jobs it started (downloads,", "# transcriptions) before the rest of the unit is killed.", ] : []), "KillMode=mixed", `TimeoutStopSec=${editor ? 90 : 60}`, ...(editor ? [ "# The editor's jobs (parakeet ~3.4 GB, yt-dlp, ffmpeg) run in this unit and count here:", "# a runaway is killed inside the unit, not by a global OOM that takes the session bus.", ] : ["# Renders started from umtool (ffmpeg, the chrome frames) run in this unit."]), `MemoryHigh=${ctx.memory.high}G`, `MemoryMax=${ctx.memory.max}G`, "", "[Install]", "WantedBy=default.target", "", ]; return lines.join("\n"); } export type SiteUnitContext = { repoRoot: string; home: string; nodeBin: string; siteId: string; bundleDir: string; // //out, absolute port: number; }; /** * archilyzer-site-.service: a built site's bundle served on this machine * only (HOST=127.0.0.1) by export/scripts/serve-out.mjs — how a private site * (`audience: "private"`, never deployed) is read. Rebuilds land in place, so * a new build needs no restart. */ export function renderSiteUnit(ctx: SiteUnitContext): string { const unit = `archilyzer-site-${ctx.siteId}`; return [ "[Unit]", `Description=Archilyzer site ${ctx.siteId} (127.0.0.1:${ctx.port})`, `Documentation=file://${SPEC(ctx.repoRoot)}/PUBLISH.md`, "After=network-online.target", "StartLimitIntervalSec=300", "StartLimitBurst=5", "", "[Service]", "Type=simple", `WorkingDirectory=${SPEC(ctx.repoRoot)}/export`, "# This machine only: a private site is never served beyond it.", "Environment=HOST=127.0.0.1", `Environment=PATH=${hostUnitPath(ctx.home, ctx.nodeBin)}`, `ExecStartPre=/bin/sh -c 'test -d ${ESC(ctx.bundleDir)} || { echo "${unit}: no bundle at ${ESC(ctx.bundleDir)} - build it first (pnpm archilyzer publish build ${ctx.siteId})" >&2; exit 1; }'`, `ExecStart=${ESC(ctx.nodeBin)} scripts/serve-out.mjs ${ESC(ctx.bundleDir)} ${ctx.port}`, "Restart=on-failure", "RestartSec=5", "TimeoutStopSec=10", "MemoryMax=1G", "", "[Install]", "WantedBy=default.target", "", ].join("\n"); } export type DockerUnitContext = { repoRoot: string; home: string; dockerBin: string; // absolute apps: readonly DockerApp[]; // Compose files after docker-compose.yml, relative to repoRoot // (docker-compose.vulkan.yml, docker-compose.anthropic.yml, …). overlays: readonly string[]; }; /** The compose arguments every docker-mode command shares: the files, then the profiles. */ export function composeArgs(ctx: Pick): string[] { const files = ["docker-compose.yml", ...ctx.overlays].flatMap((f) => ["-f", f]); const profiles = ctx.apps.filter((a) => a !== "editor").flatMap((a) => ["--profile", a]); return ["compose", ...files, ...profiles]; } /** archilyzer.service: the compose stack in the foreground. */ export function renderDockerUnit(ctx: DockerUnitContext): string { const compose = [ESC(ctx.dockerBin), ...composeArgs(ctx)].join(" "); const apps = ["editor", ...ctx.apps.filter((a) => a !== "editor")].join(", "); return [ "[Unit]", `Description=Archilyzer in Docker (${apps})`, `Documentation=file://${SPEC(ctx.repoRoot)}/RUNNING_IN_DOCKER.md`, "After=network-online.target", "Wants=network-online.target", "StartLimitIntervalSec=300", "StartLimitBurst=5", "", "[Service]", "Type=simple", `WorkingDirectory=${SPEC(ctx.repoRoot)}`, `Environment=PATH=/usr/local/bin:/usr/bin:/bin:${ctx.home}/.local/bin`, "# A user unit cannot order itself after the system's docker.service: wait for", "# the daemon to answer (two minutes), then refuse with a sentence.", `ExecStartPre=/bin/sh -c 'i=0; until ${ESC(ctx.dockerBin)} info >/dev/null 2>&1; do i=$$((i+1)); [ $$i -ge 60 ] && { echo "archilyzer: the Docker daemon is not answering - is it running? (systemctl status docker)" >&2; exit 1; }; sleep 2; done'`, "# Never a build at start: an image that was never built is refused, not built", "# behind your back (a build is many GB and many minutes).", `ExecStartPre=/bin/sh -c 'for i in $$(${compose} config --images | grep "^archilyzer:"); do ${ESC(ctx.dockerBin)} image inspect "$$i" >/dev/null 2>&1 || { echo "archilyzer: image $$i is not built - build it first (${compose} build)" >&2; exit 1; }; done'`, "# In the foreground, so every container's log is in the journal", "# (archilyzer service logs). restart: unless-stopped still restarts a", "# container that dies; this unit restarts compose itself.", `ExecStart=${compose} up --no-build`, `ExecStop=${compose} down`, "Restart=on-failure", "RestartSec=10", "# The editor's stop_grace_period is 30 s; down waits for it.", "TimeoutStopSec=120", "", "[Install]", "WantedBy=default.target", "", ].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 * lines, so a plain LCS is plenty. Empty when they are equal. */ export function unitDiff(installed: string, rendered: string): string { if (installed === rendered) return ""; const a = installed.split("\n"); const b = rendered.split("\n"); const n = a.length; const m = b.length; const lcs: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0)); for (let i = n - 1; i >= 0; i--) { for (let j = m - 1; j >= 0; j--) { lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]); } } const out: string[] = []; let i = 0; let j = 0; while (i < n || j < m) { if (i < n && j < m && a[i] === b[j]) { out.push(` ${a[i]}`); i++; j++; } else if (i < n && (j === m || lcs[i + 1][j] >= lcs[i][j + 1])) { out.push(`- ${a[i]}`); i++; } else { out.push(`+ ${b[j]}`); j++; } } return out.join("\n"); }