Archilyzer · Source

archilyzer

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

commit c8924207e623e26416db1bf8f7754ae133735e8d
parent 67a6bda98e7976a855787b66c4747b9a6e921ad3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 18:50:51 -0400

Merge r32/services: Docker is the first-class install with feature parity (runtime-umtool image with ImageMagick+Pango, chromium, hyperframes; gallery-dl, chromium, espeak-ng in the editor image; an ollama profile; Claude key and Firefox cookie overlays; storage overlay; the image build fixed since release 21) and archilyzer service install|status|logs|restart|uninstall for docker or host user units; First steps on an empty editor; RUNNING_IN_DOCKER.md rewritten with the feature table

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

# Conflicts:
#	plans/FACTS.md

Diffstat:
M.env.example | 17+++++++++++++++++
M.gitignore | 3+++
MAGENTS.md | 11++++++++---
MCHANNEL.md | 2+-
MCOMMANDS.md | 6++++++
MDockerfile | 161++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
MENVIRONMENT.md | 3+++
MRUNNING_IN_DOCKER.md | 308+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
MSETTINGS.md | 2+-
Mcommon/bin/archilyzer.ts | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/service.test.ts | 208+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/service.ts | 727+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/channelConfig.ts | 2+-
Mcommon/lib/cookiePolicy.test.ts | 13+++++++++++++
Mcommon/lib/cookiePolicy.ts | 23+++++++++++++++++++++--
Mcommon/lib/envVars.ts | 3+++
Acommon/lib/service/units.test.ts | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/service/units.ts | 280+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/settingsSchema.ts | 2+-
Mcommon/publish/buildImage.test.ts | 42+++++++++++++++++++++++++++++++++++++++++-
Mcommon/social/xGalleryDlFetcher.ts | 7++++---
Adocker-compose.anthropic.yml | 39+++++++++++++++++++++++++++++++++++++++
Adocker-compose.browser.yml | 45+++++++++++++++++++++++++++++++++++++++++++++
Mdocker-compose.gpu.yml | 19+++++++++++++------
Mdocker-compose.vulkan.yml | 21+++++++++++++--------
Mdocker-compose.yml | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocker/entrypoint.sh | 7++++++-
Meditor/CHANGELOG.md | 3+++
Meditor/app/components/dashboard/DashboardCockpit.tsx | 4++++
Aeditor/app/components/dashboard/FirstRunPanel.tsx | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/page.tsx | 21++++++++++++++++++++-
Mplans/FACTS.md | 36++++++++++++++++++++++++++++++++++++
Aplans/release-32/services.md | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
33 files changed, 2439 insertions(+), 66 deletions(-)

diff --git a/.env.example b/.env.example @@ -167,6 +167,23 @@ #PARAKEET_DEVICE=Vulkan0 # --------------------------------------------------------------------------- +# Local models, the Claude API, browser cookies +# --------------------------------------------------------------------------- +# The digest lanes and generation routed to "local" ask an ollama. Default: the +# `ollama` service (`--profile ollama`), pinned by ARCHILYZER_OLLAMA_TAG. A host's own: +#OLLAMA_URL=http://host.docker.internal:11434 +#ARCHILYZER_OLLAMA_TAG=0.40.5 +# +# The Claude API key file the anthropic overlay mounts (docker-compose.anthropic.yml; +# `archilyzer service install` adds it when the file exists). Never put the key +# itself in this file. +#ARCHILYZER_ANTHROPIC_ENV_FILE=/home/you/.config/archilyzer/anthropic.env +# +# The Firefox profiles the browser overlay mounts read-only, for +# cookiesFromBrowser = firefox:/data/browser/firefox (docker-compose.browser.yml). +#ARCHILYZER_FIREFOX_PROFILES=/home/you/.mozilla/firefox + +# --------------------------------------------------------------------------- # Image # --------------------------------------------------------------------------- #ARCHILYZER_TAG=local diff --git a/.gitignore b/.gitignore @@ -211,3 +211,6 @@ umtool/.next/ # Cost an e2e run's worth of confusing red to find. umtool/.next-*/ umtool/test-results/ + +# `archilyzer service storage-overlay` writes it for THIS machine's drives. +/docker-compose.storage.yml diff --git a/AGENTS.md b/AGENTS.md @@ -203,10 +203,15 @@ is new and is a THIRD Dockerfile — `Dockerfile.build` (the opt-in docker build runner's per-site containers, host only) and `Dockerfile.test` (sharded e2e) are untouched and unrelated. -Three runtime targets share one build: `runtime` (CPU whisper.cpp, the default), +Four runtime targets share one build: `runtime` (CPU whisper.cpp, the default), `runtime-vulkan` (parakeet.cpp on Vulkan — AMD/Intel/NVIDIA, `/dev/dri` passed -through, `docker-compose.vulkan.yml`) and `runtime-cuda` (NVIDIA-only whisper, -`docker-compose.gpu.yml`). `ARCHILYZER_TRANSCRIBER` is baked per target and is +through, `docker-compose.vulkan.yml`), `runtime-cuda` (NVIDIA-only whisper, +`docker-compose.gpu.yml`) and `runtime-umtool` (umtool's own image, on trixie: +ImageMagick 7 + Pango, chromium, hyperframes — report → video in a container). +Docker is the first-class install: RUNNING_IN_DOCKER.md's feature matrix says +what each feature needs there. `archilyzer service install` runs either Docker +or the host apps as systemd user units (`common/bin/service.ts`); on this +machine the operator runs host-mode units, which the command adopts. `ARCHILYZER_TRANSCRIBER` is baked per target and is what makes `docker/entrypoint.sh` seed a parakeet worker and fetch a GGUF rather than a whisper worker and a `.bin`. diff --git a/CHANNEL.md b/CHANNEL.md @@ -42,7 +42,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `fullSweepIntervalMinutes` | config | Full-sweep cadence: a sync upgrades itself to a full sweep when `now - lastFullSweepAt >= fullSweepIntervalMinutes`. Absent = inherit `syncScheduler.fullSweepIntervalMinutes`; 0 = never sweep (every sync is a paged walk); positives clamp to [1, 44640]. | | `skipLiveDownloads` | config | Per-channel override for the global `skipLiveDownloads`. Absent = inherit; false = allow downloading currently-live / upcoming videos. | | `downloadFilter` | config | 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). See [`downloadFilter`](#downloadfilter). | -| `cookiesFromBrowser` | config | Per-channel override of the global cookies-from-browser spec. Trimmed; blank = inherit. | +| `cookiesFromBrowser` | config | Per-channel override of the global cookies-from-browser spec (a browser spec, or `file:<path>` for a cookies.txt). Trimmed; blank = inherit. | | `cookieMode` | config | Per-channel override of the global cookie mode. Absent = inherit. | | `sleepBetweenDownloadsSeconds` | config | Per-channel override for the global pause between downloads. Absent = inherit; 0 = no sleep; floored and capped at 600. | | `audioCheck` | config | Audio-integrity checking for sources that intermittently serve corrupt audio mid-download: the managed downloader periodically validates the in-progress `.part` file and rolls back to the last known-good snapshot on corruption (transcribe handling), and a clip window gets the same final probe, fetched once more when malformed and never kept when malformed twice. ON BY DEFAULT for an Odysee video (`audioCheck: {"enabled": false}` turns it off); the channel's opt-in for any other platform. See [`audioCheck`](#audiocheck). | diff --git a/COMMANDS.md b/COMMANDS.md @@ -80,6 +80,12 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer docs cli` | `[--check]` | write COMMANDS.md from this command table and `pnpm ops --help` | | `archilyzer settings example` | `[--check]` | write settings.json.example + SETTINGS.md from the schema | | `archilyzer tts setup` | `[--engine kokoro\|orpheus\|espeak-ng] [--from <dir>] [--python <py>] [--check]` | install a text-to-speech engine under settings.tts.home/&lt;engine&gt; (default ~/.local/share/archilyzer/tts/&lt;engine&gt;): a python venv with its pinned packages (uv venv --python 3.12 when uv is on PATH, else --python &lt;py&gt; -m venv) — kokoro-onnx for kokoro, onnxruntime and numpy for orpheus — and its model files, downloaded once (kokoro: the kokoro-onnx model-files-v1.0 release; orpheus: the Q8\_0 GGUF and the SNAC decoder from Hugging Face, 3.5 GB) one stream at a time with no retries, verified by size and sha256; --from &lt;dir&gt; takes already-downloaded model files from &lt;dir&gt; instead (hard links where it can, else copies; verified the same way); orpheus's llama-server is not installed here (settings.tts.orpheus.serverBin) but is checked; --check installs nothing, lists what is missing and exits 1 when anything is | +| `archilyzer service install` | `[--mode docker\|host] [--apps <a,b>] [--sites <id>:<port>,…] [--overlays <name,…>\|none] [--bind <host>] [--editor-port <n>] [--umtool-port <n>] [--editor-memory <N>G] [--umtool-memory <N>G] [--idle-boot] [--linger] [--no-start] [--force] [--dry-run]` | install the apps as systemd USER units and start them: docker mode (the default when `docker compose` answers) is ONE unit, archilyzer.service, running `docker compose up` in the foreground with a profile per --apps (editor, umtool, site, homepage, ollama; default editor) and the overlays given or found (anthropic when the key file exists, storage when docker-compose.storage.yml does); host mode is archilyzer-editor.service and archilyzer-umtool.service (node running `next start` from the app dir, -H --bind default 0.0.0.0, ports 3001/3050, MemoryHigh/Max sized from MemTotal) plus archilyzer-site-&lt;id&gt;.service per --sites (a built bundle on 127.0.0.1); each unit refuses to start while its build or image is missing. A unit already installed under the same name is ADOPTED when identical and shown as a diff and refused when not (--force replaces it; a running unit is not restarted); --no-start enables without starting; --linger runs loginctl enable-linger (start at boot with nobody logged in); --dry-run prints the units and commands and writes nothing. Linux and systemd only | +| `archilyzer service status` | | read-only: each installed archilyzer unit's state, enablement and pid; for an app its build id, its port and what / answers; the transcription lane's held state; in docker mode each container | +| `archilyzer service logs` | `[--apps <a,b>] [--lines <n>] [--follow]` | the units' journal (journalctl --user), the last 200 lines by default | +| `archilyzer service restart` | `[--apps <a,b>] [--dry-run]` | restart the installed units (all, or the named apps: editor, umtool, site-&lt;id&gt;, docker) — the editor's running jobs are stopped by its shutdown reaper | +| `archilyzer service uninstall` | `[--mode docker\|host] [--apps <a,b>] [--dry-run]` | stop, disable and remove the units (volumes, builds and the corpus are untouched) | +| `archilyzer service storage-overlay` | `[--corpus <dir>] [--out <file>] [--check] [--dry-run]` | write docker-compose.storage.yml: every storage location's root, and every channel media link or saved-video store link no location covers, bind-mounted into the editor and umtool at the SAME absolute path (the links are absolute); --corpus also mounts a host corpus at /data/transcripts in place of the volume; read off the corpus disk only (no media drive is touched) | | `archilyzer doctor` | `[--json]` | read-only report: node, the checkout, the corpus, settings, every tool, the port block; exit 1 on a failure | | `archilyzer release show` | `[editor\|export]` | latest release, its date, how many bullets wait under \[Unreleased\] | | `archilyzer release cut` | `<editor\|export\|all> <X.Y.Z\|next\|next-minor> [--commit] [--date YYYY-MM-DD]` | \[Unreleased\] -&gt; a dated heading; all = both, one version, two commits | diff --git a/Dockerfile b/Dockerfile @@ -7,8 +7,10 @@ # Dockerfile.test — the sharded playwright e2e route. # Both keep working exactly as they did; nothing here touches them. # -# Three published targets, all built from the same app code: +# Four published targets, all built from the same app code: # runtime CPU whisper.cpp. The default. (docker-compose.yml) +# runtime-umtool umtool + the report → video toolchain (ImageMagick 7 with +# Pango, chromium, hyperframes). (docker-compose.yml, umtool) # runtime-vulkan parakeet.cpp on Vulkan. Any GPU with a Vulkan driver — # AMD/RADV, Intel, NVIDIA. (docker-compose.vulkan.yml) # runtime-cuda whisper.cpp on CUDA. NVIDIA only. (docker-compose.gpu.yml) @@ -260,6 +262,27 @@ COPY mcp/package.json mcp/package.json COPY umtool/report-to-video/package.json umtool/report-to-video/package.json COPY umtool/package.json umtool/package.json +# node-datachannel (the seeder's WebRTC, release 21) installs a PREBUILT binary +# from its GitHub release through prebuild-install, which gives up within +# seconds on a slow asset download (measured: ~11 s for its 3.4 MB from a build +# container) and then falls back to compiling it from source, which fails — +# and with it the whole install. So fetch it first, with no such deadline (node: +# the slim base has no curl), into the cache prebuild-install looks in +# (~/.npm/_prebuilds/<sha512(url)[:6]>-<file>). +# The version is the lockfile's; buildImage.test.ts holds the two equal. +ARG NODE_DATACHANNEL_VERSION=0.32.3 +ARG TARGETARCH=amd64 +RUN set -eux; \ + case "${TARGETARCH}" in amd64) arch=x64 ;; arm64) arch=arm64 ;; *) arch="${TARGETARCH}" ;; esac; \ + v="${NODE_DATACHANNEL_VERSION}"; \ + file="node-datachannel-v${v}-napi-v8-linux-${arch}.tar.gz"; \ + url="https://github.com/murat-dogan/node-datachannel/releases/download/v${v}/${file}"; \ + digest="$(node -e 'process.stdout.write(require("crypto").createHash("sha512").update(process.argv[1]).digest("hex").slice(0,6))' "${url}")"; \ + mkdir -p /root/.npm/_prebuilds; \ + node -e 'const [u, f] = process.argv.slice(1); (async () => { for (let i = 1; i <= 3; i++) { try { const r = await fetch(u); if (!r.ok) throw new Error(`HTTP ${r.status}`); require("fs").writeFileSync(f, Buffer.from(await r.arrayBuffer())); return; } catch (e) { console.error(`attempt ${i}: ${e.message}`); await new Promise((d) => setTimeout(d, 2000 * i)); } } process.exit(1); })()' \ + "${url}" "/root/.npm/_prebuilds/${digest}-${file}"; \ + ls -l /root/.npm/_prebuilds + # `allowBuilds` / `onlyBuiltDependencies` in pnpm-workspace.yaml rebuild the # native modules (lmdb, msgpackr-extract, esbuild) for THIS image's arch. RUN pnpm install --frozen-lockfile @@ -316,12 +339,16 @@ FROM ${RUNTIME_IMAGE} AS runtime-base # binary with its own python — for /usr/local/bin/yt-dlp-from-source, which # runs a yt-dlp SOURCE tree mounted at run time (docker-compose.ytdlp.yml). # pipx (+ python3-venv, which it needs to make a venv): installs git-filter-repo -# below, which the homepage's source mirror runs. +# and gallery-dl below. python3-venv is also what `archilyzer tts setup +# --engine kokoro` makes the Kokoro venv with (no uv in the image). +# espeak-ng: the zero-install text-to-speech engine (common/lib/ttsApps.ts), and +# a voice that works with no model download at all. RUN apt-get update \ && apt-get install -y --no-install-recommends \ ffmpeg aria2 zip unzip tar xz-utils gzip rsync curl ca-certificates git procps \ python3 python3-venv pipx python3-certifi python3-brotli python3-websockets \ python3-mutagen python3-pycryptodome python3-requests \ + espeak-ng \ && rm -rf /var/lib/apt/lists/* # git-filter-repo, PINNED, for `archilyzer source publish` (the homepage's @@ -333,6 +360,14 @@ RUN apt-get update \ RUN PIPX_HOME=/opt/pipx PIPX_BIN_DIR=/usr/local/bin pipx install git-filter-repo==2.47.0 \ && git filter-repo --version +# gallery-dl, PINNED: the X/Twitter post fetcher (fetch-posts, capture-posts, +# the X channels). GALLERY_DL_BIN below names it. A pin, not "latest": a +# gallery-dl that changes its output shape changes what the fetcher parses, and +# that should arrive with a rebuild you chose. common/publish/buildImage.test.ts +# holds every target to the same pin (GALLERY_DL_PIPX_SPEC). +RUN PIPX_HOME=/opt/pipx PIPX_BIN_DIR=/usr/local/bin pipx install gallery-dl==1.32.9 \ + && gallery-dl --version + # yt-dlp as the standalone release binary (it bundles its own python), installed # writable so `yt-dlp -U` works — see YTDLP_AUTO_UPDATE in docker/entrypoint.sh. # A pinned yt-dlp goes stale fast, and a stale yt-dlp is the single most common @@ -386,6 +421,19 @@ COPY --from=build /repo /repo # docker-compose.ytdlp.yml. RUN ln -s /repo/docker/yt-dlp-from-source.sh /usr/local/bin/yt-dlp-from-source +# Playwright's headless Chromium, at the version the workspace pins +# (@playwright/test → playwright-core), and the system libraries it needs +# (--with-deps: apt, per distro — bookworm, trixie and ubuntu 24.04 alike). The +# editor launches it headless for the report PDF/print exports, Bluesky post +# capture, the Nitter and Playwright X fetchers and forum (XenForo) sessions; +# umtool's shoot-page.mjs for post screenshots. A fixed path, so every process +# finds it whatever its HOME. Headed launches ("Connect X account") need a +# display, which a container has not — RUNNING_IN_DOCKER.md, the feature matrix. +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/ms-playwright +RUN cd /repo/editor \ + && ./node_modules/.bin/playwright install --with-deps --only-shell chromium \ + && rm -rf /var/lib/apt/lists/* + # Data lives in volumes, never in the image. See docker-compose.yml. # YTDLP_BIN is the one the app runs; ARCHILYZER_IMAGE_YTDLP is the one this # image ships, so the entrypoint and `archilyzer doctor` can say "override". @@ -397,8 +445,20 @@ ENV NODE_ENV=production \ ARCHILYZER_IMAGE_YTDLP=/usr/local/bin/yt-dlp \ EXPORT_INDEX_DIR=/data/builds/.export-index \ EXPORT_BUILDS_DIR=/data/builds/.export-builds \ - ARCHILYZER_SITE_OUT=/data/builds/site -RUN mkdir -p /data/transcripts /data/config /data/models /data/builds + ARCHILYZER_SITE_OUT=/data/builds/site \ + GALLERY_DL_BIN=/usr/local/bin/gallery-dl \ + REPORTS_DIR=/data/reports +RUN mkdir -p /data/transcripts /data/config /data/models /data/builds /data/reports +# Three things paths.ts keeps beside the checkout or in $HOME, which is the +# container's writable layer and gone on every recreate: the text-to-speech +# engines (~/.local/share/archilyzer/tts), their synthesis cache (/repo/.tts) +# and the generation ledger the daily caps count (/repo/.generation). Linked into +# the volumes, so a Kokoro installed once (`archilyzer tts setup`) and today's +# spend both survive `docker compose up`. +RUN mkdir -p /root/.local/share/archilyzer \ + && ln -s /data/models/tts /root/.local/share/archilyzer/tts \ + && rm -rf /repo/.tts && ln -s /data/builds/tts /repo/.tts \ + && rm -rf /repo/.generation && ln -s /data/config/generation /repo/.generation ENTRYPOINT ["/repo/docker/entrypoint.sh"] CMD ["editor"] @@ -422,6 +482,81 @@ ENV ARCHILYZER_COMMIT=${ARCHILYZER_COMMIT} \ ARCHILYZER_BRANCH=${ARCHILYZER_BRANCH} # --------------------------------------------------------------------------- +# runtime-umtool — umtool with everything report → video needs. The `umtool` +# service (docker-compose.yml) runs this target; the editor's image stays lean. +# +# Built on TRIXIE (compose passes RUNTIME_IMAGE=node:22-trixie-slim for it, as +# the Vulkan overlay does for the editor): the renderer calls ImageMagick 7's +# `magick`, and bookworm ships ImageMagick 6 (`convert`, no `magick`). The +# workspace is still built on bookworm — glibc only goes forward (top of file). +# +# What a render shells out to, and why each is here: +# magick + the "extra" coders cards, the timeline, every `pango:` text +# render (the Pango coder is in +# libmagickcore-…-extra, a Recommends that +# --no-install-recommends would drop) +# rsvg-convert (librsvg2-bin) the brand preset's SVG cards +# qrencode / zbarimg the QR codes, and their verification +# chromium compose-chrome's review still (CHROME) +# hyperframes + its headless the chrome frames (deck, posts, teaser): +# shell HYPERFRAMES_BIN, so a render never runs +# `npx --yes` against the registry +# Playwright's headless shell shoot-page.mjs (post screenshots) — +# installed in runtime-base, the editor +# uses it too +# fonts DejaVu as the fallback face, Noto emoji; +# the preset's own faces are vendored in +# report-to-video/fonts (FONTCONFIG_FILE) +# Fira Sans (the unbranded cards' face) is not packaged by Debian; an +# unbranded card falls back to DejaVu Sans here. The Archilyzer Media preset is +# unaffected — its faces ship in the repo. +# --------------------------------------------------------------------------- +FROM runtime-base AS runtime-umtool +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + imagemagick libmagickcore-7.q16-10-extra librsvg2-bin qrencode zbar-tools \ + chromium fontconfig fonts-dejavu-core fonts-noto-color-emoji \ + && rm -rf /var/lib/apt/lists/* +# Debian's ImageMagick security policy forbids reading a file through `@` +# (`pango:@card.pango`, which is how every text card is drawn — measured: "not +# allowed by the security policy") and caps memory at 256 MiB. The renderer +# feeds ImageMagick only files it wrote itself, so the image runs ImageMagick's +# own open policy: no rules. +RUN for f in /etc/ImageMagick-7/policy.xml /etc/ImageMagick-6/policy.xml; do \ + [ -f "$f" ] && printf '<policymap>\n <!-- the umtool image: renders its own files only; see the Dockerfile -->\n</policymap>\n' > "$f"; \ + done; true +# Fail the build, not the first render, when the Pango coder is missing or a +# card cannot be drawn from its markup file. +RUN set -eux; \ + magick -version | head -n 1; \ + magick -list format | grep -qi 'pango' || { echo "FATAL: ImageMagick has no Pango coder" >&2; exit 1; }; \ + printf '<span font="DejaVu Sans 40">ok</span>' > /tmp/card.pango; \ + magick -background none -size 400x pango:@/tmp/card.pango /tmp/card.png; \ + rm -f /tmp/card.pango /tmp/card.png; \ + rsvg-convert --version; qrencode --version 2>&1 | head -n 1; zbarimg --version; \ + chromium --version +# The hyperframes CLI, PINNED to the version deck.mjs names +# (HYPERFRAMES_PKG_DEFAULT; the drift test holds the two equal), and the +# chrome-headless-shell it renders with, fetched once here into root's cache. +# Its usage telemetry is off: DO_NOT_TRACK (which it honours) for every run, +# and its own switch, written once. +ARG HYPERFRAMES_VERSION=0.8.24 +ENV DO_NOT_TRACK=1 +RUN set -eux; \ + npm install -g "hyperframes@${HYPERFRAMES_VERSION}"; \ + hyperframes --version; \ + hyperframes telemetry disable; \ + hyperframes browser ensure +ENV HYPERFRAMES_BIN=/usr/local/bin/hyperframes \ + CHROME=/usr/bin/chromium +CMD ["umtool"] + +ARG ARCHILYZER_COMMIT= +ARG ARCHILYZER_BRANCH= +ENV ARCHILYZER_COMMIT=${ARCHILYZER_COMMIT} \ + ARCHILYZER_BRANCH=${ARCHILYZER_BRANCH} + +# --------------------------------------------------------------------------- # runtime-vulkan — parakeet.cpp on any Vulkan GPU. docker-compose.vulkan.yml. # # Ships whisper-cli too: the GPU is for parakeet, but a CPU whisper worker is a @@ -471,11 +606,14 @@ RUN apt-get update \ ffmpeg aria2 zip unzip tar xz-utils gzip rsync curl ca-certificates git gnupg procps \ python3 python3-venv pipx python3-certifi python3-brotli python3-websockets \ python3-mutagen python3-pycryptodome python3-requests \ + espeak-ng \ && curl -fsSL "https://deb.nodesource.com/setup_${NODE_MAJOR}.x" | bash - \ && apt-get install -y --no-install-recommends nodejs \ && rm -rf /var/lib/apt/lists/* RUN PIPX_HOME=/opt/pipx PIPX_BIN_DIR=/usr/local/bin pipx install git-filter-repo==2.47.0 \ && git filter-repo --version +RUN PIPX_HOME=/opt/pipx PIPX_BIN_DIR=/usr/local/bin pipx install gallery-dl==1.32.9 \ + && gallery-dl --version ARG TARGETARCH=amd64 RUN set -eux; \ @@ -521,6 +659,11 @@ RUN ldconfig WORKDIR /repo COPY --from=build /repo /repo RUN ln -s /repo/docker/yt-dlp-from-source.sh /usr/local/bin/yt-dlp-from-source +# Playwright's headless Chromium, as in runtime-base (read its comment). +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/ms-playwright +RUN cd /repo/editor \ + && ./node_modules/.bin/playwright install --with-deps --only-shell chromium \ + && rm -rf /var/lib/apt/lists/* ENV NODE_ENV=production \ NEXT_TELEMETRY_DISABLED=1 \ @@ -533,8 +676,14 @@ ENV NODE_ENV=production \ ARCHILYZER_IMAGE_YTDLP=/usr/local/bin/yt-dlp \ EXPORT_INDEX_DIR=/data/builds/.export-index \ EXPORT_BUILDS_DIR=/data/builds/.export-builds \ - ARCHILYZER_SITE_OUT=/data/builds/site -RUN mkdir -p /data/transcripts /data/config /data/models /data/builds + ARCHILYZER_SITE_OUT=/data/builds/site \ + GALLERY_DL_BIN=/usr/local/bin/gallery-dl \ + REPORTS_DIR=/data/reports +RUN mkdir -p /data/transcripts /data/config /data/models /data/builds /data/reports +RUN mkdir -p /root/.local/share/archilyzer \ + && ln -s /data/models/tts /root/.local/share/archilyzer/tts \ + && rm -rf /repo/.tts && ln -s /data/builds/tts /repo/.tts \ + && rm -rf /repo/.generation && ln -s /data/config/generation /repo/.generation ENTRYPOINT ["/repo/docker/entrypoint.sh"] CMD ["editor"] diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -186,6 +186,9 @@ The container's own set, read by `docker/*.sh`, the compose files and Caddy — | `ARCHILYZER_FORWARD_AUTH_UPSTREAM` | — | Forward-auth server (Authelia, tinyauth, …), `host:port`. | docker/Caddyfile | | `ARCHILYZER_FORWARD_AUTH_URI` | `/api/auth/caddy` | The forward-auth server's verify path. | docker/Caddyfile | | `ARCHILYZER_TAG` | `local` | The image tag the compose files build and run. | docker-compose*.yml | +| `ARCHILYZER_ANTHROPIC_ENV_FILE` | `~/.config/archilyzer/anthropic.env` | The host's Claude API key file (one line `ANTHROPIC_API_KEY=…`, mode 600), bind-mounted read-only into the editor and umtool by the anthropic overlay; `archilyzer service install` adds that overlay when the file exists (it never opens it). | docker-compose.anthropic.yml, common/bin/service.ts | +| `ARCHILYZER_FIREFOX_PROFILES` | `~/.mozilla/firefox` | The host's Firefox profiles directory, mounted read-only at `/data/browser/firefox` by the browser overlay, for `cookiesFromBrowser = firefox:/data/browser/firefox`. | docker-compose.browser.yml | +| `ARCHILYZER_OLLAMA_TAG` | `0.40.5` | The `ollama/ollama` image tag the `ollama` profile runs. | docker-compose.yml | ## Tests only diff --git a/RUNNING_IN_DOCKER.md b/RUNNING_IN_DOCKER.md @@ -1,9 +1,12 @@ # Running an archive in Docker -One command stands up a working archive server: the editor, the tools it drives -(yt-dlp, ffmpeg, and a transcription engine — whisper.cpp, or parakeet.cpp in the -Vulkan image), and a reverse proxy that is the only thing on the box with an open -port. +Docker is the first-class way to run Archilyzer: every feature works in it (the +[feature matrix](#every-feature-by-install) says which need an overlay, and the +few that need a desktop). One command stands up a working archive server: the +editor, the tools it drives (yt-dlp, gallery-dl, ffmpeg, and a transcription +engine — whisper.cpp, or parakeet.cpp in the Vulkan image), and a reverse proxy +that is the only thing on the box with an open port. umtool, a local model +server and the published site are one profile each. > This document is about **running the apps** — publishing included: every publish > stage (index, build, deploy) runs inside the editor's container. Fanning per-site @@ -16,6 +19,8 @@ port. ## Quickstart +From a clone to a transcribed channel: + ```sh git clone <your-remote> archilyzer cd archilyzer @@ -23,10 +28,20 @@ cp .env.example .env docker compose up -d --build ``` -Then open **http://localhost:8081**. - -The first build takes a while — it compiles whisper.cpp and builds two Next.js -apps. Afterwards, `docker compose up -d` is seconds. +1. Open **http://localhost:8081**. With no channel yet, the dashboard's **First + steps** lists what this install has and what it lacks. +2. **Paste a URL** (Channels → Add): a channel or playlist. Platform, handling + and slug fill in. +3. On the channel's page, **Sync**: captions and audio land in the `corpus` + volume. +4. **Transcribe** the videos that have no captions — the seeded worker and the + model fetched on first boot do it. + +The first build takes a while — it compiles whisper.cpp and builds three Next.js +apps. Afterwards, `docker compose up -d` is seconds. To start it at boot, enable +Docker itself (`sudo systemctl enable --now docker`): every service is +`restart: unless-stopped`, so the stack comes back with the daemon. Or install it +as a unit — [Run it as a service](#run-it-as-a-service). On first boot the container also: @@ -50,16 +65,65 @@ Watch it happen with `docker compose logs -f editor`. | **editor** | http://localhost:8081 | the admin app: channels, downloads, transcription, builds | | site | http://localhost:8080 | the published archive (profile `site`) | | homepage | http://localhost:8082 | the project's own site (profile `homepage`) | -| umtool | http://localhost:8083 | the clip/report bench (profile `umtool`) | +| umtool | http://localhost:8083 | the clip/report bench and report → video renders (profile `umtool`, its own image) | +| ollama | — (internal) | local models for digests and local generation (profile `ollama`) | Only the editor and Caddy run by default. Somebody who wants an archive runs two containers, not five: ```sh docker compose --profile site up -d # + the archive server -docker compose --profile umtool up -d # + umtool +docker compose --profile umtool up -d --build # + umtool (builds its image once) +docker compose --profile ollama up -d # + a local model server +``` + +### Run it as a service + +`archilyzer service` installs the stack as systemd **user** units and starts it +(Linux; it needs Node 22 and pnpm on the host to run the command itself — a +checkout with `pnpm install`): + +```sh +pnpm archilyzer service install --dry-run # see the unit first +pnpm archilyzer service install --apps editor,umtool,ollama --linger +pnpm archilyzer service status +pnpm archilyzer service logs --follow +pnpm archilyzer service restart +pnpm archilyzer service uninstall # volumes untouched ``` +**Docker mode** (the default when `docker compose` answers) is ONE unit, +`archilyzer.service`, running `docker compose … up` in the foreground — so every +container's log is in the journal — and `docker compose … down` on stop. `--apps` +picks the profiles (`editor`, `umtool`, `site`, `homepage`, `ollama`); the +overlays come from `--overlays vulkan,browser,…` or are found: +`docker-compose.anthropic.yml` when the Claude API key file exists, +`docker-compose.storage.yml` when you have generated one. The unit never builds: +an image that was never built is refused at start with the `docker compose build` +line to run. Compose's own restart policy does the container restarts; the unit +adds start/stop, status and logs through systemd, and `--linger` +(`loginctl enable-linger`) starts it at boot with nobody logged in. A user unit, +not a system one: nothing needs root to install it, and it runs as the person +whose checkout and `.env` it reads. + +**Host mode** (`--mode host`; the default once host units exist) is one unit per +app: `archilyzer-editor.service` and `archilyzer-umtool.service` run +`node … next start` from the app's directory (node directly — pnpm swallows the +SIGTERM the editor's shutdown reaper needs), ports 3001 and 3050, bound to +`--bind` (default `0.0.0.0`, as `next start` itself; the editor has no login, so +pass `--bind 127.0.0.1` on a machine others can reach), `MemoryHigh`/`MemoryMax` +sized from the machine's RAM (`--editor-memory 8G`), `KillMode=mixed` with time +for the reaper, and a start that refuses with a sentence while `.next/BUILD_ID` +is missing. `--sites <id>:<port>` adds `archilyzer-site-<id>.service`, a built +private site's bundle served on 127.0.0.1. `--idle-boot` boots the editor +without arming its runners. + +Installing over units that already exist ADOPTS them: identical text is left +alone; a different one is printed as a diff and refused unless `--force`. A unit +replaced while it runs keeps running until `service restart`. `--dry-run` prints +every unit and every command and writes nothing. Every flag is in +[COMMANDS.md](COMMANDS.md). + --- ## The exposure model @@ -376,6 +440,135 @@ override alone with a warning — update it where you build it. A substitute tha does not run is reported as `yt-dlp: MISSING — … does not run: …` (the editor still starts), and by `archilyzer doctor`. +### Report → video (umtool) + +```sh +docker compose --profile umtool up -d --build +``` + +umtool runs its own image, the `runtime-umtool` target: everything a render +shells out to is in it — ImageMagick 7 with the Pango coder (cards, the +timeline, every text render), `rsvg-convert`, `qrencode` and `zbarimg`, +`chromium` for the review still, the pinned `hyperframes` CLI and its headless +shell for the chrome frames (`HYPERFRAMES_BIN`, so a render never runs +`npx --yes`), and Playwright's headless Chromium for post screenshots. It is +built on trixie because bookworm has no ImageMagick 7. The Archilyzer Media +preset's faces ship in the repo; an unbranded card falls back from Fira Sans +(not packaged by Debian) to DejaVu Sans. + +Projects live in the `reports` volume (`REPORTS_DIR=/data/reports`). Clip +windows are fetched through the editor (`ARCHILYZER_EDITOR_URL=http://editor:3001` +is set for you; `WORKER_TOKEN` in `.env` is what it authenticates with). A render +runs inside the umtool container; give the Docker VM the memory a render needs +(4 GB or more on Docker Desktop). + +### Local models + +```sh +docker compose --profile ollama up -d +docker compose exec ollama ollama pull qwen3:8b +``` + +The digest lanes and generation routed to **local** reach `OLLAMA_URL`, which +compose points at the `ollama` service (`http://ollama:11434`, internal — no port +is published). The Vulkan and GPU overlays give it the same device as the +editor (ollama's Vulkan backend is opt-in upstream — the overlay sets +`OLLAMA_VULKAN=1`; check `docker compose logs ollama` for the device it found). +To use an ollama already running on the host instead: + +```sh +# .env +OLLAMA_URL=http://host.docker.internal:11434 +``` + +(`host.docker.internal` resolves on Linux too — compose maps it for the editor +and umtool. The host's ollama must listen beyond loopback for a container to +reach it: `OLLAMA_HOST=0.0.0.0`.) + +### The Claude API + +Frame scan and generation routed to **api** read the same one-line key file a +host install does (`ANTHROPIC_API_KEY=…`, mode 600, default +`~/.config/archilyzer/anthropic.env`). The overlay mounts it read-only where the +app looks by default, so no setting changes: + +```sh +docker compose -f docker-compose.yml -f docker-compose.anthropic.yml up -d +``` + +A mount, not an environment variable: the key never shows in +`docker compose config`, `docker inspect` or `.env`. Without the overlay those +features say "no API key"; nothing else needs it. `ARCHILYZER_ANTHROPIC_ENV_FILE` +names another file. Generation routed to **code** is done by a Claude Code +session through the MCP (`/gen`), not by the container — register the MCP from +the container ([below](#the-mcp-server-from-the-container)). + +### Browser cookies + +yt-dlp's `--cookies-from-browser` (Settings → cookies, a channel's own value, +`cookieMode`) and gallery-dl's read a browser's cookie store, and a container has +no browser. Mount the host's Firefox profiles read-only: + +```sh +docker compose -f docker-compose.yml -f docker-compose.browser.yml up -d +``` + +and set **cookiesFromBrowser** to `firefox:/data/browser/firefox` (the newest +profile under it; `firefox:/data/browser/firefox/<xxxx.default-release>` pins +one). yt-dlp copies the database before reading it, so Firefox may stay open. + +| Browser | From a container | Works for | +|---|---|---| +| Firefox | the browser overlay | YouTube, Rumble (`cf_clearance`; the app pins the User-Agent it was issued to), Odysee, X through gallery-dl | +| Chrome / Chromium | **no** — their Linux cookies are encrypted with a key the desktop keyring holds | export a `cookies.txt` (Netscape format) instead | + +A `cookies.txt` works anywhere: copy it into the config volume and name it with +`file:`, which the app passes as `--cookies <path>`: + +```sh +docker compose cp cookies.txt editor:/data/config/cookies.txt +# Settings → cookiesFromBrowser: file:/data/config/cookies.txt +``` + +It goes stale as the site rotates its cookies; re-export when fetches start +asking for a login. `ARCHILYZER_FIREFOX_PROFILES` in `.env` names a profiles +directory that is not `~/.mozilla/firefox` (a snap's or a flatpak's). + +### X posts + +gallery-dl is in the image (pinned; `GALLERY_DL_BIN`), and so is the headless +Chromium the post capture and the Nitter fallback use. **Connect X account** and +**Connect forum session** open a browser window for you to log in, and a +container has no display: log in to X in the host's Firefox and use the browser +overlay above (the X fetchers read the same store), or connect on a host install. + +### Text to speech + +`espeak-ng` is in the image, so `pnpm ops tts` speaks with no model at all. +Kokoro (the default engine) installs into the container on demand: + +```sh +docker compose exec editor pnpm archilyzer tts setup --engine kokoro +``` + +It lands in the `models` volume (the image links +`~/.local/share/archilyzer/tts` there), so it survives `docker compose up`. +Orpheus needs a `llama-server` beside the editor, which the image does not carry +— run Orpheus on a host install. + +### The MCP server, from the container + +```sh +claude mcp add archilyzer -- docker compose -f /path/to/archilyzer/docker-compose.yml \ + exec -T editor pnpm --silent archilyzer mcp +``` + +`-T` (no TTY) and `--silent` keep stdout to the JSON-RPC protocol alone. Inside +the container `ARCHILYZER_EDITOR_URL` already names the editor, so `fetch_clip` +works once `WORKER_TOKEN` is set in `.env`. Point it at a published archive +with `exec -T -e TRANSCRIPT_SITE_URL=https://… editor …`, or at a local build +with `-e TRANSCRIPT_LOCAL_DIR=/data/builds/.export-builds/<site-id>/out`. + ### Driving the editor without a browser Every editor gesture is a server action, which is fine for a person and hostile @@ -596,8 +789,10 @@ reachable from a Linux container at all, so it would have to be a host install. ### Backup `corpus` is the volume that matters — real media, real transcripts, hundreds of -GB when it grows up. `config` holds `settings.json`. `models` and `builds` are -reproducible; losing them costs a download and a rebuild. +GB when it grows up. `config` holds `settings.json` and the generation ledger; +`reports` holds umtool's projects — real work, back it up too. `models`, +`builds` and `ollama` are reproducible; losing them costs a download and a +rebuild. ```sh docker run --rm -v archilyzer_corpus:/corpus -v "$PWD:/backup" \ @@ -606,10 +801,28 @@ docker run --rm -v archilyzer_corpus:/corpus -v "$PWD:/backup" \ ### A channel whose media is on another drive -The Storage panel can move a channel's `data/` to another root (see AGENTS.md). In a -container that root is a path **inside the container**, and `channels/<slug>/data` -becomes an absolute symlink to it — so the drive must be bind-mounted **at the same -absolute path the editor recorded**: +The Storage panel can move a channel's media to another drive (see AGENTS.md): +`channels/<slug>/media` becomes ONE absolute symlink to `<root>/<slug>/media`. In +a container that root is a path **inside the container**, so the drive must be +bind-mounted **at the same absolute path the corpus's links name**. Generate the +overlay from the configured storage locations and the links themselves: + +```sh +pnpm archilyzer service storage-overlay # writes docker-compose.storage.yml +pnpm archilyzer service storage-overlay --dry-run # prints it +docker compose -f docker-compose.yml -f docker-compose.storage.yml up -d +``` + +It lists every location's root, every channel `media` link (and a legacy `data` +link) whose target no location covers, and the saved-video store when it is a +link — read off the corpus disk with `readlink`, so an unmounted drive cannot +stall it. Each is mounted into the editor and umtool with `create_host_path: +false`: a drive that is not mounted on the host refuses `up` rather than +becoming an empty directory the corpus would read as no media. `--corpus <dir>` +also mounts a host corpus at `/data/transcripts` in place of the volume — the +path from a host install to Docker without copying it. `archilyzer service +install` adds the overlay by itself once the file exists; re-run the command +after adding a location or moving a channel. By hand it is one line per drive: ```yaml services: @@ -655,7 +868,7 @@ mount; fix the path. So the container's remedy is the manual one, and it is not a downgrade: **change the location's root to the path the media is actually at, and re-point.** Edit the location on `/storage`, or press Re-point after correcting the root; the job rewrites each -channel's `data/` symlink and its `config.dataDir` and moves no bytes. Equivalently, +channel's `media` link and its `config.mediaDir` and moves no bytes. Equivalently, fix the compose file so the bind mount lands where the editor recorded — the same `-v /host/path:/container/path` line above — and nothing needs re-pointing at all. `autoRepoint` has nothing to act on here and can stay off. @@ -675,6 +888,40 @@ docker compose down # stop; volumes survive docker compose down -v # stop AND DELETE the corpus ``` +## Every feature, by install + +**works** — nothing to add. *needs X* — one step, named. **no** — not +supported there, and why. The three Docker columns are the default image, the +Vulkan overlay and the CUDA overlay; umtool runs its own image in all three. + +| Feature | Host install | Docker CPU | Docker Vulkan | Docker CUDA | +|---|---|---|---|---| +| Channels: add, sync, download (yt-dlp + deno) | works | works | works | works | +| Imports: archive.org (torrents via aria2), Odysee, BitChute, the Wayback Machine | works | works | works | works | +| The Odysee audio check, audio audit, find-copy, mirrors | works | works | works | works | +| Cookies from a browser | works (any browser yt-dlp reads) | Firefox: *needs the browser overlay*; Chrome: *needs a cookies.txt* (`file:`) — [Browser cookies](#browser-cookies) | same | same | +| X posts: fetch and capture (gallery-dl) | *needs gallery-dl* | works (pinned in the image) | works | works | +| Bluesky capture, the Nitter and Playwright X fetchers, forum threads (headless Chromium) | *needs `playwright install chromium`* | works | works | works | +| Connect X account / Connect forum session (a browser window) | works | **no** — a container has no display; use the browser overlay's Firefox login | **no** | **no** | +| Transcription, whisper.cpp on the CPU | *needs whisper.cpp* | works | works (whisper-cli is in it too) | works | +| Transcription on a GPU | *needs a GPU build* | **no** — CPU image | works: parakeet.cpp on Vulkan (AMD, Intel, NVIDIA) | works: whisper.cpp on CUDA (NVIDIA) | +| Diarization (sherpa-onnx, Sortformer) | *needs the engine's python env* | **no** — not baked (an engine and models the operator chooses); run it on a host or a [unit executor](#running-as-a-unit-executor-for-another-machine) | **no** | **no** | +| Digests, attribution, generation routed to **local** | *needs ollama* | *needs `--profile ollama`* (or the host's ollama) | same, on the GPU (`OLLAMA_VULKAN=1`) | same, on the GPU | +| Frame scan, generation routed to **api** (Claude API) | *needs the key file* | *needs the anthropic overlay* | same | same | +| Generation routed to **code** (`/gen` in Claude Code) | works (MCP) | works ([MCP from the container](#the-mcp-server-from-the-container)) | works | works | +| Curated tags, reports prepare/export, articles, PDF/print exports | works | works | works | works | +| Report → video renders | *needs ImageMagick 7 + Pango, qrencode, rsvg-convert, chromium* | *needs `--profile umtool`* (its image has all of it) | same | same | +| Text to speech: espeak-ng | *needs espeak-ng* | works | works | works | +| Text to speech: Kokoro | *needs `tts setup`* | *needs `tts setup`* in the container (kept in the models volume) | same | same | +| Text to speech: Orpheus | *needs `tts setup --engine orpheus` + a llama-server* | **no** — no llama-server in the image | **no** | **no** | +| Publish: index, build, deploy (local, Cloudflare) | works | works (token in `.env`) | works | works | +| Publish: the docker runner's per-site fan-out | works | **no** — no engine in a container, by design | **no** | **no** | +| The homepage's `/source` mirror | works | *needs the source overlay*; no gitleaks/stagit (no secret scan, no history pages) | same | same | +| The seeder (WebTorrent behind WireGuard) | works (`archilyzer seed`) | *needs the seeder overlay* | same | same | +| Media on other drives | works (UUID re-point) | *needs the storage overlay*; re-point by path only | same | same | +| The MCP server | works | works (`exec -T`) | works | works | +| Run as a service | `service install --mode host` | `service install` (or Docker's own restart) | same, `--overlays vulkan` | same, `--overlays gpu` | + --- ## What is in the image, and what is not @@ -682,34 +929,33 @@ docker compose down -v # stop AND DELETE the corp **Baked in:** Node 22 (the pinned wrangler needs it) + the installed workspace, the built editor / umtool / homepage, `yt-dlp`, a JavaScript runtime for it (`deno` — without one yt-dlp warns and silently loses formats), `ffmpeg`/`ffprobe`, `whisper-cli` (statically linked), +`gallery-dl` (pinned), Playwright's headless Chromium, `espeak-ng`, `aria2`, `zip`/`tar`/`xz`/`gzip`, `rsync`, `git`, `curl`, `ps`; `python3` with yt-dlp's -optional modules (for a substituted yt-dlp), `pipx` and a pinned `git-filter-repo` -(the homepage's source mirror), and — in the workspace's `node_modules` — a -pinned `wrangler`, so a deploy fetches nothing. The Vulkan image adds -`parakeet-cli`, the Mesa Vulkan drivers and `vulkaninfo`. +optional modules (for a substituted yt-dlp) and `venv` (for a Kokoro install), +`pipx` and a pinned `git-filter-repo` (the homepage's source mirror), and — in +the workspace's `node_modules` — a pinned `wrangler`, so a deploy fetches +nothing. The Vulkan image adds `parakeet-cli`, the Mesa Vulkan drivers and +`vulkaninfo`. The umtool image (`runtime-umtool`) adds ImageMagick 7 with Pango, +`rsvg-convert`, `qrencode`, `zbarimg`, `chromium` and the pinned `hyperframes` +with its headless shell. Local models are the `ollama` service's own image. **Not baked, on purpose:** - **The corpus.** It is a separate git repo holding production data, and it lives in the `corpus` volume. -- **whisper models.** 142 MB to 3 GB, and the choice is yours. Fetched on boot. +- **Speech models.** 142 MB to 3 GB, and the choice is yours. Fetched on boot. - **The export site build.** It is a static render *of a corpus*, and there is no corpus at image-build time. The publish stages make it at run time. - **Credentials.** `CLOUDFLARE_API_TOKEN` and friends come from `.env` at run - time, never from the image. + time; the Claude API key file is mounted by its overlay. Never in the image. - **The repository.** No `.git`; `docker-compose.source.yml` mounts the host's for the `/source` mirror. The build's commit and branch are baked as `ARCHILYZER_COMMIT`/`ARCHILYZER_BRANCH` when the build passes them (`ARCHILYZER_COMMIT=$(git rev-parse HEAD) ARCHILYZER_BRANCH=$(git branch --show-current) docker compose build`) — the publish stamps record them. -- **ImageMagick with Pango, and `qrencode`.** Only `umtool/report-to-video/` - needs them, and rendering a report to video is a workstation task, not - something a server does. Run that part on a host checkout. -- **gallery-dl.** The X/Twitter post fetcher. Install it and point - `GALLERY_DL_BIN` at it if you want the social corpus. -- **ollama / claude.** The digest lanes reach a local ollama or the `claude` CLI. - Point `OLLAMA_URL` at a host ollama (`http://host.docker.internal:11434`) if you - want digests. +- **Diarization engines and Orpheus's llama-server.** Each is an engine plus + models the operator chooses, GPU-specific; the matrix above says where they + run. ### Two build runners, and the container has one diff --git a/SETTINGS.md b/SETTINGS.md @@ -156,7 +156,7 @@ Default: ## `cookiesFromBrowser` -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). Default: `""` 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,208 @@ +// `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-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,727 @@ +// `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; + // The login name linger is about. + user: 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, + user: os.userInfo().username, + 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 = deps.user; + 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/envVars.ts b/common/lib/envVars.ts @@ -188,6 +188,9 @@ const DECLARED: EnvVarDecl[] = [ { name: "ARCHILYZER_FORWARD_AUTH_UPSTREAM", audience: "docker", default: "—", readBy: "docker/Caddyfile", doc: "Forward-auth server (Authelia, tinyauth, …), `host:port`." }, { name: "ARCHILYZER_FORWARD_AUTH_URI", audience: "docker", default: "`/api/auth/caddy`", readBy: "docker/Caddyfile", doc: "The forward-auth server's verify path." }, { name: "ARCHILYZER_TAG", audience: "docker", default: "`local`", readBy: "docker-compose*.yml", doc: "The image tag the compose files build and run." }, + { name: "ARCHILYZER_ANTHROPIC_ENV_FILE", audience: "docker", default: "`~/.config/archilyzer/anthropic.env`", readBy: "docker-compose.anthropic.yml, common/bin/service.ts", doc: "The host's Claude API key file (one line `ANTHROPIC_API_KEY=…`, mode 600), bind-mounted read-only into the editor and umtool by the anthropic overlay; `archilyzer service install` adds that overlay when the file exists (it never opens it)." }, + { name: "ARCHILYZER_FIREFOX_PROFILES", audience: "docker", default: "`~/.mozilla/firefox`", readBy: "docker-compose.browser.yml", doc: "The host's Firefox profiles directory, mounted read-only at `/data/browser/firefox` by the browser overlay, for `cookiesFromBrowser = firefox:/data/browser/firefox`." }, + { name: "ARCHILYZER_OLLAMA_TAG", audience: "docker", default: "`0.40.5`", readBy: "docker-compose.yml", doc: "The `ollama/ollama` image tag the `ollama` profile runs." }, // ── test: harnesses, fakes and test-mode branches ────────────────────── { name: "E2E_TEST_ROUTES", audience: "test", default: "off", readBy: "editor/app/api/test/_guard.ts, editor/instrumentation.ts", doc: "`1` opens the editor's `/api/test/*` routes and marks a test server at boot. Set by `editor/playwright.config.ts` on its test server, and by nothing else." }, 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/publish/buildImage.test.ts b/common/publish/buildImage.test.ts @@ -100,7 +100,7 @@ test("build-site.sh's asset sync ships a changed svg, drops a removed one, and t // nobody asked for, or a mirror rewritten by a version nobody tested. test("the runtime image installs the git-filter-repo that source publish names, in every target", () => { const dockerfile = readFileSync(path.join(REPO, "Dockerfile"), "utf8"); - const installs = [...dockerfile.matchAll(/pipx install (\S+)/g)].map((m) => m[1]); + const installs = [...dockerfile.matchAll(/pipx install (git-filter-repo\S*)/g)].map((m) => m[1]); // runtime-base (runtime + runtime-vulkan) and runtime-cuda, which repeats it. assert.equal(installs.length, 2, `expected two \`pipx install\` lines, found ${installs.length}`); for (const spec of installs) { @@ -112,6 +112,46 @@ test("the runtime image installs the git-filter-repo that source publish names, } }); +// gallery-dl (the X post fetcher) is pinned, and the editor's targets agree on +// the pin: runtime-base (runtime, runtime-vulkan, runtime-umtool) and +// runtime-cuda, which repeats it. GALLERY_DL_BIN names the installed one. +test("every runtime target installs the same pinned gallery-dl and names it in GALLERY_DL_BIN", () => { + const dockerfile = readFileSync(path.join(REPO, "Dockerfile"), "utf8"); + const installs = [...dockerfile.matchAll(/pipx install (gallery-dl\S*)/g)].map((m) => m[1]); + assert.equal(installs.length, 2, `expected two gallery-dl installs, found ${installs.length}`); + assert.match(installs[0], /^gallery-dl==\d+\.\d+\.\d+$/, "gallery-dl is pinned to an exact version"); + assert.equal(installs[1], installs[0], "runtime-base and runtime-cuda pin the same gallery-dl"); + const bins = [...dockerfile.matchAll(/^\s+GALLERY_DL_BIN=(\S+)/gm)].map((m) => m[1]); + assert.deepEqual(bins, ["/usr/local/bin/gallery-dl", "/usr/local/bin/gallery-dl"]); +}); + +// The umtool image renders with the hyperframes CLI it installs, never `npx +// --yes` at render time: the pin is the one deck.mjs names, and +// HYPERFRAMES_BIN points at it. +test("the umtool image installs the hyperframes deck.mjs pins and points HYPERFRAMES_BIN at it", async () => { + const dockerfile = readFileSync(path.join(REPO, "Dockerfile"), "utf8"); + const pinned = /^ARG HYPERFRAMES_VERSION=(\S+)$/m.exec(dockerfile)?.[1]; + assert.ok(pinned, "the Dockerfile pins HYPERFRAMES_VERSION"); + const deck = readFileSync(path.join(REPO, "umtool", "report-to-video", "deck.mjs"), "utf8"); + const named = /export const HYPERFRAMES_PKG_DEFAULT = "hyperframes@([^"]+)";/.exec(deck)?.[1]; + assert.equal(pinned, named, `the image installs hyperframes@${pinned}, deck.mjs renders with hyperframes@${named}`); + assert.match(dockerfile, /^ENV HYPERFRAMES_BIN=\/usr\/local\/bin\/hyperframes /m); + assert.match(dockerfile, /^FROM runtime-base AS runtime-umtool$/m); +}); + +// The deps stage pre-fetches node-datachannel's prebuilt binary into +// prebuild-install's cache (its own download gives up too soon from a build +// container); the version it fetches must be the one the lockfile installs, or +// the cache misses and the install falls back to a source build that fails. +test("the deps stage pre-fetches the node-datachannel prebuilt the lockfile installs", () => { + const dockerfile = readFileSync(path.join(REPO, "Dockerfile"), "utf8"); + const pinned = /^ARG NODE_DATACHANNEL_VERSION=(\S+)$/m.exec(dockerfile)?.[1]; + assert.ok(pinned, "the Dockerfile pins NODE_DATACHANNEL_VERSION"); + const lock = readFileSync(path.join(REPO, "pnpm-lock.yaml"), "utf8"); + const locked = [...new Set([...lock.matchAll(/^ {2}node-datachannel@(\d+\.\d+\.\d+):$/gm)].map((m) => m[1]))]; + assert.deepEqual(locked, [pinned], `the lockfile installs node-datachannel ${locked.join(", ")}; the Dockerfile pre-fetches ${pinned}`); +}); + // The yt-dlp substitution hook: the image ships its own yt-dlp as // ARCHILYZER_IMAGE_YTDLP beside YTDLP_BIN (the entrypoint and the doctor tell an // override by the difference), and links the from-source wrapper — in every 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 diff --git a/docker-compose.anthropic.yml b/docker-compose.anthropic.yml @@ -0,0 +1,39 @@ +# Claude API overlay: the features that call the Claude API (frame scan, +# generation routed to "api") read the same one-line key file a host install +# does — ANTHROPIC_API_KEY=…, mode 600. +# +# docker compose -f docker-compose.yml -f docker-compose.anthropic.yml up -d +# +# (`archilyzer service install` adds this overlay by itself when the file +# exists.) +# +# The file is bind-mounted READ-ONLY at the path the app's default +# `generation.apiKeyFile` names (~/.config/archilyzer/anthropic.env, root's home +# in the container), so no setting changes. A mount, not an env_file and not a +# variable: its value never appears in `docker compose config`, in +# `docker inspect`, or in .env. The app refuses a key file that group or others +# can read — `chmod 600` it on the host; a bind mount keeps the host's mode. +# +# Not there? `up` refuses with "bind source path does not exist" rather than +# creating an empty directory where the file should be. Leave the overlay out +# and those features say "no API key"; every other feature works without it. +# +# Another path: ARCHILYZER_ANTHROPIC_ENV_FILE in .env. + +services: + editor: + volumes: + - type: bind + source: ${ARCHILYZER_ANTHROPIC_ENV_FILE:-${HOME:-.}/.config/archilyzer/anthropic.env} + target: /root/.config/archilyzer/anthropic.env + read_only: true + bind: + create_host_path: false + umtool: + volumes: + - type: bind + source: ${ARCHILYZER_ANTHROPIC_ENV_FILE:-${HOME:-.}/.config/archilyzer/anthropic.env} + target: /root/.config/archilyzer/anthropic.env + read_only: true + bind: + create_host_path: false diff --git a/docker-compose.browser.yml b/docker-compose.browser.yml @@ -0,0 +1,45 @@ +# Browser cookies overlay: yt-dlp's `--cookies-from-browser` (Settings → +# cookiesFromBrowser, a channel's own value, and cookieMode) and gallery-dl's +# read a browser's cookie store. In a container there is no browser, so the +# host's Firefox profiles are mounted READ-ONLY and the setting names the path: +# +# docker compose -f docker-compose.yml -f docker-compose.browser.yml up -d +# +# then, in Settings (or a channel's Configure form): +# +# cookiesFromBrowser = firefox:/data/browser/firefox +# +# yt-dlp takes a path as the profile and reads the newest cookies.sqlite under +# it (one profile dir — firefox:/data/browser/firefox/<xxxx.default-release> — +# pins one). It copies the database before reading, so read-only is enough, and +# Firefox may stay open on the host. +# +# What works from here: +# Firefox YouTube, Rumble (cf_clearance — the app pins the User-Agent that +# cookie was issued to), Odysee, X via gallery-dl. Its cookies are +# not encrypted on Linux. +# Chrome / NOT from a container: on Linux their cookies are encrypted with a +# Chromium key held by the desktop keyring (GNOME Keyring, KWallet), which a +# container cannot reach. Export a cookies.txt (Netscape format) +# instead, copy it into the config volume and name it with file:: +# docker compose cp cookies.txt editor:/data/config/cookies.txt +# cookiesFromBrowser = file:/data/config/cookies.txt +# (no overlay needed for that one; a cookies.txt goes stale as the +# site rotates its cookies — re-export when fetches start failing). +# +# Where your profiles are: +# ~/.mozilla/firefox the classic place (the default here) +# ~/.config/mozilla/firefox a newer Firefox's XDG location +# ~/snap/firefox/common/.mozilla/firefox Ubuntu's snap +# ~/.var/app/org.mozilla.firefox/.mozilla/firefox flatpak +# Set ARCHILYZER_FIREFOX_PROFILES in .env when yours is not the first. + +services: + editor: + volumes: + - type: bind + source: ${ARCHILYZER_FIREFOX_PROFILES:-${HOME:-.}/.mozilla/firefox} + target: /data/browser/firefox + read_only: true + bind: + create_host_path: false diff --git a/docker-compose.gpu.yml b/docker-compose.gpu.yml @@ -28,8 +28,9 @@ services: count: all capabilities: [gpu] - # The other three run the same image so `docker compose ... up` never rebuilds - # a second variant behind your back. None of them touches the GPU. + # site and homepage run the same image so `docker compose ... up` never + # rebuilds a second variant behind your back. Neither touches the GPU. + # umtool keeps its own image (runtime-umtool). site: build: target: runtime-cuda @@ -38,7 +39,13 @@ services: build: target: runtime-cuda image: archilyzer:${ARCHILYZER_TAG:-local}-cuda - umtool: - build: - target: runtime-cuda - image: archilyzer:${ARCHILYZER_TAG:-local}-cuda + + # ollama (profile `ollama`) on the NVIDIA GPU too. + ollama: + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] diff --git a/docker-compose.vulkan.yml b/docker-compose.vulkan.yml @@ -53,8 +53,9 @@ services: # measure what the GPU is buying you. Unset — the default — lets # parakeet.cpp choose. - # The other three run the same image so `up` never builds a second variant - # behind your back. None of them touches the GPU. + # site and homepage run the same image so `up` never builds a second + # variant behind your back. Neither touches the GPU. umtool keeps its own + # image (runtime-umtool) — the renderer needs no GPU. site: build: target: runtime-vulkan @@ -67,9 +68,13 @@ services: args: RUNTIME_IMAGE: node:22-trixie-slim image: archilyzer:${ARCHILYZER_TAG:-local}-vulkan - umtool: - build: - target: runtime-vulkan - args: - RUNTIME_IMAGE: node:22-trixie-slim - image: archilyzer:${ARCHILYZER_TAG:-local}-vulkan + + # ollama (profile `ollama`) on the same render node. Its Vulkan backend is + # opt-in upstream (OLLAMA_VULKAN=1) and newer than its CUDA/ROCm ones: check + # `docker compose logs ollama` for the device it found, and compare a + # generation's speed with the variable unset if in doubt. + ollama: + devices: + - /dev/dri:/dev/dri + environment: + OLLAMA_VULKAN: "1" diff --git a/docker-compose.yml b/docker-compose.yml @@ -8,6 +8,11 @@ # docker compose --profile site up -d + the published archive # docker compose --profile site --profile homepage up -d # docker compose --profile umtool up -d +# docker compose --profile ollama up -d + a local model server +# +# Or as a service that starts at boot: `pnpm archilyzer service install` +# (a systemd user unit running this file; RUNNING_IN_DOCKER.md, "Run it as a +# service"). # # THE EXPOSURE MODEL, which is the load-bearing part of this file: # @@ -83,6 +88,13 @@ x-app-env: &app-env # are on the caddy service below. EDITOR_PORT: "3001" UMTOOL_PORT: "3050" + # umtool's projects (report → video), in the reports volume. + REPORTS_DIR: /data/reports + # Local models: the `ollama` service (profile `ollama`) by default. A host's + # own ollama instead: OLLAMA_URL=http://host.docker.internal:11434 in .env. + OLLAMA_URL: ${OLLAMA_URL:-http://ollama:11434} + # How umtool (and an MCP run inside a container) reaches the editor. + ARCHILYZER_EDITOR_URL: http://editor:3001 services: # ------------------------------------------------------------------------- @@ -116,6 +128,10 @@ services: editor: <<: *app command: ["editor"] + # host.docker.internal resolves on Linux too (Docker Desktop has it built + # in): a host's ollama, or another service on the host, at that name. + extra_hosts: + - "host.docker.internal:host-gateway" environment: <<: *app-env # The publish lock's host identity (common/publish/stageLock.ts). Its @@ -130,6 +146,7 @@ services: - config:/data/config - models:/data/models - builds:/data/builds + - reports:/data/reports healthcheck: # /api/pulse answers from in-memory state plus two stat() calls — it is # built to be polled forever, which is exactly what a healthcheck does. @@ -182,12 +199,46 @@ services: <<: *app profiles: [umtool] command: ["umtool"] + # Its own image: the runtime-umtool target adds what report → video + # renders shell out to (ImageMagick 7 with Pango, rsvg-convert, qrencode, + # zbarimg, chromium, hyperframes and its headless shell). On trixie, for + # ImageMagick 7 — the Dockerfile says why. + build: + context: . + target: runtime-umtool + args: + RUNTIME_IMAGE: node:22-trixie-slim + ARCHILYZER_COMMIT: ${ARCHILYZER_COMMIT:-} + ARCHILYZER_BRANCH: ${ARCHILYZER_BRANCH:-} + image: archilyzer:${ARCHILYZER_TAG:-local}-umtool + extra_hosts: + - "host.docker.internal:host-gateway" environment: <<: *app-env + UMTOOL_CACHE_DIR: /data/builds/umtool-cache volumes: - corpus:/data/transcripts - config:/data/config - builds:/data/builds + - reports:/data/reports + # A render runs ffmpeg and a headless browser in here; give its children + # time to stop. + stop_grace_period: 30s + + # ------------------------------------------------------------------------- + # Local models: ollama, for the digest lanes and generation routed to + # "local". Internal only (no port); the apps reach it at http://ollama:11434. + # Pull a model once: + # docker compose exec ollama ollama pull qwen3:8b + # GPU: the vulkan and gpu overlays give it the same device as the editor. + # ------------------------------------------------------------------------- + ollama: + image: ollama/ollama:${ARCHILYZER_OLLAMA_TAG:-0.40.5} + profiles: [ollama] + restart: unless-stopped + networks: [archilyzer] + volumes: + - ollama:/root/.ollama networks: archilyzer: @@ -210,5 +261,10 @@ volumes: # the locally deployed site and homepage. Reproducible; losing it costs a # rebuild, not data. builds: + # umtool's projects: manifests, takes, renders. Real work — back it up with + # the corpus. + reports: + # ollama's models (profile `ollama`). Re-downloadable. + ollama: caddy-data: caddy-config: diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh @@ -45,7 +45,12 @@ mkdir -p \ "${MODELS_DIR}" \ "${BUILDS_DIR}" \ "${SITE_OUT}" \ - "${HOMEPAGE_OUT}" + "${HOMEPAGE_OUT}" \ + "${REPORTS_DIR:-/data/reports}" +# The targets of the image's three state links (Dockerfile, runtime-base): the +# TTS engines, the TTS cache and the generation ledger. Fixed paths, as the +# links are. +mkdir -p /data/models/tts /data/builds/tts /data/config/generation # The operator's private config dir (compose sets it inside the config volume), # made so `docker compose cp` has somewhere to put the source mirror's rules. # Only made, never filled: what goes in it is the operator's. diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog ## [Unreleased] +- **Every feature runs in Docker, and the whole stack runs as a service.** `pnpm archilyzer service install` installs Archilyzer as systemd user units and starts it — in Docker (one `archilyzer.service` running `docker compose up`, the default when Docker is present) or on the host (`--mode host`: `archilyzer-editor.service`, `archilyzer-umtool.service`, and `--sites <id>:<port>` for a private site's server). `service status` shows each unit, its build, its port's answer and whether the transcription lane is held; `service logs`, `service restart` and `service uninstall` do what they say; `--dry-run` prints the units and writes nothing, and units you already have under those names are adopted when identical and shown as a diff when not (`--force` replaces them). In Docker, umtool now renders report videos (its own image carries ImageMagick 7, chromium and hyperframes), the image carries gallery-dl, headless Chromium and espeak-ng, `--profile ollama` runs local models, and overlays mount the Claude API key file, your Firefox cookies and every media drive (`archilyzer service storage-overlay` writes that one). RUNNING_IN_DOCKER.md has a feature-by-install table. +- **A cookies.txt works wherever a browser's cookies do.** Set cookies-from-browser (in Settings or on a channel) to `file:/path/to/cookies.txt` and yt-dlp and gallery-dl are handed `--cookies <path>` — for a container, or a machine whose browser store cannot be read. +- **A fresh install's dashboard says what to do first.** With no channel yet, **First steps** lists adding a channel, whether a transcription worker has its model, syncing and transcribing, and publishing — each with what this install already has. - **A frame scan can be re-derived and corrected from its panel, with no model.** The video page's **Frame scan** panel has **Re-derive (no model)** beside the hero's screen name (what `archilyzer frames rederive` did), and **Correct a reading**: open the reading at a time, or from the **Correct** beside any event, and set a field to what the frame shows — the stack, players left, the blinds, the tournament's name, the log lines… — or **Mark misread** to set the whole reading aside. The correction is kept beside what the model read (each corrected field says what it read), the timeline is worked out again at once with your values, and every later scan and re-derive keeps them; **Clear correction** takes one back. The corrections are listed under the flags. Needs a restart of the editor. - **Find copies of gone videos from the channel page and the site page.** The channel's Download stage (and a site's page, for all its channels) has **Find copies of gone videos**: which gone videos (no transcript, or every one with no media), at most how many lookups, and whether to try failed copies again. **Preview** looks without recording or fetching anything and lists each video with the copy it would use (the Wayback capture or the archive.org file); **Find and fetch copies**, armed by a preview of the same settings, runs it and links the find-copy job and the fetch-copies job it started. Needs a restart of the editor. - **Audit audio from the channel page, and see the verdicts.** The Download stage has **Audit audio** (videos with no transcript, or every video holding audio; at most how many files; decode again files already audited) and a line with the channel's verdicts — clean, damaged, undecodable, and out of date where the file changed since — and when it last checked. The video page shows its audio's verdict: how much decodes and where the gaps are. The counts appear once the channel's report is regenerated. Needs a restart of the editor. diff --git a/editor/app/components/dashboard/DashboardCockpit.tsx b/editor/app/components/dashboard/DashboardCockpit.tsx @@ -8,6 +8,7 @@ import { usePolledPayload, useNow } from "../../lib/usePolledPayload"; import { PipelineBand } from "./PipelineBand"; import { NeedsWorkPanel } from "./NeedsWorkPanel"; import { QuickAddPanel } from "./QuickAddPanel"; +import { FirstRunPanel, type FirstRunState } from "./FirstRunPanel"; import type { ChannelRowView } from "yt-dlp-transcript-common/views/channelRow"; import { ChannelsTable } from "../../channels/components/ChannelsTable"; import { @@ -33,6 +34,8 @@ export type DashboardCockpitInitial = { // client state — so a global AutoRefresh re-seeds them live. channels: ChannelRowView[]; changelogSource: string | null; + // Set while the corpus has no channel (app/page.tsx): the first-run checklist. + firstRun?: FirstRunState | null; }; // The mission-control cockpit. A server component (app/page.tsx) SSRs the @@ -74,6 +77,7 @@ export function DashboardCockpit({ return ( <div className="flex flex-col gap-6"> <h1 className="sr-only">Dashboard</h1> + {initial.firstRun && <FirstRunPanel state={initial.firstRun} />} <PipelineBand jobs={jobs} workers={workers} diff --git a/editor/app/components/dashboard/FirstRunPanel.tsx b/editor/app/components/dashboard/FirstRunPanel.tsx @@ -0,0 +1,85 @@ +import Link from "next/link"; + +// What a fresh install has and lacks, gathered by app/page.tsx (server side) +// when the corpus has no channel yet. Every line is a fact about this install; +// a step already done says so rather than being left out. +export type FirstRunState = { + // Enabled local transcription workers, each with the model file it would run + // and whether that file is there. + workers: { name: string; model: string; present: boolean }[]; + siteCount: number; +}; + +function Step({ + n, + done, + title, + href, + action, + children, +}: { + n: number; + done: boolean; + title: string; + href: string; + action: string; + children?: React.ReactNode; +}) { + return ( + <li className="flex gap-3" data-done={done ? "true" : "false"}> + <span + aria-hidden="true" + className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border font-mono text-[11px] ${ + done ? "border-brand bg-brand/15 text-brand" : "border-border text-muted-foreground" + }`} + > + {done ? "✓" : n} + </span> + <div className="flex min-w-0 flex-col gap-0.5"> + <div className="flex flex-wrap items-baseline gap-x-3"> + <span className="text-sm font-medium text-foreground">{title}</span> + <Link href={href} className="text-xs text-brand underline underline-offset-2 hover:text-foreground"> + {action} + </Link> + </div> + {children && <div className="text-xs text-muted-foreground break-words">{children}</div>} + </div> + </li> + ); +} + +// The dashboard's first-run checklist: shown only while there is no channel. +export function FirstRunPanel({ state }: { state: FirstRunState }) { + const ready = state.workers.filter((w) => w.present); + return ( + <section aria-label="First steps" className="rounded-md border border-brand/40 bg-card px-4 py-3"> + <h2 className="font-mono text-xs uppercase tracking-[0.14em] text-brand mb-3">First steps</h2> + <ol className="flex flex-col gap-3"> + <Step n={1} done={false} title="Add a channel" href="/channels/new" action="Paste a URL" /> + <Step + n={2} + done={ready.length > 0} + title="A transcription worker with a model" + href="/workers" + action="Workers page" + > + {state.workers.length === 0 + ? "No transcription worker is enabled." + : state.workers.map((w) => ( + <span key={w.name} className="block"> + {w.name}: {w.present ? "model ready" : "model missing"} — <code>{w.model || "none named"}</code> + </span> + ))} + </Step> + <Step n={3} done={false} title="Sync, then transcribe" href="/channels" action="Channels page"> + Sync downloads captions and audio; Transcribe covers the videos without captions. + </Step> + <Step n={4} done={state.siteCount > 0} title="Publish a site" href="/sites" action="Sites page"> + {state.siteCount > 0 + ? `${state.siteCount} site${state.siteCount === 1 ? "" : "s"} configured.` + : "No site yet."} + </Step> + </ol> + </section> + ); +} diff --git a/editor/app/page.tsx b/editor/app/page.tsx @@ -1,4 +1,4 @@ -import { readFileSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import type { Metadata } from "next"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { inspectChannelMedia } from "yt-dlp-transcript-common/lib/channelMedia"; @@ -27,6 +27,8 @@ import { } from "yt-dlp-transcript-common/views/channelRow"; import { buildWidgetActionablePayload } from "yt-dlp-transcript-common/views/widgetActionable"; import type { ActionableRow } from "./lib/actionable/loadActionable"; +import type { FirstRunState } from "./components/dashboard/FirstRunPanel"; +import type { Paths } from "yt-dlp-transcript-common/lib/paths"; export const dynamic = "force-dynamic"; @@ -38,6 +40,22 @@ export async function generateMetadata(): Promise<Metadata> { return { title: `Dashboard — ${settings.adminTitle}` }; } +// The first-run checklist's facts (only computed while there is no channel): +// each enabled local worker's model — its own, else the engine's default, as +// the doctor reads it — and whether the file is there; how many sites exist. +function firstRunState(paths: Paths): FirstRunState { + const settings = getSettings(); + const workers = settings.workers + .filter((w) => w.enabled && w.kind === "local") + .map((w) => { + const own = typeof w.config?.model === "string" ? w.config.model.trim() : ""; + const model = + own || (w.appId === "whisper-cpp" ? paths.whisperModel : w.appId === "parakeet" ? paths.parakeetModel : ""); + return { name: w.name || w.id, model, present: model !== "" && existsSync(model) }; + }); + return { workers, siteCount: listSiteIds(paths).length }; +} + function loadChangelog(): string | null { try { return readFileSync(getPaths().editorChangelogFile, "utf8"); @@ -131,6 +149,7 @@ export default async function Dashboard({ sync, channels, changelogSource, + firstRun: summary.rows.length === 0 ? firstRunState(paths) : null, }} /> ); diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9988,3 +9988,39 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri HAND_FIELDS order, token chained, stopping at the first refusal (earlier writes kept and named). Written unmarked = the operator's. A blank is never written as a placeholder. + + +## The apps as services, and Docker parity (verified 2026-10-16, branch `r32/services`) + +- **`archilyzer service install|status|logs|restart|uninstall|storage-overlay`** (`common/bin/service.ts`; units + rendered by the pure `common/lib/service/units.ts`, tested byte for byte). systemd USER units in + `$XDG_CONFIG_HOME/systemd/user` (default `~/.config/systemd/user`); Linux only. +- **Unit names:** docker mode `archilyzer.service` (compose `up --no-build` in the foreground, `down` on stop, + `--profile` per app, `-f` per overlay); host mode `archilyzer-editor.service`, `archilyzer-umtool.service`, + `archilyzer-site-<id>.service` (`export/scripts/serve-out.mjs <exportBuildsDir>/<id>/out <port>`, HOST=127.0.0.1). +- **Host units are the operator's hand-written units of 2026-10-16, reproduced**: node directly, `next start -H 0.0.0.0 + -p 3001|3050` from the app dir, `UV_THREADPOOL_SIZE=16` (editor), PATH `~/.local/bin:~/.local/share/pnpm:/usr/local/bin: + /usr/bin:/bin` (node's dir first when elsewhere), ExecStartPre refusing without `.next/BUILD_ID`, StartLimit 5/300 s, + KillMode=mixed, TimeoutStopSec 90 (editor) / 60 (umtool), MemoryMax = ceil(MemTotal × ½) (editor) / ceil(× ⅜) + (umtool) GiB, MemoryHigh 1 GiB under — 8G/7G and 6G/5G on a 16 GB machine. Install over an identical unit = adopt + (no write, no daemon-reload); a different one → diff, refused without `--force`; a replaced running unit is NOT + restarted. +- **Mode default:** `--mode`, else host when any `archilyzer-*.service` is installed, else docker when it is, else + docker when `docker compose version` answers, else host. +- **Image:** `runtime-umtool` target (FROM runtime-base on trixie via `RUNTIME_IMAGE`, for ImageMagick 7's `magick`; + + Pango coder, rsvg-convert, qrencode, zbarimg, chromium, `hyperframes@<HYPERFRAMES_PKG_DEFAULT>` + `browser + ensure`; `HYPERFRAMES_BIN`, `CHROME`). runtime-base and runtime-cuda: gallery-dl pinned via pipx (`GALLERY_DL_BIN`), + espeak-ng, Playwright's headless shell at `PLAYWRIGHT_BROWSERS_PATH=/opt/ms-playwright` (`--with-deps`), + `REPORTS_DIR=/data/reports`, and three state links into volumes: `~/.local/share/archilyzer/tts` → + `/data/models/tts`, `/repo/.tts` → `/data/builds/tts`, `/repo/.generation` → `/data/config/generation` (the daily + caps' ledger survives a recreate). `buildImage.test.ts` holds the gallery-dl and hyperframes pins. +- **Compose:** volumes `reports`, `ollama`; `ollama` service (profile `ollama`, `ollama/ollama:${ARCHILYZER_OLLAMA_TAG:-0.40.5}`, + internal); `OLLAMA_URL` defaults to `http://ollama:11434`; `ARCHILYZER_EDITOR_URL=http://editor:3001`; + `host.docker.internal:host-gateway` on editor and umtool. Overlays: `docker-compose.anthropic.yml` (the key file + bind-mounted read-only at `/root/.config/archilyzer/anthropic.env`, `create_host_path: false` — never env, so + `docker compose config` cannot print it), `docker-compose.browser.yml` (Firefox profiles at `/data/browser/firefox`), + `docker-compose.storage.yml` (GENERATED, gitignored; every location root + every uncovered absolute `media`/`data`/ + saved-videos link target, same path, editor + umtool). +- **Cookie spec `file:<path>`** (`cookiePolicy.ts` `cookieArgs`, `cookieFileOf`; gallery-dl's login args) → + `--cookies <path>`; any other spec stays `--cookies-from-browser <spec>`. `file:` with no path → no flag. +- **First run:** the dashboard's `FirstRunPanel` renders only while the actionable summary has zero channels. diff --git a/plans/release-32/services.md b/plans/release-32/services.md @@ -0,0 +1,95 @@ +# Release 32 — every feature in Docker, and both modes as services (as shipped) + +Operator ask (2026-10-16): "Could we have everything able to be run as a systemd service, supporting either on host or +via Docker?" and "I want to make it as easy as possible for anyone to use all the features of Archilyzer, and I think +Docker is a core component of that." Rulings followed: Docker is the first-class install with full feature parity, +host mode the alternative, both run as systemd services from one command; on THIS machine the operator chose host-mode +user units (written by hand 2026-10-16), which `service install --mode host` must reproduce and adopt; nothing in this +lane installs, enables, starts or stops a unit here. + +## What + +- **`archilyzer service install|status|logs|restart|uninstall`** (`common/bin/service.ts`, units rendered by the pure + `common/lib/service/units.ts`). systemd USER units; Linux only (a sentence elsewhere). + - docker mode (default when `docker compose` answers and nothing is installed): ONE `archilyzer.service` running + `docker compose -f … --profile … up --no-build` in the foreground, `down` on stop, Restart=on-failure; two + ExecStartPre guards (wait ≤ 2 min for the daemon; refuse with the build line when an `archilyzer:` image is + missing). `--apps` = profiles (editor, umtool, site, homepage, ollama); overlays from `--overlays` or found + (anthropic when the key file EXISTS — never opened; storage when `docker-compose.storage.yml` exists). + - host mode: `archilyzer-editor.service`, `archilyzer-umtool.service` — byte for byte the operator's units for this + machine's paths (node directly, `next start -H <bind> -p 3001|3050`, UV_THREADPOOL_SIZE=16, explicit PATH with + `~/.local/bin`, ExecStartPre BUILD_ID refusal, StartLimit 5/300 s, KillMode=mixed, TimeoutStopSec 90/60, + MemoryHigh/Max from MemTotal: 7G/8G and 5G/6G at 16 GB) — and `archilyzer-site-<id>.service` per `--sites + <id>:<port>` (`serve-out.mjs` over the built bundle, HOST=127.0.0.1; how the private sites were served by hand). + - Adopt: an installed unit with identical text is left alone (no write, no daemon-reload); a different one is shown + as a diff and refused unless `--force`; a replaced running unit is not restarted. `--dry-run` writes nothing. + `--linger` runs `loginctl enable-linger`; `--no-start` enables only; `--idle-boot` adds ARCHILYZER_IDLE_BOOT=1. + - `status` (read-only): each unit's state/enablement/pid/since, an app's build id, its port's answer, the + transcription lane's held/armed state (host: settings.json; docker: `exec editor cat`), each container in docker + mode. `logs` wraps `journalctl --user`, `restart` / `uninstall` systemctl. +- **`archilyzer service storage-overlay`**: writes `docker-compose.storage.yml` (gitignored): every location root, + every channel `media`/legacy `data` link and the saved-video store link no location covers, bind-mounted into the + editor and umtool at the same absolute path, `create_host_path: false`; `--corpus <dir>` mounts a host corpus at + `/data/transcripts`. Read by lstat/readlink on the corpus disk only. +- **Image parity** (Dockerfile): a `runtime-umtool` target (trixie for ImageMagick 7; Pango coder asserted at build; + rsvg-convert, qrencode, zbarimg, chromium, `hyperframes@0.8.24` + its headless shell, telemetry off) run by the + umtool service; in every editor target gallery-dl (pinned 1.32.9, `GALLERY_DL_BIN`), Playwright's headless Chromium + (`--with-deps`, `/opt/ms-playwright` — the editor's report exports, Bluesky/Nitter/X/forum fetchers need it too), + espeak-ng, `REPORTS_DIR`, and links keeping TTS installs, the TTS cache and the generation ledger in volumes. The deps + stage pre-fetches node-datachannel's prebuilt (prebuild-install timed out from the build container, the source + fallback failed, and with it every image build since release 21). +- **Compose**: `reports` and `ollama` volumes; an `ollama` service (profile, internal, `ARCHILYZER_OLLAMA_TAG`), `OLLAMA_URL` + defaulting to it; `ARCHILYZER_EDITOR_URL=http://editor:3001`; `host.docker.internal` on Linux. Overlays + `docker-compose.anthropic.yml` (the key file as a read-only bind — never an env value, so `docker compose config` + cannot print it) and `docker-compose.browser.yml` (Firefox profiles read-only); vulkan/gpu overlays give ollama the + GPU and no longer retarget umtool. +- **Cookie spec `file:<path>`** → `--cookies <path>` for yt-dlp and gallery-dl (Chrome's keyring-encrypted cookies + cannot be read from a container; a cookies.txt can). +- **Editor first run**: the dashboard's **First steps** while there is no channel (add a channel; each enabled + worker's model present or missing; sync and transcribe; publish). +- **RUNNING_IN_DOCKER.md**: quickstart to a transcribed channel, Run it as a service, report → video, local models, + the Claude API, browser cookies, X posts, TTS, the MCP from the container, the storage overlay (now the media tier's + links), and the feature × install matrix. + +## Files + +`common/lib/service/{units.ts,units.test.ts}`, `common/bin/{service.ts,service.test.ts,archilyzer.ts}`, +`common/lib/{cookiePolicy.ts,cookiePolicy.test.ts,envVars.ts,settingsSchema.ts,channelConfig.ts}`, +`common/social/xGalleryDlFetcher.ts`, `common/publish/buildImage.test.ts`, `Dockerfile`, `docker-compose.yml`, +`docker-compose.{vulkan,gpu,anthropic,browser}.yml`, `docker/entrypoint.sh`, `.env.example`, `.gitignore`, +`editor/app/page.tsx`, `editor/app/components/dashboard/{FirstRunPanel.tsx,DashboardCockpit.tsx}`, +`RUNNING_IN_DOCKER.md`, `AGENTS.md`; COMMANDS.md, ENVIRONMENT.md, CHANNEL.md, SETTINGS.md regenerated. + +## Gates + +On the branch after merging main `45c5a583`: tsc clean (all packages); common **4477** (4476 pass, 1 skipped; new: +`service/units.test.ts` 9, `bin/service.test.ts` 9, `cookiePolicy` +1, `buildImage` +3); editor **327/327**; +test:scripts **1045** (1041 pass, 4 skipped); `docs env`, `docs files`, `docs cli`, `settings example` checks clean. + +- **Host units vs the operator's live units** (read-only): `service install --mode host --dry-run` with the primary + checkout as root → both `= … already installed, identical — adopted`; `service status` against them → active, + enabled, build ids, `/` → 200 on 3001 and 3050, the transcription lane's state. No unit was installed, enabled, + started or stopped. +- **Image** (capped builder, 8 GB): `runtime` 457 s, **2.60 GB**; `runtime-umtool` 529 s, **4.28 GB** (rebuilt after + the merge and the policy fix, 540 s). Not built: `runtime-vulkan`, `runtime-cuda` (their new lines — gallery-dl, + espeak-ng, Playwright `--with-deps` on trixie/ubuntu 24.04 — are unverified by a build). +- **Container smoke** (`-p r32smoke`, fresh volumes, `ARCHILYZER_FETCH_MODEL=none`, `ARCHILYZER_IDLE_BOOT=1`, editor + + umtool, `down -v` after): `/api/pulse` 200; the dashboard shows **First steps** with "model missing"; `exec editor + pnpm archilyzer --help` lists the six `service` rows; gallery-dl 1.32.9, espeak-ng, yt-dlp, whisper-cli; the three + state links resolve into the volumes; headless Chromium launches in the editor (147.0.7727.15); `archilyzer doctor` + exit 0 (2 warnings: the skipped model; qrencode, which only the umtool image carries); umtool `/` 200, umtool → + `http://editor:3001/api/pulse` 200; ImageMagick 7.1.1-43 with PANGO, rsvg-convert 2.60.0, qrencode 4.1.1, zbarimg, + Chromium 155, hyperframes 0.8.24 + its headless shell, Playwright's shell. +- **Renders in the umtool container**: chrome-deck (hyperframes frames), brand (pango/rsvg cards), deck-build, + chrome-posts, chrome-teaser, chrome-feed, audio-poster, av-sync: **99 tests, 98 pass, 0 skipped**. The one failure is + av-sync's CONTROL assertion (that the old unpinned graph drifts ~60 ms) — with Debian's ffmpeg 7.1 it does not drift; + the pinned assertion (the shipped behaviour) passes. Found and fixed on the way: Debian's ImageMagick policy refused + `pango:@file` (every text card). +- `docker compose config -q` clean for the base file and each overlay (vulkan, gpu, anthropic, browser) with the + umtool and ollama profiles. The `ollama/ollama` image was not pulled. + +## Rulings followed + +Docker first-class, host the alternative, both as services from one command; host-mode units on this machine are the +operator's and are adopted, never replaced without `--force`; nothing calls a model; the Claude key file is never +read or printed by the command (existence only) and reaches a container only as a read-only mount.