// `archilyzer service` against a fake systemctl / loginctl / docker on PATH and // a temp XDG_CONFIG_HOME — nothing here reaches the machine's own systemd. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test bin/service.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { install, logs, planUnits, restart, status, storageMounts, renderStorageOverlay, uninstall, type ServiceDeps } from "./service"; const FAKE = `#!/bin/sh echo "$(basename "$0") $*" >> "$FAKE_LOG" case "$(basename "$0") $1 $2" in "systemctl --user show") printf 'LoadState=loaded\\nActiveState=active\\nSubState=running\\nMainPID=4242\\nUnitFileState=enabled\\nActiveEnterTimestamp=Fri 2026-10-16 12:00:00 UTC\\n' ;; "systemctl --user is-active") exit 3 ;; "loginctl show-user"*) echo "Linger=no" ;; "docker compose version") echo "Docker Compose version v2" ;; "journalctl --user"*) echo "a journal line" ;; esac case "$*" in *"config --images"*) echo "archilyzer:local"; echo "caddy:2.11-alpine" ;; "image inspect"*) exit 1 ;; esac exit 0 `; type Rig = { deps: ServiceDeps; root: string; units: string; log: () => string[]; lines: string[]; errors: string[] }; function rig(opts: { docker?: boolean; platform?: NodeJS.Platform } = {}): Rig { const root = fs.mkdtempSync(path.join(os.tmpdir(), "service-test-")); const bin = path.join(root, "bin"); fs.mkdirSync(bin); const tools = ["systemctl", "loginctl", "journalctl", ...(opts.docker ? ["docker"] : [])]; for (const t of tools) fs.writeFileSync(path.join(bin, t), FAKE, { mode: 0o755 }); const repo = path.join(root, "repo"); for (const app of ["editor", "umtool"]) fs.mkdirSync(path.join(repo, app, ".next"), { recursive: true }); fs.writeFileSync(path.join(repo, "editor", ".next", "BUILD_ID"), "build-editor-1"); fs.writeFileSync(path.join(repo, "docker-compose.yml"), "services: {}\n"); // A PATH of the fakes and the one real tool they use — never the machine's // own systemctl or docker. const sys = path.join(root, "sys"); fs.mkdirSync(sys); fs.symlinkSync(fs.existsSync("/usr/bin/basename") ? "/usr/bin/basename" : "/bin/basename", path.join(sys, "basename")); const logFile = path.join(root, "calls.log"); const lines: string[] = []; const errors: string[] = []; const settingsFile = path.join(root, "settings.json"); fs.writeFileSync(settingsFile, JSON.stringify({ autoQueue: { transcription: { held: true, enabled: true } } })); const deps: ServiceDeps = { env: { PATH: `${bin}:${sys}`, HOME: path.join(root, "home"), XDG_CONFIG_HOME: path.join(root, "config"), FAKE_LOG: logFile }, out: { log: (s) => lines.push(s), error: (s) => errors.push(s) }, platform: opts.platform ?? "linux", repoRoot: repo, settingsFile, exportBuildsDir: path.join(repo, "export", ".export-builds"), memTotalBytes: 16283088 * 1024, nodeBin: "/usr/bin/node", user: "someone", probe: async () => "200", }; return { deps, root, units: path.join(root, "config", "systemd", "user"), log: () => (fs.existsSync(logFile) ? fs.readFileSync(logFile, "utf8").trim().split("\n") : []), lines, errors, }; } test("host install writes both units, reloads, enables and starts them; a second install adopts", async () => { const r = rig(); 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-housekeeping.service", "archilyzer-housekeeping.timer", "archilyzer-umtool.service"]); assert.ok(r.log().includes("systemctl --user daemon-reload")); // 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"))); fs.writeFileSync(path.join(r.root, "calls.log"), ""); r.lines.length = 0; assert.equal(await install({ mode: "host" }, r.deps), 0); assert.ok(r.lines.some((l) => l === "= archilyzer-editor.service: already installed, identical — adopted")); assert.equal(r.log().includes("systemctl --user daemon-reload"), false, "nothing written, nothing to reload"); }); test("a unit that differs is shown and refused, and replaced only with --force", async () => { const r = rig(); fs.mkdirSync(r.units, { recursive: true }); const file = path.join(r.units, "archilyzer-editor.service"); const planned = planUnits("host", { apps: "editor" }, r.deps)[0]; const tuned = planned.text.replace("MemoryMax=8G", "MemoryMax=12G"); fs.writeFileSync(file, tuned); assert.equal(await install({ mode: "host", apps: "editor" }, r.deps), 1); assert.equal(fs.readFileSync(file, "utf8"), tuned, "never overwritten without --force"); assert.ok(r.lines.some((l) => l.includes("- MemoryMax=12G"))); assert.ok(r.lines.some((l) => l.includes("+ MemoryMax=8G"))); assert.match(r.errors.join("\n"), /--force/); assert.equal(r.log().length, 0, "no systemctl call on a refusal"); assert.equal(await install({ mode: "host", apps: "editor", force: true }, r.deps), 0); assert.equal(fs.readFileSync(file, "utf8"), planned.text); }); test("--dry-run prints the units and the commands and writes nothing", async () => { const r = rig(); assert.equal(await install({ mode: "host", sites: "demo-private:8767", linger: true, dryRun: true }, r.deps), 0); assert.equal(fs.existsSync(r.units), false); assert.equal(r.log().length, 0); const text = r.lines.join("\n"); 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 archilyzer-housekeeping\.timer/); }); test("docker is the default mode when compose answers; one unit, and a missing image is named", async () => { const r = rig({ docker: true }); assert.equal(await install({ apps: "editor,umtool", noStart: true }, r.deps), 0, r.errors.join("\n")); assert.deepEqual(fs.readdirSync(r.units), ["archilyzer.service"]); const text = fs.readFileSync(path.join(r.units, "archilyzer.service"), "utf8"); assert.match(text, /^ExecStart=\S+\/docker compose -f docker-compose\.yml --profile umtool up --no-build$/m); assert.ok(r.log().includes("systemctl --user enable archilyzer.service"), "--no-start: enable without --now"); assert.ok(r.lines.some((l) => l.includes("image archilyzer:local is not built"))); assert.equal(r.lines.some((l) => l.includes("caddy")), false, "a pulled image is not ours to build"); }); test("docker mode adds the key overlay when the key file exists, without reading it", async () => { const r = rig({ docker: true }); fs.writeFileSync(path.join(r.deps.repoRoot, "docker-compose.anthropic.yml"), "services: {}\n"); const key = path.join(r.root, "key.env"); fs.writeFileSync(key, "not read\n", { mode: 0o000 }); r.deps.env.ARCHILYZER_ANTHROPIC_ENV_FILE = key; const [unit] = planUnits("docker", {}, r.deps); assert.match(unit.text, /-f docker-compose\.anthropic\.yml/); assert.equal(planUnits("docker", { overlays: "none" }, r.deps)[0].text.includes("anthropic"), false); }); test("bad arguments are refused with a sentence", async () => { const r = rig(); assert.throws(() => planUnits("host", { apps: "editor,ollama" }, r.deps), /host mode's apps are editor, umtool/); assert.throws(() => planUnits("host", { sites: "Bad Id:1" }, r.deps), /--sites takes/); assert.throws(() => planUnits("host", { editorMemory: "512M" }, r.deps), /whole GiB/); assert.throws(() => planUnits("docker", { apps: "editor" }, r.deps), /docker is not on PATH/); const off = rig({ platform: "darwin" }); await assert.rejects(install({ mode: "host" }, off.deps), /needs Linux and systemd/); }); test("status reads each unit's state, build, port, answer and the lane, read-only", async () => { const r = rig(); await install({ mode: "host", noStart: true }, r.deps); r.lines.length = 0; fs.writeFileSync(path.join(r.root, "calls.log"), ""); assert.equal(await status({}, r.deps), 0); const text = r.lines.join("\n"); assert.match(text, /archilyzer-editor\.service: active \(running\), enabled, pid 4242/); assert.match(text, /build build-editor-1/); assert.match(text, /http:\/\/127\.0\.0\.1:3001\/ → 200/); assert.match(text, /http:\/\/127\.0\.0\.1:3050\/ → 200/); assert.match(text, /transcription lane: HELD, armed/); assert.ok(r.log().every((l) => l.startsWith("systemctl --user show")), r.log().join("\n")); }); test("restart, logs and uninstall act on the installed units", async () => { const r = rig(); await install({ mode: "host", noStart: true }, r.deps); fs.writeFileSync(path.join(r.root, "calls.log"), ""); 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-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, 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-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", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "storage-overlay-")); const channels = path.join(root, "corpus", "channels"); const drive = path.join(root, "drive-a"); const loose = path.join(root, "drive-b", "lone", "media"); fs.mkdirSync(path.join(drive, "on-a", "media"), { recursive: true }); fs.mkdirSync(loose, { recursive: true }); for (const slug of ["on-a", "lone", "classic"]) fs.mkdirSync(path.join(channels, slug), { recursive: true }); fs.symlinkSync(path.join(drive, "on-a", "media"), path.join(channels, "on-a", "media")); fs.symlinkSync(loose, path.join(channels, "lone", "media")); fs.mkdirSync(path.join(channels, "classic", "media")); // A dangling link still names its drive: an unmounted one is exactly when the mount matters. fs.symlinkSync("/mnt/not-mounted/x/media", path.join(channels, "classic", "data")); const saved = path.join(root, "corpus", "saved-videos"); fs.symlinkSync(path.join(root, "drive-c", "saved"), saved); const mounts = storageMounts({ locationRoots: [drive, "relative/ignored"], channelsDir: channels, savedVideosDir: saved }); assert.deepEqual(mounts, [drive, "/mnt/not-mounted/x/media", loose, path.join(root, "drive-c", "saved")].sort((a, b) => (a === drive ? -1 : b === drive ? 1 : a.localeCompare(b)))); const yml = renderStorageOverlay(mounts, "/srv/corpus"); assert.match(yml, /source: \/srv\/corpus\n {8}target: \/data\/transcripts/); assert.ok(yml.includes(`source: ${loose}\n target: ${loose}\n`)); // One per bind in each of the two services, and one in the header's prose. assert.equal((yml.match(/create_host_path: false/g) ?? []).length, 2 * (mounts.length + 1) + 1); assert.match(renderStorageOverlay([]), /services: \{\}/); });