commit 7cfcbbabf88986f5b143d903ece057fc67abe028
parent 7566939b4a024c28f0e48a50bc3532f4c4a76bc6
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 16 Oct 2026 17:21:13 -0400
common: archilyzer service install|status|logs|restart|uninstall|storage-overlay — the apps as systemd user units, in Docker (one archilyzer.service running compose in the foreground) or on the host (archilyzer-editor/umtool/site-<id>.service, rendered byte for byte as the operator's own units); an installed unit is adopted when identical, diffed and refused without --force when not; --dry-run writes nothing. A cookies spec file:<path> is a cookies.txt (--cookies) for yt-dlp and gallery-dl
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 1505 insertions(+), 7 deletions(-)
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -876,6 +876,91 @@ export const COMMANDS: Command[] = [
check: flags.check === true,
}),
},
+ // The apps as systemd user units, in Docker or on the host (release 32;
+ // bin/service.ts, lib/service/units.ts).
+ {
+ 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",
+ flags: {
+ mode: "string",
+ apps: "string",
+ sites: "string",
+ overlays: "string",
+ bind: "string",
+ "editor-port": "string",
+ "umtool-port": "string",
+ "editor-memory": "string",
+ "umtool-memory": "string",
+ "idle-boot": "boolean",
+ linger: "boolean",
+ "no-start": "boolean",
+ force: "boolean",
+ "dry-run": "boolean",
+ },
+ run: async ({ flags }) =>
+ (await import("./service")).main("install", {
+ mode: str(flags.mode),
+ apps: str(flags.apps),
+ sites: str(flags.sites),
+ overlays: str(flags.overlays),
+ bind: str(flags.bind),
+ editorPort: str(flags["editor-port"]),
+ umtoolPort: str(flags["umtool-port"]),
+ editorMemory: str(flags["editor-memory"]),
+ umtoolMemory: str(flags["umtool-memory"]),
+ idleBoot: flags["idle-boot"] === true,
+ linger: flags.linger === true,
+ noStart: flags["no-start"] === true,
+ force: flags.force === true,
+ dryRun: flags["dry-run"] === true,
+ }),
+ },
+ {
+ 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",
+ run: async () => (await import("./service")).main("status", {}),
+ },
+ {
+ path: ["service", "logs"],
+ usage: "[--apps <a,b>] [--lines <n>] [--follow] the units' journal (journalctl --user), the last 200 lines by default",
+ flags: { apps: "string", lines: "string", follow: "boolean" },
+ run: async ({ flags }) =>
+ (await import("./service")).main("logs", { apps: str(flags.apps), lines: str(flags.lines), follow: flags.follow === true }),
+ },
+ {
+ 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",
+ flags: { apps: "string", "dry-run": "boolean" },
+ run: async ({ flags }) =>
+ (await import("./service")).main("restart", { apps: str(flags.apps), dryRun: flags["dry-run"] === true }),
+ },
+ {
+ path: ["service", "uninstall"],
+ usage: "[--mode docker|host] [--apps <a,b>] [--dry-run] stop, disable and remove the units (volumes, builds and the corpus are untouched)",
+ flags: { mode: "string", apps: "string", "dry-run": "boolean" },
+ run: async ({ flags }) =>
+ (await import("./service")).main("uninstall", {
+ mode: str(flags.mode),
+ apps: str(flags.apps),
+ dryRun: flags["dry-run"] === true,
+ }),
+ },
+ {
+ path: ["service", "storage-overlay"],
+ usage:
+ "[--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)",
+ flags: { corpus: "string", out: "string", check: "boolean", "dry-run": "boolean" },
+ run: async ({ flags }) =>
+ (await import("./service")).storageOverlayMain({
+ corpus: str(flags.corpus),
+ out: str(flags.out),
+ check: flags.check === true,
+ dryRun: flags["dry-run"] === true,
+ }),
+ },
{
path: ["doctor"],
usage:
@@ -902,6 +987,11 @@ export const COMMANDS: Command[] = [
},
];
+// A string flag's value, or undefined.
+function str(v: unknown): string | undefined {
+ return typeof v === "string" ? v : undefined;
+}
+
// A row for a bin that parses its own argv: a passthrough command that runs
// `common/bin/<file>` as a child with the words after its path.
function script(path: string[], file: string, usage: string, heapMb?: number): Command {
diff --git a/common/bin/service.test.ts b/common/bin/service.test.ts
@@ -0,0 +1,207 @@
+// `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"), USER: "someone", 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",
+ 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-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"));
+ // 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/);
+});
+
+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-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(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"));
+});
+
+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: \{\}/);
+});
diff --git a/common/bin/service.ts b/common/bin/service.ts
@@ -0,0 +1,724 @@
+// `archilyzer service install|status|logs|restart|uninstall` — the apps as
+// systemd user units, in Docker or on the host (release 32), and `service
+// storage-overlay`, the compose overlay that mounts every media drive at the
+// path the corpus's links name.
+//
+// The units are rendered by lib/service/units.ts (pure, tested byte for byte);
+// this file gathers the context, compares with what is installed, writes, and
+// drives systemctl / journalctl / loginctl / docker. Linux and systemd only — a
+// clear refusal anywhere else.
+//
+// Installing over units that already exist under the same names ADOPTS them:
+// identical text is left alone; a difference is shown as a diff and refused
+// unless --force, so a hand-tuned unit is never overwritten by accident.
+// Replacing a unit that is running does not restart it — `service restart`
+// does that, when its jobs can be interrupted.
+//
+// `--dry-run` prints the units and the commands and writes nothing.
+
+import { spawn, spawnSync, type SpawnSyncReturns } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { findOnPath } from "../lib/ttsInstall";
+import {
+ composeArgs,
+ defaultMemory,
+ DOCKER_APPS,
+ DOCKER_UNIT,
+ HOST_APPS,
+ hostUnitName,
+ renderDockerUnit,
+ renderHostUnit,
+ renderSiteUnit,
+ siteUnitName,
+ unitDiff,
+ type DockerApp,
+ type HostApp,
+ type MemoryLimit,
+} from "../lib/service/units";
+
+export type ServiceMode = "docker" | "host";
+
+export type ServiceOptions = {
+ mode?: string;
+ apps?: string;
+ sites?: string;
+ overlays?: string;
+ bind?: string;
+ editorPort?: string;
+ umtoolPort?: string;
+ editorMemory?: string;
+ umtoolMemory?: string;
+ idleBoot?: boolean;
+ linger?: boolean;
+ dryRun?: boolean;
+ force?: boolean;
+ noStart?: boolean;
+ follow?: boolean;
+ lines?: string;
+};
+
+type Out = { log: (s: string) => void; error: (s: string) => void };
+
+export type ServiceDeps = {
+ env: NodeJS.ProcessEnv;
+ out: Out;
+ platform: NodeJS.Platform;
+ // The checkout (paths.monorepoRoot).
+ repoRoot: string;
+ // Paths the status and the overlay read.
+ settingsFile: string;
+ exportBuildsDir: string;
+ memTotalBytes: number;
+ nodeBin: string;
+ // A probe of http://127.0.0.1:<port>/ — the status code, or a word.
+ probe: (url: string) => Promise<string>;
+};
+
+export async function defaultDeps(): Promise<ServiceDeps> {
+ const { getPaths } = await import("../lib/paths");
+ const p = getPaths();
+ return {
+ env: process.env,
+ out: console,
+ platform: process.platform,
+ repoRoot: p.monorepoRoot,
+ settingsFile: p.settingsFile,
+ exportBuildsDir: p.exportBuildsDir,
+ memTotalBytes: os.totalmem(),
+ nodeBin: process.execPath,
+ probe: async (url) => {
+ try {
+ const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(3000) });
+ return String(res.status);
+ } catch {
+ return "not answering";
+ }
+ },
+ };
+}
+
+// --- shared --------------------------------------------------------------
+
+class Refusal extends Error {}
+
+function unitDir(env: NodeJS.ProcessEnv): string {
+ const home = env.HOME || os.homedir();
+ return path.join(env.XDG_CONFIG_HOME || path.join(home, ".config"), "systemd", "user");
+}
+
+function run(bin: string, args: string[], env: NodeJS.ProcessEnv, cwd?: string): SpawnSyncReturns<string> {
+ return spawnSync(bin, args, { env, cwd, encoding: "utf8" });
+}
+
+function need(bin: string, env: NodeJS.ProcessEnv, why: string): string {
+ const found = findOnPath(bin, env.PATH);
+ if (!found) throw new Refusal(`${bin} is not on PATH — ${why}`);
+ return found;
+}
+
+function refuseOffLinux(deps: ServiceDeps): void {
+ if (deps.platform !== "linux") {
+ throw new Refusal(
+ `archilyzer service needs Linux and systemd (this is ${deps.platform}). In Docker Desktop, ` +
+ "compose's own `restart: unless-stopped` brings the stack back with Docker — `docker compose up -d` is the whole install.",
+ );
+ }
+}
+
+function splitList(v: string | undefined): string[] {
+ return (v ?? "")
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean);
+}
+
+function installedUnits(dir: string): string[] {
+ let names: string[];
+ try {
+ names = fs.readdirSync(dir);
+ } catch {
+ return [];
+ }
+ return names.filter((n) => n === DOCKER_UNIT || /^archilyzer-[a-z0-9-]+\.service$/.test(n)).sort();
+}
+
+function dockerAvailable(env: NodeJS.ProcessEnv): string | null {
+ const docker = findOnPath("docker", env.PATH);
+ if (!docker) return null;
+ return run(docker, ["compose", "version"], env).status === 0 ? docker : null;
+}
+
+/** The mode a command acts on: --mode, else what is installed, else docker when compose answers, else host. */
+export function resolveMode(opts: ServiceOptions, deps: ServiceDeps): ServiceMode {
+ if (opts.mode !== undefined) {
+ if (opts.mode !== "docker" && opts.mode !== "host") throw new Refusal("--mode is docker or host");
+ return opts.mode;
+ }
+ const installed = installedUnits(unitDir(deps.env));
+ if (installed.some((u) => u !== DOCKER_UNIT)) return "host";
+ if (installed.includes(DOCKER_UNIT)) return "docker";
+ return dockerAvailable(deps.env) ? "docker" : "host";
+}
+
+function parsePort(v: string | undefined, fallback: number, name: string): number {
+ if (v === undefined) return fallback;
+ const n = Number(v);
+ if (!Number.isInteger(n) || n < 1 || n > 65535) throw new Refusal(`--${name} is a port number`);
+ return n;
+}
+
+function parseMemory(v: string | undefined, fallback: MemoryLimit, name: string): MemoryLimit {
+ if (v === undefined) return fallback;
+ const m = /^(\d+)G$/i.exec(v.trim());
+ if (!m || Number(m[1]) < 2) throw new Refusal(`--${name} is whole GiB, at least 2 (e.g. 8G); MemoryHigh is set 1G under it`);
+ const max = Number(m[1]);
+ return { high: max - 1, max };
+}
+
+type Planned = { name: string; text: string };
+
+function anthropicKeyFile(env: NodeJS.ProcessEnv): string {
+ const home = env.HOME || os.homedir();
+ return env.ARCHILYZER_ANTHROPIC_ENV_FILE || path.join(home, ".config", "archilyzer", "anthropic.env");
+}
+
+/** The compose overlays a docker unit runs with: --overlays, or the automatic ones. */
+export function resolveOverlays(opts: ServiceOptions, deps: ServiceDeps): { files: string[]; why: string[] } {
+ const list = splitList(opts.overlays);
+ if (list.length === 1 && list[0] === "none") return { files: [], why: [] };
+ if (list.length > 0) {
+ const files = list.map((name) => `docker-compose.${name}.yml`);
+ for (const f of files) {
+ if (!fs.existsSync(path.join(deps.repoRoot, f))) throw new Refusal(`no ${f} in ${deps.repoRoot}`);
+ }
+ return { files, why: files.map((f) => `${f} (--overlays)`) };
+ }
+ const files: string[] = [];
+ const why: string[] = [];
+ // The key file's EXISTENCE only — it is never opened here.
+ if (fs.existsSync(anthropicKeyFile(deps.env))) {
+ files.push("docker-compose.anthropic.yml");
+ why.push("docker-compose.anthropic.yml (the Claude API key file exists)");
+ }
+ if (fs.existsSync(path.join(deps.repoRoot, "docker-compose.storage.yml"))) {
+ files.push("docker-compose.storage.yml");
+ why.push("docker-compose.storage.yml (written by `archilyzer service storage-overlay`)");
+ }
+ return { files, why };
+}
+
+/** The units `install` would write, rendered. */
+export function planUnits(mode: ServiceMode, opts: ServiceOptions, deps: ServiceDeps): Planned[] {
+ const home = deps.env.HOME || os.homedir();
+ if (mode === "docker") {
+ if (opts.sites) throw new Refusal("--sites is host mode's; in Docker the `site` profile serves the local deploy");
+ const apps = splitList(opts.apps ?? "editor");
+ for (const a of apps) {
+ if (!DOCKER_APPS.includes(a as DockerApp)) throw new Refusal(`docker mode's apps are ${DOCKER_APPS.join(", ")} — not "${a}"`);
+ }
+ const docker = need("docker", deps.env, "docker mode runs `docker compose`");
+ const { files } = resolveOverlays(opts, deps);
+ return [
+ {
+ name: DOCKER_UNIT,
+ text: renderDockerUnit({ repoRoot: deps.repoRoot, home, dockerBin: docker, apps: apps as DockerApp[], overlays: files }),
+ },
+ ];
+ }
+ const apps = splitList(opts.apps ?? HOST_APPS.join(","));
+ for (const a of apps) {
+ if (!HOST_APPS.includes(a as HostApp)) throw new Refusal(`host mode's apps are ${HOST_APPS.join(", ")} — not "${a}" (private sites: --sites <id>:<port>)`);
+ }
+ // Next's own default, and what the editor has always been started with here.
+ // The editor has no login: on a machine others can reach, pass --bind 127.0.0.1.
+ const bind = opts.bind ?? "0.0.0.0";
+ const planned: Planned[] = [];
+ for (const app of apps as HostApp[]) {
+ const port = app === "editor" ? parsePort(opts.editorPort, 3001, "editor-port") : parsePort(opts.umtoolPort, 3050, "umtool-port");
+ const memory =
+ app === "editor"
+ ? parseMemory(opts.editorMemory, defaultMemory("editor", deps.memTotalBytes), "editor-memory")
+ : parseMemory(opts.umtoolMemory, defaultMemory("umtool", deps.memTotalBytes), "umtool-memory");
+ planned.push({
+ name: hostUnitName(app),
+ text: renderHostUnit(app, { repoRoot: deps.repoRoot, home, nodeBin: deps.nodeBin, bind, port, memory, idleBoot: opts.idleBoot === true }),
+ });
+ }
+ for (const spec of splitList(opts.sites)) {
+ const m = /^([a-z0-9][a-z0-9-]*):(\d+)$/.exec(spec);
+ if (!m) throw new Refusal(`--sites takes <id>:<port>[,<id>:<port>] — not "${spec}"`);
+ const port = parsePort(m[2], 0, "sites");
+ planned.push({
+ name: siteUnitName(m[1]),
+ text: renderSiteUnit({
+ repoRoot: deps.repoRoot,
+ home,
+ nodeBin: deps.nodeBin,
+ siteId: m[1],
+ bundleDir: path.join(deps.exportBuildsDir, m[1], "out"),
+ port,
+ }),
+ });
+ }
+ return planned;
+}
+
+// --- install -------------------------------------------------------------
+
+export async function install(opts: ServiceOptions, deps: ServiceDeps): Promise<number> {
+ refuseOffLinux(deps);
+ const { out, env } = deps;
+ const mode = resolveMode(opts, deps);
+ const planned = planUnits(mode, opts, deps);
+ const dir = unitDir(env);
+ const systemctl = opts.dryRun ? "systemctl" : need("systemctl", env, "the units are systemd user units");
+
+ out.log(`mode: ${mode}${opts.mode === undefined ? " (default)" : ""}; units in ${dir}`);
+ if (mode === "docker") {
+ for (const w of resolveOverlays(opts, deps).why) out.log(`overlay: ${w}`);
+ }
+
+ // Compare with what is there.
+ const toWrite: Planned[] = [];
+ let refused = false;
+ for (const unit of planned) {
+ const file = path.join(dir, unit.name);
+ let installed: string | null = null;
+ try {
+ installed = fs.readFileSync(file, "utf8");
+ } catch {
+ installed = null;
+ }
+ if (installed === null) {
+ out.log(`+ ${unit.name}: new`);
+ toWrite.push(unit);
+ } else if (installed === unit.text) {
+ out.log(`= ${unit.name}: already installed, identical — adopted`);
+ } else {
+ out.log(`! ${unit.name}: installed, and different from what this would write:`);
+ out.log(unitDiff(installed, unit.text).replace(/^/gm, " "));
+ if (opts.force) toWrite.push(unit);
+ else refused = true;
+ }
+ }
+ if (refused) {
+ out.error("Refused: a unit above differs from the installed one. Pass --force to replace it (a running unit is not restarted; `archilyzer service restart` does that).");
+ return 1;
+ }
+
+ // 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 cmds: string[][] = [];
+ if (toWrite.length) cmds.push([systemctl, "--user", "daemon-reload"]);
+ cmds.push([systemctl, "--user", "enable", ...(opts.noStart ? [] : ["--now"]), ...names]);
+ const user = env.USER || os.userInfo().username;
+ if (opts.linger) cmds.push(["loginctl", "enable-linger", user]);
+
+ if (opts.dryRun) {
+ for (const unit of planned) {
+ out.log(`\n--- ${path.join(dir, unit.name)} ---\n${unit.text}`);
+ }
+ out.log("Would run:");
+ for (const c of cmds) out.log(` ${c.join(" ")}`);
+ out.log("(dry run: nothing written)");
+ return 0;
+ }
+
+ // A unit replaced while it runs keeps running the old text until a restart.
+ const replacedRunning = toWrite.filter((u) => fs.existsSync(path.join(dir, u.name)) && isActive(systemctl, u.name, env));
+ fs.mkdirSync(dir, { recursive: true });
+ for (const unit of toWrite) {
+ const file = path.join(dir, unit.name);
+ const tmp = `${file}.tmp-${process.pid}`;
+ fs.writeFileSync(tmp, unit.text);
+ fs.renameSync(tmp, file);
+ out.log(`wrote ${file}`);
+ }
+ for (const c of cmds) {
+ const r = run(c[0], c.slice(1), env);
+ if (r.status !== 0) {
+ out.error(`${c.join(" ")} failed: ${(r.stderr || r.stdout || "").trim()}`);
+ return 1;
+ }
+ out.log(`ran: ${c.join(" ")}`);
+ }
+ if (replacedRunning.length) {
+ out.log(`Replaced while running: ${replacedRunning.map((u) => u.name).join(", ")} — the new unit applies at the next restart (archilyzer service restart).`);
+ }
+ if (!opts.linger && !lingerOn(user, env)) {
+ out.log(`Linger is off for ${user}: these units start when you log in, not at boot. --linger turns it on (loginctl enable-linger ${user}).`);
+ }
+ return 0;
+}
+
+function isActive(systemctl: string, unit: string, env: NodeJS.ProcessEnv): boolean {
+ return run(systemctl, ["--user", "is-active", "--quiet", unit], env).status === 0;
+}
+
+function lingerOn(user: string, env: NodeJS.ProcessEnv): boolean {
+ const r = run("loginctl", ["show-user", user, "--property=Linger"], env);
+ return r.status === 0 && /Linger=yes/.test(r.stdout);
+}
+
+function buildWarnings(mode: ServiceMode, planned: Planned[], opts: ServiceOptions, deps: ServiceDeps): string[] {
+ const out: string[] = [];
+ if (mode === "host") {
+ for (const unit of planned) {
+ const app = /^archilyzer-(editor|umtool)\.service$/.exec(unit.name)?.[1];
+ if (app && !fs.existsSync(path.join(deps.repoRoot, app, ".next", "BUILD_ID"))) {
+ out.push(`${app} has no build yet; its unit refuses to start until there is one — pnpm --filter ${app} exec next build`);
+ }
+ const site = /^archilyzer-site-(.+)\.service$/.exec(unit.name)?.[1];
+ if (site && !fs.existsSync(path.join(deps.exportBuildsDir, site, "out"))) {
+ out.push(`site ${site} has no bundle yet; its unit refuses to start until there is one — pnpm archilyzer publish build ${site}`);
+ }
+ }
+ return out;
+ }
+ const docker = findOnPath("docker", deps.env.PATH);
+ if (!docker) return out;
+ const apps = splitList(opts.apps ?? "editor") as DockerApp[];
+ const args = composeArgs({ apps, overlays: resolveOverlays(opts, deps).files });
+ const images = run(docker, [...args, "config", "--images"], deps.env, deps.repoRoot);
+ if (images.status !== 0) {
+ out.push(`docker compose config failed: ${(images.stderr || "").trim().split("\n")[0]}`);
+ return out;
+ }
+ for (const image of images.stdout.split("\n").map((s) => s.trim()).filter((s) => s.startsWith("archilyzer:"))) {
+ if (run(docker, ["image", "inspect", image], deps.env).status !== 0) {
+ out.push(`image ${image} is not built; the unit refuses to start until it is — docker ${args.join(" ")} build`);
+ }
+ }
+ return out;
+}
+
+// --- 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);
+ const props: Record<string, string> = {};
+ for (const line of (r.stdout || "").split("\n")) {
+ const i = line.indexOf("=");
+ if (i > 0) props[line.slice(0, i)] = line.slice(i + 1);
+ }
+ return props;
+}
+
+function unitField(text: string, key: string): string | undefined {
+ return new RegExp(`^${key}=(.*)$`, "m").exec(text)?.[1];
+}
+
+function laneLine(settingsText: string | null): string {
+ if (settingsText === null) return "transcription lane: settings not readable";
+ try {
+ const s = JSON.parse(settingsText) as { autoQueue?: { transcription?: { held?: unknown; enabled?: unknown } } };
+ const t = s.autoQueue?.transcription ?? {};
+ return `transcription lane: ${t.held === true ? "HELD" : "free"}${t.enabled === true ? ", armed" : ", not armed"}`;
+ } catch {
+ return "transcription lane: settings do not parse";
+ }
+}
+
+export async function status(opts: ServiceOptions, deps: ServiceDeps): Promise<number> {
+ refuseOffLinux(deps);
+ const { out, env } = deps;
+ const dir = unitDir(env);
+ const units = installedUnits(dir);
+ if (units.length === 0) {
+ out.log(`No archilyzer units in ${dir}. Install them: archilyzer service install [--mode docker|host]`);
+ return 0;
+ }
+ const systemctl = need("systemctl", env, "status asks systemd");
+ for (const unit of units) {
+ const text = fs.readFileSync(path.join(dir, unit), "utf8");
+ const p = show(systemctl, unit, env);
+ const state = `${p.ActiveState ?? "?"} (${p.SubState ?? "?"})`;
+ const enabled = p.UnitFileState ?? "?";
+ out.log(`${unit}: ${state}, ${enabled}${p.MainPID && p.MainPID !== "0" ? `, pid ${p.MainPID}` : ""}${p.ActiveEnterTimestamp ? `, since ${p.ActiveEnterTimestamp}` : ""}`);
+ const exec = unitField(text, "ExecStart") ?? "";
+ const workdir = unitField(text, "WorkingDirectory") ?? "";
+ if (unit === DOCKER_UNIT) {
+ const docker = findOnPath("docker", env.PATH);
+ const args = exec.split(" ").slice(1, -2); // drop the docker path, then "up --no-build"
+ if (docker) {
+ const ps = run(docker, [...args, "ps", "--format", "{{.Service}}\t{{.State}}\t{{.Status}}"], env, workdir);
+ for (const row of (ps.stdout || "").split("\n").filter(Boolean)) out.log(` ${row.replace(/\t/g, " ")}`);
+ const port = readDotEnv(path.join(workdir, ".env")).EDITOR_HTTP_PORT ?? "8081";
+ out.log(` editor http://127.0.0.1:${port}/ → ${await deps.probe(`http://127.0.0.1:${port}/`)}`);
+ const settings = run(docker, [...args, "exec", "-T", "editor", "cat", "/data/config/settings.json"], env, workdir);
+ out.log(` ${laneLine(settings.status === 0 ? settings.stdout : null)}`);
+ }
+ continue;
+ }
+ const port = /-p (\d+)$/.exec(exec)?.[1] ?? / (\d+)$/.exec(exec)?.[1];
+ if (/archilyzer-(editor|umtool)\.service/.test(unit)) {
+ let buildId = "none";
+ try {
+ buildId = fs.readFileSync(path.join(workdir, ".next", "BUILD_ID"), "utf8").trim();
+ } catch {
+ /* none */
+ }
+ out.log(` build ${buildId}`);
+ }
+ if (port) out.log(` http://127.0.0.1:${port}/ → ${await deps.probe(`http://127.0.0.1:${port}/`)}`);
+ if (unit === hostUnitName("editor")) {
+ let text: string | null = null;
+ try {
+ text = fs.readFileSync(deps.settingsFile, "utf8");
+ } catch {
+ text = null;
+ }
+ out.log(` ${laneLine(text)}`);
+ }
+ }
+ return 0;
+}
+
+function readDotEnv(file: string): Record<string, string> {
+ const outv: Record<string, string> = {};
+ let text = "";
+ try {
+ text = fs.readFileSync(file, "utf8");
+ } catch {
+ return outv;
+ }
+ for (const raw of text.split("\n")) {
+ const m = /^\s*([A-Z_][A-Z0-9_]*)=(.*)$/.exec(raw);
+ // Only the port keys are ever read from here; nothing else is kept.
+ if (m && /_HTTP_PORT$/.test(m[1])) outv[m[1]] = m[2].trim();
+ }
+ return outv;
+}
+
+// --- logs / restart / uninstall ----------------------------------------------
+
+function selectUnits(opts: ServiceOptions, deps: ServiceDeps): string[] {
+ const units = installedUnits(unitDir(deps.env));
+ const apps = splitList(opts.apps);
+ 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);
+ return units.filter((u) => wanted.has(u));
+}
+
+export async function logs(opts: ServiceOptions, deps: ServiceDeps): Promise<number> {
+ refuseOffLinux(deps);
+ const units = selectUnits(opts, deps);
+ if (units.length === 0) {
+ deps.out.error("No archilyzer units installed (or none matches --apps).");
+ return 1;
+ }
+ const journalctl = need("journalctl", deps.env, "logs read the journal");
+ const lines = opts.lines ?? "200";
+ if (!/^\d+$/.test(lines)) throw new Refusal("--lines is a number");
+ const args = ["--user", ...units.flatMap((u) => ["-u", u]), "-n", lines, "--no-pager", ...(opts.follow ? ["-f"] : [])];
+ return new Promise((resolve) => {
+ const child = spawn(journalctl, args, { stdio: "inherit", env: deps.env });
+ child.on("close", (code) => resolve(code ?? 1));
+ child.on("error", () => resolve(1));
+ });
+}
+
+export async function restart(opts: ServiceOptions, deps: ServiceDeps): Promise<number> {
+ refuseOffLinux(deps);
+ const units = selectUnits(opts, deps);
+ if (units.length === 0) {
+ deps.out.error("No archilyzer units installed (or none matches --apps).");
+ return 1;
+ }
+ const cmd = ["--user", "restart", ...units];
+ if (opts.dryRun) {
+ deps.out.log(`Would run: systemctl ${cmd.join(" ")}`);
+ return 0;
+ }
+ const systemctl = need("systemctl", deps.env, "restart asks systemd");
+ const r = run(systemctl, cmd, deps.env);
+ if (r.status !== 0) {
+ deps.out.error(`systemctl ${cmd.join(" ")} failed: ${(r.stderr || "").trim()}`);
+ return 1;
+ }
+ deps.out.log(`restarted ${units.join(", ")}`);
+ return 0;
+}
+
+export async function uninstall(opts: ServiceOptions, deps: ServiceDeps): Promise<number> {
+ refuseOffLinux(deps);
+ const dir = unitDir(deps.env);
+ let units = selectUnits(opts, deps);
+ if (opts.mode === "docker") units = units.filter((u) => u === DOCKER_UNIT);
+ if (opts.mode === "host") units = units.filter((u) => u !== DOCKER_UNIT);
+ if (units.length === 0) {
+ deps.out.log(`Nothing to uninstall in ${dir}.`);
+ return 0;
+ }
+ const cmds = [
+ ["systemctl", "--user", "disable", "--now", ...units],
+ ["systemctl", "--user", "daemon-reload"],
+ ];
+ if (opts.dryRun) {
+ deps.out.log("Would run:");
+ 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);
+ if (stop.status !== 0) {
+ deps.out.error(`systemctl ${cmds[0].slice(1).join(" ")} failed: ${(stop.stderr || "").trim()}`);
+ return 1;
+ }
+ for (const u of units) {
+ fs.rmSync(path.join(dir, u), { force: true });
+ deps.out.log(`removed ${path.join(dir, u)}`);
+ }
+ run(systemctl, cmds[1].slice(1), deps.env);
+ return 0;
+}
+
+// --- storage-overlay ---------------------------------------------------------
+
+export type StorageOverlayOptions = { out?: string; corpus?: string; check?: boolean; dryRun?: boolean };
+
+/**
+ * The directories a container must see at the SAME absolute path for the
+ * corpus's links to resolve: every storage location's root, every channel
+ * `media` link whose target no location covers, and the saved-video store when
+ * it is a link. Read off the corpus disk only (lstat/readlink) — no media drive
+ * is touched, so an unmounted one cannot stall this.
+ */
+export function storageMounts(input: { locationRoots: string[]; channelsDir: string; savedVideosDir: string }): string[] {
+ const roots = input.locationRoots.filter((r) => path.isAbsolute(r)).map((r) => path.resolve(r));
+ const under = (p: string) => roots.some((r) => p === r || p.startsWith(r + path.sep));
+ const extra = new Set<string>();
+ const linkTarget = (p: string): string | null => {
+ try {
+ if (!fs.lstatSync(p).isSymbolicLink()) return null;
+ const t = fs.readlinkSync(p);
+ return path.isAbsolute(t) ? path.resolve(t) : null;
+ } catch {
+ return null;
+ }
+ };
+ let slugs: string[] = [];
+ try {
+ slugs = fs.readdirSync(input.channelsDir);
+ } catch {
+ slugs = [];
+ }
+ for (const slug of slugs.sort()) {
+ for (const name of ["media", "data"]) {
+ const t = linkTarget(path.join(input.channelsDir, slug, name));
+ if (t && !under(t)) extra.add(t);
+ }
+ }
+ const saved = linkTarget(input.savedVideosDir);
+ if (saved && !under(saved)) extra.add(saved);
+ return [...new Set([...roots, ...[...extra].sort()])];
+}
+
+export function renderStorageOverlay(mounts: string[], corpus?: string): string {
+ const bind = (source: string, target: string) => [
+ " - type: bind",
+ ` source: ${source}`,
+ ` target: ${target}`,
+ " bind:",
+ " create_host_path: false",
+ ];
+ const volumes = [
+ ...(corpus ? bind(corpus, "/data/transcripts") : []),
+ ...mounts.flatMap((m) => bind(m, m)),
+ ];
+ const header = [
+ "# Generated by `archilyzer service storage-overlay` — do not edit; re-run it",
+ "# after adding a storage location or moving a channel's media.",
+ "#",
+ "# Every media drive the corpus's links point at, mounted at the SAME absolute",
+ "# path inside the containers (a channel's `media` link is absolute). A drive",
+ "# that is not mounted on the host refuses `up` (create_host_path: false)",
+ "# rather than mounting an empty directory the corpus would read as no media.",
+ "#",
+ "# docker compose -f docker-compose.yml -f docker-compose.storage.yml up -d",
+ "# (`archilyzer service install` adds it by itself when this file exists.)",
+ ];
+ if (volumes.length === 0) {
+ return [...header, "#", "# No location, and no link to another drive: nothing to mount.", "services: {}", ""].join("\n");
+ }
+ return [...header, "", "services:", " editor:", " volumes:", ...volumes, " umtool:", " volumes:", ...volumes, ""].join("\n");
+}
+
+export async function storageOverlay(opts: StorageOverlayOptions, deps: ServiceDeps): Promise<number> {
+ const { getSettings } = await import("../lib/settings");
+ const { getPaths } = await import("../lib/paths");
+ const p = getPaths();
+ const settings = await getSettings();
+ const mounts = storageMounts({
+ locationRoots: settings.storage.locations.map((l) => l.root),
+ channelsDir: p.channelsDir,
+ savedVideosDir: p.savedVideosDir,
+ });
+ const corpus = opts.corpus ? path.resolve(opts.corpus) : undefined;
+ const text = renderStorageOverlay(mounts, corpus);
+ const file = path.resolve(deps.repoRoot, opts.out ?? "docker-compose.storage.yml");
+ if (opts.dryRun) {
+ deps.out.log(text);
+ return 0;
+ }
+ if (opts.check) {
+ let current = "";
+ try {
+ current = fs.readFileSync(file, "utf8");
+ } catch {
+ /* missing */
+ }
+ if (current === text) {
+ deps.out.log(`${file} is current (${mounts.length} mount${mounts.length === 1 ? "" : "s"})`);
+ return 0;
+ }
+ deps.out.error(`${file} is stale — re-run archilyzer service storage-overlay`);
+ return 1;
+ }
+ fs.writeFileSync(file, text);
+ deps.out.log(`wrote ${file}: ${mounts.length} mount${mounts.length === 1 ? "" : "s"}${corpus ? `, the corpus from ${corpus}` : ""}`);
+ for (const m of mounts) deps.out.log(` ${m}`);
+ return 0;
+}
+
+// --- entry -------------------------------------------------------------------
+
+export async function main(
+ verb: "install" | "status" | "logs" | "restart" | "uninstall",
+ opts: ServiceOptions,
+ deps?: ServiceDeps,
+): Promise<number> {
+ const d = deps ?? (await defaultDeps());
+ try {
+ switch (verb) {
+ case "install":
+ return await install(opts, d);
+ case "status":
+ return await status(opts, d);
+ case "logs":
+ return await logs(opts, d);
+ case "restart":
+ return await restart(opts, d);
+ case "uninstall":
+ return await uninstall(opts, d);
+ }
+ } catch (err) {
+ if (err instanceof Refusal) {
+ d.out.error(`service ${verb}: ${err.message}`);
+ return 2;
+ }
+ throw err;
+ }
+}
+
+export async function storageOverlayMain(opts: StorageOverlayOptions, deps?: ServiceDeps): Promise<number> {
+ const d = deps ?? (await defaultDeps());
+ return storageOverlay(opts, d);
+}
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -202,7 +202,7 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
downloadFilter:
"Per-channel title/description download filter, matched against the per-video metadata prefetch. A declined video is SETTLED by a terminal download-outcome keyed on the filter's signature, not by an archive line, so changing either pattern re-evaluates every settled video on the next run. An object with no real rule is dropped (the filter is inert).",
cookiesFromBrowser:
- "Per-channel override of the global cookies-from-browser spec. Trimmed; blank = inherit.",
+ "Per-channel override of the global cookies-from-browser spec (a browser spec, or `file:<path>` for a cookies.txt). Trimmed; blank = inherit.",
cookieMode: "Per-channel override of the global cookie mode. Absent = inherit.",
sleepBetweenDownloadsSeconds:
"Per-channel override for the global pause between downloads. Absent = inherit; 0 = no sleep; floored and capped at 600.",
diff --git a/common/lib/cookiePolicy.test.ts b/common/lib/cookiePolicy.test.ts
@@ -5,6 +5,7 @@ import {
alwaysCookies,
authRetryCookies,
cookieArgs,
+ cookieFileOf,
isCookieMode,
resolveCookiePolicy,
type ResolvedCookiePolicy,
@@ -107,3 +108,15 @@ test("cookieArgs emits the flag pair or nothing", () => {
assert.deepEqual(cookieArgs(undefined), []);
assert.deepEqual(cookieArgs(""), []);
});
+
+test("a file: spec is a cookies.txt: --cookies <path>, never --cookies-from-browser", () => {
+ assert.deepEqual(cookieArgs("file:/data/config/cookies.txt"), ["--cookies", "/data/config/cookies.txt"]);
+ assert.deepEqual(cookieArgs(" file: /x/cookies.txt "), ["--cookies", "/x/cookies.txt"]);
+ // A file: with no path names nothing — no flag at all, rather than a browser called "file:".
+ assert.deepEqual(cookieArgs("file:"), []);
+ assert.equal(cookieFileOf("file:/a"), "/a");
+ assert.equal(cookieFileOf("firefox:/data/browser/firefox"), undefined);
+ assert.equal(cookieFileOf(undefined), undefined);
+ // A browser spec whose profile is a path stays a browser spec.
+ assert.deepEqual(cookieArgs("firefox:/data/browser/firefox"), ["--cookies-from-browser", "firefox:/data/browser/firefox"]);
+});
diff --git a/common/lib/cookiePolicy.ts b/common/lib/cookiePolicy.ts
@@ -79,8 +79,27 @@ export function authRetryCookies(p: ResolvedCookiePolicy): string | undefined {
return p.mode === "defer" ? undefined : p.cookies;
}
+// A spec that names a cookies.txt (Netscape format) rather than a browser:
+// `file:<path>`. For a machine that cannot read a browser's store — a Docker
+// container (Chrome's cookies are keyring-encrypted on Linux), a server with no
+// browser at all. The path, or undefined when the spec names a browser.
+export const COOKIE_FILE_PREFIX = "file:";
+export function cookieFileOf(spec: string | undefined): string | undefined {
+ const s = spec?.trim() ?? "";
+ if (!s.startsWith(COOKIE_FILE_PREFIX)) return undefined;
+ const file = s.slice(COOKIE_FILE_PREFIX.length).trim();
+ return file || undefined;
+}
+
// The argv fragment for a resolved cookie spec. Empty when there is none, so
-// spawn sites can unconditionally spread it.
+// spawn sites can unconditionally spread it. `file:<path>` → `--cookies
+// <path>` (yt-dlp and gallery-dl spell it the same); anything else is a
+// browser spec → `--cookies-from-browser <spec>`.
export function cookieArgs(cookies: string | undefined): string[] {
- return cookies ? ["--cookies-from-browser", cookies] : [];
+ if (!cookies) return [];
+ if (cookies.trim().startsWith(COOKIE_FILE_PREFIX)) {
+ const file = cookieFileOf(cookies);
+ return file ? ["--cookies", file] : [];
+ }
+ return ["--cookies-from-browser", cookies];
}
diff --git a/common/lib/service/units.test.ts b/common/lib/service/units.test.ts
@@ -0,0 +1,164 @@
+// The rendered units, byte for byte: host mode's two (the shape the
+// operator's own units on the reference machine took, with its paths replaced
+// by synthetic ones), a private site's, and docker mode's.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/service/units.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ composeArgs,
+ defaultMemory,
+ hostUnitPath,
+ renderDockerUnit,
+ renderHostUnit,
+ renderSiteUnit,
+ unitDiff,
+} from "./units";
+
+// MemTotal of the reference machine (16 GB nominal), in bytes.
+const MEM_16G = 16283088 * 1024;
+const CTX = { repoRoot: "/home/user/archilyzer", home: "/home/user", nodeBin: "/usr/bin/node", bind: "0.0.0.0" };
+
+const EDITOR = `[Unit]
+Description=Archilyzer editor (:3001)
+Documentation=file:///home/user/archilyzer/RUNNING_IN_DOCKER.md
+After=network-online.target
+Wants=network-online.target
+# A crash-loop stops after 5 tries in 5 minutes instead of spinning.
+StartLimitIntervalSec=300
+StartLimitBurst=5
+
+[Service]
+Type=simple
+WorkingDirectory=/home/user/archilyzer/editor
+# Next reads editor/.env itself (WORKER_TOKEN and the rest).
+Environment=NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 UV_THREADPOOL_SIZE=16
+# yt-dlp, gallery-dl, parakeet-cli and git-filter-repo live in ~/.local/bin.
+Environment=PATH=/home/user/.local/bin:/home/user/.local/share/pnpm:/usr/local/bin:/usr/bin:/bin
+ExecStartPre=/bin/sh -c 'test -s .next/BUILD_ID || { echo "archilyzer-editor: no build in /home/user/archilyzer/editor/.next - build it first (pnpm --filter editor exec next build)" >&2; exit 1; }'
+# node directly, not pnpm: pnpm swallows SIGTERM.
+ExecStart=/usr/bin/node node_modules/next/dist/bin/next start -H 0.0.0.0 -p 3001
+Restart=on-failure
+RestartSec=5
+# 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=90
+# 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.
+MemoryHigh=7G
+MemoryMax=8G
+
+[Install]
+WantedBy=default.target
+`;
+
+const UMTOOL = `[Unit]
+Description=Archilyzer umtool (:3050)
+Documentation=file:///home/user/archilyzer/RUNNING_IN_DOCKER.md
+After=network-online.target archilyzer-editor.service
+Wants=network-online.target
+StartLimitIntervalSec=300
+StartLimitBurst=5
+
+[Service]
+Type=simple
+WorkingDirectory=/home/user/archilyzer/umtool
+# Next reads umtool/.env.local itself.
+Environment=NODE_ENV=production NEXT_TELEMETRY_DISABLED=1
+Environment=PATH=/home/user/.local/bin:/home/user/.local/share/pnpm:/usr/local/bin:/usr/bin:/bin
+ExecStartPre=/bin/sh -c 'test -s .next/BUILD_ID || { echo "archilyzer-umtool: no build in /home/user/archilyzer/umtool/.next - build it first (pnpm --filter umtool exec next build)" >&2; exit 1; }'
+ExecStart=/usr/bin/node node_modules/next/dist/bin/next start -H 0.0.0.0 -p 3050
+Restart=on-failure
+RestartSec=5
+KillMode=mixed
+TimeoutStopSec=60
+# Renders started from umtool (ffmpeg, the chrome frames) run in this unit.
+MemoryHigh=5G
+MemoryMax=6G
+
+[Install]
+WantedBy=default.target
+`;
+
+test("host mode renders the editor unit exactly", () => {
+ const got = renderHostUnit("editor", { ...CTX, port: 3001, memory: defaultMemory("editor", MEM_16G) });
+ assert.equal(got, EDITOR, unitDiff(EDITOR, got));
+});
+
+test("host mode renders the umtool unit exactly", () => {
+ const got = renderHostUnit("umtool", { ...CTX, port: 3050, memory: defaultMemory("umtool", MEM_16G) });
+ assert.equal(got, UMTOOL, unitDiff(UMTOOL, got));
+});
+
+test("memory defaults scale with MemTotal and never fall under the floor", () => {
+ assert.deepEqual(defaultMemory("editor", MEM_16G), { high: 7, max: 8 });
+ assert.deepEqual(defaultMemory("umtool", MEM_16G), { high: 5, max: 6 });
+ assert.deepEqual(defaultMemory("editor", 64 * 2 ** 30), { high: 31, max: 32 });
+ assert.deepEqual(defaultMemory("editor", 2 * 2 ** 30), { high: 2, max: 3 });
+ assert.deepEqual(defaultMemory("umtool", 2 * 2 ** 30), { high: 1, max: 2 });
+});
+
+test("the idle-boot option reaches the editor's environment only", () => {
+ const ed = renderHostUnit("editor", { ...CTX, port: 3001, memory: { high: 7, max: 8 }, idleBoot: true });
+ assert.match(ed, /^Environment=NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 UV_THREADPOOL_SIZE=16 ARCHILYZER_IDLE_BOOT=1$/m);
+ const um = renderHostUnit("umtool", { ...CTX, port: 3050, memory: { high: 5, max: 6 }, idleBoot: true });
+ assert.doesNotMatch(um, /IDLE_BOOT/);
+});
+
+test("PATH puts a version manager's node first", () => {
+ assert.equal(hostUnitPath("/h", "/usr/bin/node"), "/h/.local/bin:/h/.local/share/pnpm:/usr/local/bin:/usr/bin:/bin");
+ assert.equal(
+ hostUnitPath("/h", "/h/.nvm/versions/node/v22.1.0/bin/node"),
+ "/h/.nvm/versions/node/v22.1.0/bin:/h/.local/bin:/h/.local/share/pnpm:/usr/local/bin:/usr/bin:/bin",
+ );
+});
+
+test("a path with % or $ is spelled so systemd reads it back as written", () => {
+ const got = renderHostUnit("editor", { ...CTX, repoRoot: "/srv/a%b$c", port: 3001, memory: { high: 7, max: 8 } });
+ // WorkingDirectory= expands specifiers but not variables; an Exec line both.
+ assert.ok(got.includes("\nWorkingDirectory=/srv/a%%b$c/editor\n"), got);
+ assert.ok(got.includes("no build in /srv/a%%b$$c/editor/.next"), got);
+});
+
+test("a private site's unit serves its bundle on this machine only", () => {
+ const bundle = "/home/user/archilyzer/export/.export-builds/demo-private/out";
+ const got = renderSiteUnit({ ...CTX, siteId: "demo-private", bundleDir: bundle, port: 8767 });
+ assert.ok(got.includes("\nDescription=Archilyzer site demo-private (127.0.0.1:8767)\n"));
+ assert.ok(got.includes("\nEnvironment=HOST=127.0.0.1\n"));
+ assert.ok(got.includes(`\nExecStart=/usr/bin/node scripts/serve-out.mjs ${bundle} 8767\n`));
+ assert.ok(got.includes("\nWorkingDirectory=/home/user/archilyzer/export\n"));
+ assert.ok(got.includes("pnpm archilyzer publish build demo-private"));
+});
+
+test("docker mode: one unit, compose in the foreground, profiles from the apps, down on stop", () => {
+ const ctx = {
+ repoRoot: "/home/user/archilyzer",
+ home: "/home/user",
+ dockerBin: "/usr/bin/docker",
+ apps: ["editor", "umtool", "ollama"] as const,
+ overlays: ["docker-compose.anthropic.yml"],
+ };
+ assert.deepEqual(composeArgs(ctx), [
+ "compose", "-f", "docker-compose.yml", "-f", "docker-compose.anthropic.yml", "--profile", "umtool", "--profile", "ollama",
+ ]);
+ const got = renderDockerUnit(ctx);
+ const compose =
+ "/usr/bin/docker compose -f docker-compose.yml -f docker-compose.anthropic.yml --profile umtool --profile ollama";
+ assert.ok(got.includes("\nDescription=Archilyzer in Docker (editor, umtool, ollama)\n"));
+ assert.ok(got.includes(`\nExecStart=${compose} up --no-build\n`));
+ assert.ok(got.includes(`\nExecStop=${compose} down\n`));
+ assert.ok(got.includes("\nWorkingDirectory=/home/user/archilyzer\n"));
+ assert.ok(got.includes("\nRestart=on-failure\n"));
+ // Every shell $ in an Exec line is doubled, so systemd hands sh a single one.
+ for (const line of got.split("\n").filter((l) => l.startsWith("ExecStartPre="))) {
+ assert.equal(line.replace(/\$\$/g, "").includes("$"), false, line);
+ }
+ assert.ok(got.includes(`image $$i is not built - build it first (${compose} build)`));
+});
+
+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");
+});
diff --git a/common/lib/service/units.ts b/common/lib/service/units.ts
@@ -0,0 +1,280 @@
+// 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-<id>.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.
+
+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; // <exportBuildsDir>/<id>/out, absolute
+ port: number;
+};
+
+/**
+ * archilyzer-site-<id>.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<DockerUnitContext, "apps" | "overlays">): 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");
+}
+
+/**
+ * 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<number>(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");
+}
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -1757,7 +1757,7 @@ export const siteSettingsSchema = z.object({
"Configured transcription workers (named processing slots). The scheduler distributes each video to the highest-priority free worker. A settings.json predating this field is migrated to a single enabled worker from the active app (see defaultWorkersFromApps). See common/lib/workers.ts.",
),
cookiesFromBrowser: settingsField((v): string => (typeof v === "string" ? v.trim() : "")).describe(
- "Browser spec (e.g. \"firefox\", \"chrome:Default\") passed to `yt-dlp --cookies-from-browser`. WHEN it is passed is governed by `cookieMode` below. Empty string = no cookies configured. Per-channel override available (ChannelConfig.cookiesFromBrowser).",
+ "Browser spec (e.g. \"firefox\", \"chrome:Default\", \"firefox:/data/browser/firefox\" for a profile directory) passed to `yt-dlp --cookies-from-browser` — or `file:<path>`, a cookies.txt passed as `--cookies <path>` (for a container or a server with no browser). WHEN it is passed is governed by `cookieMode` below. Empty string = no cookies configured. Per-channel override available (ChannelConfig.cookiesFromBrowser).",
),
cookieMode: settingsField((v): CookieMode => (isCookieMode(v) ? v : DEFAULT_COOKIE_MODE)).describe(
"How yt-dlp invocations use the configured cookies (see common/lib/cookiePolicy.ts): \"always\" passes them on every invocation, \"when-required\" (default; the historical behavior) only to retry an auth/age failure, \"defer\" never in normal runs — auth-gated videos are excluded from batches and collected into the per-channel \"Needs cookies\" bucket for a manual cookie run. Per-channel override available (ChannelConfig.cookieMode).",
diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts
@@ -30,6 +30,7 @@ import { createInterface } from "node:readline";
import type { Readable } from "node:stream";
import { execa } from "execa";
import { getPaths } from "../lib/paths";
+import { cookieArgs } from "../lib/cookiePolicy";
import type { Post } from "../lib/posts";
import type { OlderBackfillPosition } from "../lib/posts-server";
import { normalizeXTweet, xCreatedAt, type XTweetRaw } from "./xNormalize";
@@ -202,9 +203,9 @@ function galleryDlPacingArgs(): string[] {
// When none are configured we simply run as a guest rather than failing.
function galleryDlLoginArgs(opts: GalleryDlLoginAndCap): string[] {
if (opts.cookieFile) return ["--cookies", opts.cookieFile];
- // Same browser-cookie spec yt-dlp uses (cookiePolicy.ts), same syntax.
- if (opts.cookies) return ["--cookies-from-browser", opts.cookies];
- return [];
+ // Same browser-cookie spec yt-dlp uses (cookiePolicy.ts), same syntax —
+ // `file:<path>` included, which is `--cookies <path>`.
+ return cookieArgs(opts.cookies);
}
// The random gap a post capture waits before each contact with X after its