Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add a managed SuperCollider runtime and setup:supercollider (#9412)
[._.]/ Adam Eivyf280f2c3ac7b
diff --git a/docker/supercollider/Dockerfile b/docker/supercollider/Dockerfilenew file mode 100644index 0000000000..a33f6271f0--- /dev/null+++ b/docker/supercollider/Dockerfile@@ -0,0 +1,88 @@+# PortOS managed SuperCollider runtime (sclang + scsynth + stock class library+# and plugins), built only by `npm run setup:supercollider`. Contract, limits and+# platform evidence: docs/SUPERCOLLIDER.md. License/source notices: NOTICE.md.+#+# Every input is pinned so a rebuild on another install produces the same+# runtime:+# - the Debian base image by digest,+# - every Debian package through snapshot.debian.org at the base image's own+# serial date (the official images are built from that snapshot),+# - the SuperCollider release source tarball by SHA-256.+#+# Changing anything in this directory changes the recipe hash PortOS stamps on+# the image, which marks an older image stale and its readiness evidence void.+# Bump SUPERCOLLIDER_RUNTIME_VERSION in server/lib/superColliderRuntime.js with+# any pin change; its test fails when the two disagree.++ARG DEBIAN_IMAGE=debian:trixie-20260918-slim@sha256:a99cfc517144bc59b1978475ec53b46ecabec7e43635402ee5b77cc54cd1b20a++FROM ${DEBIAN_IMAGE} AS base+ARG DEBIAN_SNAPSHOT=20260918T000000Z+# Point apt at the dated snapshot instead of the moving mirror. Valid-Until is+# necessarily in the past for an archived Release file.+RUN set -eux; \+ sed -i \+ -e "s#http://deb.debian.org/debian-security#http://snapshot.debian.org/archive/debian-security/${DEBIAN_SNAPSHOT}#" \+ -e "s#http://deb.debian.org/debian\$#http://snapshot.debian.org/archive/debian/${DEBIAN_SNAPSHOT}#" \+ /etc/apt/sources.list.d/debian.sources; \+ grep -q "snapshot.debian.org/archive/debian/${DEBIAN_SNAPSHOT}" /etc/apt/sources.list.d/debian.sources; \+ printf 'Acquire::Check-Valid-Until "false";\nAcquire::Retries "5";\nAPT::Install-Recommends "false";\n' \+ > /etc/apt/apt.conf.d/99portos-snapshot++FROM base AS build+ARG SC_VERSION=3.14.1+ARG SC_SOURCE_SHA256=ee640c68777ae697682066ce5c4a8b7e56c5b223e76c79c13b5be5387ee55bb2+RUN set -eux; \+ apt-get update; \+ apt-get install -y \+ build-essential bzip2 ca-certificates cmake curl pkg-config \+ libasound2-dev libfftw3-dev libjack-jackd2-dev libncurses-dev \+ libreadline-dev libsndfile1-dev libudev-dev; \+ rm -rf /var/lib/apt/lists/*+RUN set -eux; \+ curl -fsSL --retry 5 -o /tmp/sc.tar.bz2 \+ "https://github.com/supercollider/supercollider/releases/download/Version-${SC_VERSION}/SuperCollider-${SC_VERSION}-Source.tar.bz2"; \+ echo "${SC_SOURCE_SHA256} /tmp/sc.tar.bz2" | sha256sum -c -; \+ mkdir /src; \+ tar -xjf /tmp/sc.tar.bz2 -C /src --strip-components=1; \+ rm /tmp/sc.tar.bz2+# Headless build: no Qt/IDE/editor integrations, no X11/Avahi/HID/Link, no+# supernova. NATIVE stays off so the binaries run on any CPU of this architecture.+RUN set -eux; \+ cmake -S /src -B /build \+ -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local \+ -DSC_QT=OFF -DSC_IDE=OFF -DSC_EL=OFF -DSC_VIM=OFF \+ -DSUPERNOVA=OFF -DNO_X11=ON -DNO_AVAHI=ON -DSC_HIDAPI=OFF -DSC_ABLETON_LINK=OFF \+ -DENABLE_TESTSUITE=OFF -DINSTALL_HELP=OFF -DNATIVE=OFF -DUSE_CCACHE=OFF; \+ cmake --build /build --parallel "$(nproc)"; \+ cmake --install /build; \+ mkdir -p /usr/local/share/doc/supercollider; \+ cp /src/COPYING /src/AUTHORS /usr/local/share/doc/supercollider/; \+ echo "SuperCollider ${SC_VERSION} source: https://github.com/supercollider/supercollider/releases/tag/Version-${SC_VERSION} (sha256 ${SC_SOURCE_SHA256})" \+ > /usr/local/share/doc/supercollider/SOURCE+# The runtime stage installs exactly the Debian packages that own the shared+# libraries the installed binaries and plugins link against.+RUN set -eux; \+ find /usr/local/bin /usr/local/lib -type f \( -name 'sclang' -o -name 'scsynth' -o -name '*.so' \) -print0 \+ | xargs -0 ldd 2>/dev/null \+ | awk '$2 == "=>" && $3 ~ /^\// && $3 !~ /^\/usr\/local\// { print $3 }' | sort -u \+ | xargs realpath | xargs dpkg-query -S \+ | cut -d: -f1 | sort -u > /usr/local/share/doc/supercollider/runtime-packages.txt; \+ test -s /usr/local/share/doc/supercollider/runtime-packages.txt++FROM base AS runtime+COPY --from=build /usr/local /usr/local+RUN set -eux; \+ apt-get update; \+ xargs -a /usr/local/share/doc/supercollider/runtime-packages.txt apt-get install -y; \+ rm -rf /var/lib/apt/lists/*; \+ ldconfig; \+ if ldd /usr/local/bin/sclang /usr/local/bin/scsynth | grep 'not found'; then exit 1; fi; \+ sclang -v; \+ scsynth -v+COPY sclang_conf.yaml /opt/portos/sclang_conf.yaml+COPY NOTICE.md /usr/local/share/doc/supercollider/PORTOS-NOTICE.md+# Renders run as an unprivileged host-mapped user with a read-only root and a+# private tmpfs home; nothing here needs to be writable at runtime.+ENV LANG=C.UTF-8+WORKDIR /tmpdiff --git a/docker/supercollider/NOTICE.md b/docker/supercollider/NOTICE.mdnew file mode 100644index 0000000000..13357d7501--- /dev/null+++ b/docker/supercollider/NOTICE.md@@ -0,0 +1,32 @@+# PortOS SuperCollider runtime — license and source notices++This image is built locally by `npm run setup:supercollider` from the recipe in+this directory. PortOS does not publish or redistribute a prebuilt image.++## SuperCollider++- Version: 3.14.1 (`sclang`, `scsynth`, the stock class library and the stock+ server plugins; no Qt GUI, IDE, supernova, Quarks or third-party plugins)+- License: GNU General Public License, version 3 or later. The full text is+ installed at `/usr/local/share/doc/supercollider/COPYING`, with `AUTHORS`.+- Corresponding source: the official release tarball+ `https://github.com/supercollider/supercollider/releases/download/Version-3.14.1/SuperCollider-3.14.1-Source.tar.bz2`+ (SHA-256 `ee640c68777ae697682066ce5c4a8b7e56c5b223e76c79c13b5be5387ee55bb2`),+ built unmodified with the CMake options listed in the `Dockerfile`. The same+ reference is written to `/usr/local/share/doc/supercollider/SOURCE`.+- Upstream: https://supercollider.github.io/++## Debian packages++The base image is the official `debian:trixie-20260918-slim` image (pinned by+digest), and every package is installed from `snapshot.debian.org` at+`20260918T000000Z`. Each package's copyright and license file remains at+`/usr/share/doc/<package>/copyright` inside the image; the exact runtime package+list is recorded in `/usr/local/share/doc/supercollider/runtime-packages.txt`.+Source for any of them is available from the same snapshot+(`https://snapshot.debian.org/`).++## PortOS files++`sclang_conf.yaml` and this notice are part of PortOS and carry the PortOS+repository license.diff --git a/docker/supercollider/sclang_conf.yaml b/docker/supercollider/sclang_conf.yamlnew file mode 100644index 0000000000..e9e861d933--- /dev/null+++ b/docker/supercollider/sclang_conf.yaml@@ -0,0 +1,8 @@+# Stock class library only. excludeDefaultPaths drops the system and user+# Extensions directories, so no Quark, extension or operator customization can+# load; the private tmpfs home holds no startup file either.+includePaths:+ - /usr/local/share/SuperCollider/SCClassLibrary+excludePaths: []+postInlineWarnings: false+excludeDefaultPaths: truediff --git a/docs/README.md b/docs/README.mdindex 0a6f1abcb2..7504abeb1d 100644--- a/docs/README.md+++ b/docs/README.md@@ -9,6 +9,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo| Doc | Covers ||-----|--------|| [HTML_COMPOSITIONS.md](./HTML_COMPOSITIONS.md) | Seekable HTML scenes rendered offline to MP4 through hidden managed-browser targets |+| [SUPERCOLLIDER.md](./SUPERCOLLIDER.md) | Managed SuperCollider Docker runtime: `setup:supercollider`, readiness states, containment policy and platform evidence || [CODE_ANIMATION_PACKAGES.md](./CODE_ANIMATION_PACKAGES.md) | Versioned portable Code Animation source/brief packages and non-executing validation || [ARCHITECTURE.md](./ARCHITECTURE.md) | System design: React client, Express server, PM2 satellites, PostgreSQL + `data/` files || [features/catalog-ingest.md](./features/catalog-ingest.md) | Catalog extraction graph, context budgets, coverage, and review draft contract |diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 78a142e9d4..bccc8d41e9 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -710,3 +710,7 @@ originals and is distinct from space reclamation.### Media prompt examinations`media_prompt_examinations` is db-primary, machine-local history of explicit media analyses. Each immutable UUID record retains the source kind and filename/video ID, both requested prompts and negatives, rationale, and provider/model attribution. Source references are descriptive locators, not foreign keys: examinations remain usable after source media deletion. No binary data or credentials are stored. Lists are paginated and details loaded on demand. PostgreSQL dumps cover the records; migration 418 registers additive boot DDL with no seed or backfill. The JSON adapter is only for development/tests. No federation is added.++### SuperCollider runtime evidence++`data/supercollider/` is `ephemeral-file`: `runtime-evidence.json` caches the last synthetic render probe for the managed SuperCollider image (bound to this machine's local image id, runtime version and containment policy), and `jobs/` holds in-flight probe/render scratch that each run removes. Nothing in it relates to other records, needs search, or federates. Setup re-derives it, so it is excluded from backups (`/supercollider/`) and purgeable from the Data Manager. See [SUPERCOLLIDER.md](./SUPERCOLLIDER.md).diff --git a/docs/SUPERCOLLIDER.md b/docs/SUPERCOLLIDER.mdnew file mode 100644index 0000000000..6fd35d26f5--- /dev/null+++ b/docs/SUPERCOLLIDER.md@@ -0,0 +1,113 @@+# SuperCollider runtime++PortOS can render [SuperCollider](https://supercollider.github.io/) source offline for the Music Designer. Generated `.scd` code is untrusted: `sclang` can run shell commands and load startup files. PortOS therefore compiles and renders it only inside a disposable, locked-down Docker container built from a PortOS-owned recipe. There is no native fallback. Design record: [ADR 2026-10-01](./decisions/2026-10-01-supercollider-code-audio.md), epic #9407.++This page covers the managed runtime: the image, its setup command and its readiness contract.++## Prerequisites++- **Docker running Linux containers** on an `amd64` or `arm64` host: Docker Desktop (macOS, Windows) or Docker Engine (Linux). PortOS never installs, starts or reconfigures Docker. A missing or stopped engine is reported as unavailable, with the next step to take.+- **Disk and time, once.** The image is compiled from source on your machine. Plan for 10–30 minutes of build time and a few hundred MB for the final image, plus Docker's build cache for the compiler toolchain (reclaimable with `docker builder prune`). Renders do not keep a daemon running. Each render starts a container, which exits when the render finishes.++## Setup++```bash+npm run setup:supercollider # show status, offer to build+npm run setup:supercollider -- --yes # build + verify without asking+npm run setup:supercollider -- --yes --rebuild # repair: rebuild every layer, re-verify+npm run setup:supercollider -- --verbose # stream the full docker build log+npm run setup:supercollider -- --status --json # machine-readable status (never builds)+```++Setup is explicit and idempotent:++1. It checks Docker. If Docker is missing, stopped, serving Windows containers or running on an unsupported architecture, setup stops there.+2. It builds `portos-supercollider:<runtime version>` only when the image is missing, was built from a different recipe, or `--rebuild` was passed. Without `--yes` it asks first, and in a non-interactive shell it declines.+3. It runs the **synthetic render probe** when no current passing result exists. The probe renders a stock-UGen SynthDef through a non-realtime score for 2 s at 48 kHz stereo. It runs under exactly the containment that real renders use. PortOS then decodes and measures the WAV it wrote.++When the image is current and the probe evidence is current and passing, a second run does neither step. Setup and status never call an AI provider, and nothing here runs when the server boots.++By default, build output shows only the step headers. If a step fails, the failure message includes a bounded tail of the build log.++### Exit codes++| Code | Meaning |+|---|---|+| 0 | Ready (or `--status` printed) |+| 1 | Unexpected error, including a bad option |+| 2 | Docker unavailable (missing, stopped, Windows containers, unsupported architecture) |+| 3 | Build needed but not approved (no `--yes`, or answered no) |+| 4 | Image build failed |+| 5 | Synthetic render probe failed |++## Readiness states++`--status --json` and `getSuperColliderStatus()` return `{ state, ready, message, action, docker, image, runtime, smoke }`:++| `state` | Meaning |+|---|---|+| `docker-missing` | No docker CLI found |+| `docker-stopped` | CLI present, engine not answering (`docker.error` says why) |+| `docker-unsupported` | Engine serves non-Linux containers or an unsupported architecture |+| `image-missing` | The image has not been built on this machine |+| `image-stale` | The image was built for another runtime version or recipe |+| `unverified` | The image is current, but no probe result matches it |+| `smoke-failed` | The current probe failed (`smoke.error`) |+| `ready` | Current image plus a current passing probe |++The probe evidence (`smoke`) records the image id, runtime version, policy version and policy fingerprint, the Docker platform, and the measured audio. Its duration, channels, sample rate, peak and RMS are measured from the decoded WAV, not taken from the score. Evidence is **current** only when all four identifiers match. Any of these makes earlier evidence stale until setup runs again:++- rebuilding the image,+- bumping the runtime version,+- editing the recipe,+- changing the containment arguments or the probe.++Status reads the cached evidence and never renders.++Evidence is stored in `data/supercollider/runtime-evidence.json`. It is machine-local, excluded from backups, and safe to delete; setup recreates it.++## The image++The recipe lives in `docker/supercollider/`. See its `NOTICE.md` for license and source notices.++- SuperCollider **3.14.1** is built from the official release source tarball, verified by SHA-256. The build is headless: no Qt GUI or IDE, no supernova, no X11, Avahi, HID or Ableton Link. It includes `sclang`, `scsynth`, the stock class library and the stock server plugins. Quarks and third-party plugins are not included.+- The base is Debian `trixie` slim, pinned by digest. All Debian packages come from `snapshot.debian.org` at the base image's own date, so a rebuild installs the same package versions.+- `sclang` loads only the stock class library (`excludeDefaultPaths`). System and user Extensions are never on its path.+- SuperCollider is GPL-3.0-or-later. Its license text, authors list and source reference are installed under `/usr/local/share/doc/supercollider/` in the image.++The image is stamped with two labels: the runtime version (`SUPERCOLLIDER_RUNTIME_VERSION`) and a hash of the recipe directory. A test fails if the Dockerfile's pinned SuperCollider version, its source hash in `NOTICE.md`, and the runtime constants disagree. **Bump `SUPERCOLLIDER_RUNTIME_VERSION` with any pin change.**++## Containment policy++`buildSuperColliderRunArgs()` in `server/lib/superColliderRuntime.js` is the one definition of the container boundary. The probe and real renders both use it:++- `--network none`, `--cap-drop ALL`, `no-new-privileges`, `--read-only` root filesystem+- a non-root user: the host process's own uid:gid, or `nobody` when the host runs as root or has no POSIX ids+- CPU, memory (swap disabled), PID and per-file-size limits; core dumps disabled+- a private `tmpfs` home and temp directory, and an environment of explicit values only (the server's own variables and credentials never reach the container)+- the frozen source directory mounted read-only, and one job-private output directory as the only writable mount; no Docker socket+- `--pull never`, so a missing local image is never fetched from a registry by name+- `--init` to reap the `scsynth` process that `sclang` spawns++The runner (`runSuperColliderContainer`) enforces a wall-time limit and cancellation. It always runs `docker rm --force` afterwards, because killing the docker CLI does not stop a container. Removing the container removes every process inside it. Files the container writes are read back only if they are regular files within the size limit (`readContainedOutput`). A symlink in the output directory cannot point the host at its own files.++## Platform evidence++The recipe targets Linux `amd64` and `arm64` Docker engines. Readiness is per machine: a host is `ready` only after the probe has passed on that host's engine with the current image. The probe result records the engine version, OS and architecture, so the evidence names the platform it was proven on. Any other configuration stays visibly unavailable.++As of this change, the recipe has not been built in CI. Docker was not available on the machine where it was authored. The first successful `npm run setup:supercollider -- --yes` on each architecture provides the evidence. Record the outcome in the epic (#9407).++## Troubleshooting++- **Build fails fetching packages**: `snapshot.debian.org` is occasionally slow or rate-limited. Apt retries five times. Re-run setup; Docker reuses completed layers.+- **Build fails downloading the SuperCollider source, or the checksum fails**: the GitHub release asset was unreachable or altered. The build stops at the checksum rather than compiling unverified source.+- **`smoke-failed`**: read `smoke.error`, then try `npm run setup:supercollider -- --yes --rebuild`, which rebuilds without the layer cache.+- **`docker-stopped` right after starting Docker Desktop**: the engine can take a minute to come up. Re-run once it reports running.++## For the render service and UI++Import the contract rather than re-deriving it:++- `server/lib/superColliderRuntime.js`: version and policy constants, `SUPERCOLLIDER_RENDER_FORMAT`, `SUPERCOLLIDER_CONTAINER_LIMITS`, `SUPERCOLLIDER_CONTAINER_LABEL` (for orphan sweeps), `buildSuperColliderRunArgs`, `evaluateSuperColliderStatus`+- `server/services/superColliderRuntime.js`: `getSuperColliderStatus`, `setupSuperColliderRuntime` (concurrent calls share one run), `runSuperColliderContainer`, `readContainedOutput`+- `server/lib/wavAudioFile.js`: `measureWavAudio` for decoded duration, channel, rate, level and non-finite checksdiff --git a/package.json b/package.jsonindex 55a336e865..36feafe2b4 100644--- a/package.json+++ b/package.json@@ -35,6 +35,7 @@"test:db": "npm run test:db --prefix server","setup:llm": "node scripts/setup-llm.js","setup:motion": "node scripts/setup-motion.js",+ "setup:supercollider": "node scripts/setup-supercollider.js","setup:browser": "node scripts/setup-browser.js","setup:facetime": "node scripts/setup-facetime.js","setup:remote-desktop": "node scripts/setup-remote-desktop.js",diff --git a/scripts/setup-supercollider.js b/scripts/setup-supercollider.jsnew file mode 100644index 0000000000..90d50b9214--- /dev/null+++ b/scripts/setup-supercollider.js@@ -0,0 +1,115 @@+#!/usr/bin/env node++/**+ * SuperCollider Runtime Setup+ *+ * Builds the PortOS-owned SuperCollider image (sclang + scsynth + the stock+ * class library and plugins, from the pinned recipe in docker/supercollider/)+ * and proves it with a synthetic offline render under the same containment the+ * Music Designer uses. Docker must already be installed and running — this+ * never installs or reconfigures Docker, and never calls an AI provider.+ *+ * Usage:+ * npm run setup:supercollider # status + offer to build+ * npm run setup:supercollider -- --yes # build/verify without asking+ * npm run setup:supercollider -- --yes --rebuild # repair: rebuild every layer, re-probe+ * npm run setup:supercollider -- --verbose # stream the full docker build log+ * npm run setup:supercollider -- --status [--json]+ *+ * Idempotent: a built, current image is not rebuilt, and current passing probe+ * evidence is not re-run. Exit codes: see SETUP_EXIT_CODES.+ */++import { createInterface } from 'node:readline';+import { isDirectlyInvoked } from './lib/directInvocation.js';+import { getSuperColliderStatus, setupSuperColliderRuntime } from '../server/services/superColliderRuntime.js';++export const SETUP_EXIT_CODES = Object.freeze({+ ready: 0,+ failed: 1,+ 'docker-unavailable': 2,+ declined: 3,+ 'build-failed': 4,+ 'smoke-failed': 5,+});++export function parseSuperColliderSetupArgs(argv) {+ const options = { yes: false, status: false, json: false, rebuild: false, verbose: false };+ const flags = { '--yes': 'yes', '-y': 'yes', '--status': 'status', '--json': 'json', '--rebuild': 'rebuild', '--verbose': 'verbose' };+ for (const arg of argv) {+ if (!flags[arg]) throw new Error(`Unknown option: ${arg} (known: ${Object.keys(flags).join(', ')})`);+ options[flags[arg]] = true;+ }+ if (options.json && !options.status) throw new Error('--json is only valid with --status');+ return options;+}++/** The exit code for a setup outcome; anything unrecognized is a generic failure. */+export const exitCodeForOutcome = (outcome) => SETUP_EXIT_CODES[outcome] ?? SETUP_EXIT_CODES.failed;++// Build output is thousands of compiler lines; by default show only the step+// headers (BuildKit `#N [stage x/y] …`, classic builder `Step x/y : …`).+export const isBuildStepLine = (line) => /^#\d+ \[[^\]]+\]/.test(line) || /^Step \d+\/\d+ :/.test(line);++const mark = (ok) => (ok ? '✅' : '❌');++function printStatus(status) {+ const { docker, image, smoke, runtime } = status;+ const dockerLine = !docker.installed ? 'not installed'+ : !docker.running ? `installed, engine not reachable${docker.error ? ` (${docker.error})` : ''}`+ : `${docker.serverVersion} (${docker.os}/${docker.arch})`;+ console.log(`${mark(docker.running)} Docker: ${dockerLine}`);+ const imageLine = !image ? `${runtime.image} not built`+ : `${runtime.image}${image.sizeBytes ? ` (${Math.round(image.sizeBytes / 1e6)} MB)` : ''}${image.current ? '' : ` — stale (built for ${image.runtimeVersion || 'an unknown version'})`}`;+ console.log(`${mark(image?.current)} Image: ${imageLine}`);+ const smokeLine = !smoke ? 'not run'+ : !smoke.current ? `stale (last run ${smoke.checkedAt} against a different image/runtime/policy)`+ : smoke.ok ? `passed ${smoke.checkedAt} — ${smoke.measurement.durationMs} ms, ${smoke.measurement.channels} ch, ${smoke.measurement.sampleRate} Hz, peak ${smoke.measurement.peak}`+ : `failed ${smoke.checkedAt}: ${smoke.error}`;+ console.log(`${mark(smoke?.current && smoke.ok)} Render probe: ${smokeLine}`);+ const log = status.ready ? console.log : console.warn;+ log(`${status.ready ? '🎛️' : '⚠️'} ${status.message}`);+ if (status.action) log(`👉 ${status.action}`);+}++function ask(question) {+ const rl = createInterface({ input: process.stdin, output: process.stdout });+ return new Promise(resolve => rl.question(question, answer => { rl.close(); resolve(/^y(es)?$/i.test(answer.trim())); }));+}++async function confirmBuild({ yes }) {+ if (yes) return true;+ const question = '📦 Build the SuperCollider image now? It compiles SuperCollider from source inside Docker — expect 10–30 minutes, a few hundred MB of image and more for build cache. [y/N] ';+ if (process.stdin.isTTY && await ask(question)) return true;+ console.warn('⚠️ Skipped the image build. Re-run with --yes to build it.');+ return false;+}++async function main() {+ const options = parseSuperColliderSetupArgs(process.argv.slice(2));+ if (options.status) {+ const status = await getSuperColliderStatus();+ if (options.json) console.log(JSON.stringify(status, null, 2));+ else printStatus(status);+ return;+ }+ console.log('🎛️ SuperCollider runtime setup');+ const result = await setupSuperColliderRuntime({+ rebuild: options.rebuild,+ confirmBuild: () => confirmBuild(options),+ onLine: (line) => { if (options.verbose || isBuildStepLine(line)) console.log(` ${line}`); },+ });+ if (result.built) console.log('✅ Image built');+ else if (result.outcome === 'ready' || result.outcome === 'smoke-failed') console.log('✅ Image already current — skipped the build');+ if (result.probed) console.log(`${result.status.ready ? '✅' : '❌'} Synthetic render probe ${result.status.ready ? 'passed' : 'failed'}`);+ if (result.outcome === 'build-failed') console.error(`❌ Image build failed: ${result.error}`);+ printStatus(result.status);+ process.exitCode = exitCodeForOutcome(result.outcome);+}++if (isDirectlyInvoked(import.meta.url)) {+ main().catch(error => {+ console.error(`❌ SuperCollider setup failed: ${error.message}`);+ process.exitCode = SETUP_EXIT_CODES.failed;+ });+}diff --git a/scripts/setup-supercollider.test.js b/scripts/setup-supercollider.test.jsnew file mode 100644index 0000000000..20c278047c--- /dev/null+++ b/scripts/setup-supercollider.test.js@@ -0,0 +1,25 @@+import { describe, expect, it } from 'vitest';+import { exitCodeForOutcome, isBuildStepLine, parseSuperColliderSetupArgs } from './setup-supercollider.js';++describe('SuperCollider setup CLI', () => {+ it('accepts only the documented flags', () => {+ expect(parseSuperColliderSetupArgs(['--yes', '--rebuild'])).toMatchObject({ yes: true, rebuild: true, status: false });+ expect(parseSuperColliderSetupArgs(['--status', '--json'])).toMatchObject({ status: true, json: true });+ expect(() => parseSuperColliderSetupArgs(['--force'])).toThrow('Unknown option');+ expect(() => parseSuperColliderSetupArgs(['--json'])).toThrow('only valid with --status');+ });++ it('gives each failure its own non-zero exit code', () => {+ const outcomes = ['docker-unavailable', 'declined', 'build-failed', 'smoke-failed'];+ expect(exitCodeForOutcome('ready')).toBe(0);+ expect(new Set(outcomes.map(exitCodeForOutcome)).size).toBe(outcomes.length);+ expect(outcomes.map(exitCodeForOutcome).every((code) => code > 1)).toBe(true);+ expect(exitCodeForOutcome('something-new')).toBe(1);+ });++ it('keeps default build output to step headers', () => {+ expect(isBuildStepLine('#7 [build 3/5] RUN set -eux; cmake -S /src -B /build')).toBe(true);+ expect(isBuildStepLine('Step 4/12 : RUN apt-get update')).toBe(true);+ expect(isBuildStepLine('#7 412.3 [ 61%] Building CXX object server/plugins/BinaryOpUGens.cpp.o')).toBe(false);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 781a08685c..07dbfcdf50 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -535,7 +535,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `chiptuneScore.js` | Chiptune score contract (#2911): `chiptuneScoreSchema` (Zod) + `sanitizeChiptuneScore`, `buildScoreEvents` — the pattern/order → absolute-time flatten mirrored by `client/src/lib/chiptunePlayback.js`. || `musicVideoLayers.js` | Music Video per-scene visual layers (#8985): `MUSIC_VIDEO_VISUAL_LAYERS` (`footage`/`still`/`card`), `MUSIC_VIDEO_STILL_MOVES` (`hold`/`push`/`pan`), `sceneVisualLayer(scene, { layered })` (only a composed render honors a still/card), `sceneHasAuthoredSpan`, and `sceneRenderReady(scene, { layered })`. Pure leaf shared by `services/musicVideo/render.js` and the client board (`client/src/lib/musicVideoLayers.js`). || `pitchMath.js` | Dependency-free scientific-pitch math shared by the LLM-authored music formats on both runtimes: `pitchToMidi("C4")` → 60 (null when unparseable) and `midiToFreq(69)` → 440. |-| `wavAudioFile.js` | `writeWavAudioFile(wav, dir, basename)` — land a synthesized WAV Buffer as `<basename>.ogg` via the system ffmpeg, falling back to `<basename>.wav` (and dropping a stale `.ogg`) when ffmpeg is missing or the encode fails; resolves to the filename used. Shared by the chiptune and drawn-waveform renderers and the code-engine take upload. `wavDurationMs(buffer)` reads a PCM WAV's duration from its RIFF header (0 for anything that is not a parseable WAV). |+| `wavAudioFile.js` | `writeWavAudioFile(wav, dir, basename)` — land a synthesized WAV Buffer as `<basename>.ogg` via the system ffmpeg, falling back to `<basename>.wav` (and dropping a stale `.ogg`) when ffmpeg is missing or the encode fails; resolves to the filename used. Shared by the chiptune and drawn-waveform renderers and the code-engine take upload. `wavDurationMs(buffer)` reads a PCM WAV's duration from its RIFF header (0 for anything that is not a parseable WAV). `measureWavAudio(buffer)` decodes PCM 16/24/32-bit or float 32/64 (EXTENSIBLE included) into `{ channels, sampleRate, frames, durationMs, peak, rms, nonFinite }` so native renders are judged by their samples (null when undecodable). |+| `superColliderRuntime.js` | Managed SuperCollider runtime contract (#9412), pure: image/runtime/policy version constants, `buildSuperColliderRunArgs` (the one contained `docker run` for untrusted `sclang` source: no network/caps, read-only root, limits, ro input, private output), `buildSuperColliderBuildArgs`, the shipped synthetic probe, `evaluateSuperColliderStatus` (docker-missing … ready, with stale image/evidence invalidation). I/O lives in `services/superColliderRuntime.js`. || `waveSketch.js` | Drawn-waveform music contract v1 (browser-safe; new paintings are v2 — see `paintedCanvas.js`): the LLM draws single-cycle `shapes` (point polylines in [-1, 1]) played by `voices` as timed strokes with optional glide, shape morph, and drawn envelope, plus a whole-piece `contour`. `normalizeWaveSketch(raw)` is the one lenient, idempotent validator (null when nothing playable survives); `synthesizeWaveSketch(sketch)` → deterministic mono PCM (seeded noise), so the client preview and server render match; `pcmPeaks(pcm, columns)` for drawing it; `WAVE_SKETCH_LIMITS`. `normalizeWaveSketch` dispatches a `version: 2` sketch to `normalizePaintedCanvas`; `synthesizeSketchChannels(sketch)` renders either version to its channel list; `isPaintedCanvas(sketch)`. || `paintedCanvas.js` | Painted-spectrogram canvas, wave sketch v2 (#8464, browser-safe): stereo time × log-frequency canvas painted with strokes (`path` keyframes `{t, hz, a}`, per-keyframe `overtones`, noise `width`, `pan`), plus optional `sections` and tempo grid. `normalizePaintedCanvas(raw, { durationSec, limits })` is the lenient idempotent validator; `synthesizePaintedCanvas(canvas)` → deterministic `[left, right]` PCM using only IEEE-exact math (series sine table, log2/exp2), so server WAV and browser preview match on any engine; render work bounded by `PAINTED_CANVAS_LIMITS.WORK_MAX_PARTIAL_SEC`; `paintedCanvasStats(canvas)` → stroke/keyframe/noise/work totals. || `spectrogramImage.js` | `spectrogramPixels(pcm, { sampleRate, width, height, minHz, maxHz })` → raw RGB pixels of a log-frequency STFT spectrogram (80 dB range) — the picture a model gets of its own painted canvas in the review pass (#8464). Pure; the caller encodes the PNG. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 95c9ca420d..940b775f8e 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -491,6 +491,7 @@ export * from './chiptuneScore.js';export * from './pitchMath.js';export * from './musicVideoLayers.js';export * from './wavAudioFile.js';+export * from './superColliderRuntime.js';export * from './waveSketch.js';export * from './paintedCanvas.js';export * from './spectrogramImage.js';diff --git a/server/lib/superColliderRuntime.js b/server/lib/superColliderRuntime.jsnew file mode 100644index 0000000000..77a88ae28f--- /dev/null+++ b/server/lib/superColliderRuntime.js@@ -0,0 +1,359 @@+/**+ * The managed SuperCollider runtime contract (#9412, epic #9407) — pure: no+ * filesystem, no docker, no clock. `services/superColliderRuntime.js` does the+ * I/O; the render service and the Music Designer UI import the constants and+ * `evaluateSuperColliderStatus` from here so every surface agrees on what+ * "ready" means.+ *+ * Three things decide readiness, and each invalidates the next:+ * 1. a reachable Linux Docker engine on a supported architecture,+ * 2. the PortOS-built image, stamped with the runtime version and the hash of+ * the checked-in recipe (`docker/supercollider/`) it was built from,+ * 3. passing synthetic-render evidence recorded against THAT image id, this+ * runtime version and this containment policy.+ * A recipe edit, a runtime bump, a policy change or a rebuilt image therefore+ * voids older evidence instead of letting a stale "ready" stand.+ *+ * Generated SuperCollider source is untrusted: `sclang` can run shell commands+ * and load startup files. `buildSuperColliderRunArgs` is the ONE place the+ * container boundary is spelled out, so the readiness probe and real renders+ * run under the same policy.+ */++import { createHash } from 'crypto';++export const SUPERCOLLIDER_VERSION = '3.14.1';+/** Bump with any change to the recipe's pinned inputs (its test checks the Dockerfile agrees). */+export const SUPERCOLLIDER_RUNTIME_VERSION = `${SUPERCOLLIDER_VERSION}-portos.1`;+/** Bump when the containment policy or synthetic probe changes meaning; the fingerprint below also catches unbumped edits. */+export const SUPERCOLLIDER_POLICY_VERSION = 1;++export const SUPERCOLLIDER_IMAGE_REPOSITORY = 'portos-supercollider';+export const SUPERCOLLIDER_IMAGE = `${SUPERCOLLIDER_IMAGE_REPOSITORY}:${SUPERCOLLIDER_RUNTIME_VERSION}`;+/** Recipe directory, relative to the PortOS code root. */+export const SUPERCOLLIDER_RECIPE_DIR = 'docker/supercollider';+export const SUPERCOLLIDER_SETUP_COMMAND = 'npm run setup:supercollider -- --yes';++export const SUPERCOLLIDER_IMAGE_LABELS = Object.freeze({+ runtimeVersion: 'org.portos.supercollider.runtime-version',+ recipeHash: 'org.portos.supercollider.recipe-sha256',+});+/** Every render container carries this label, so an orphan sweep can find them. */+export const SUPERCOLLIDER_CONTAINER_LABEL = 'org.portos.supercollider.render';++/** Docker server architectures the recipe builds for; anything else is visibly unsupported. */+export const SUPERCOLLIDER_SUPPORTED_ARCHITECTURES = Object.freeze(['amd64', 'arm64']);++/** The fixed render format the trusted runner supplies (generated source never chooses it). */+export const SUPERCOLLIDER_RENDER_FORMAT = Object.freeze({ sampleRate: 48_000, channels: 2 });++export const SUPERCOLLIDER_CONTAINER_LIMITS = Object.freeze({+ cpus: '2',+ memory: '1g',+ pids: 64,+ tmpfsBytes: 64 * 1024 * 1024,+ // Per-file write ceiling (RLIMIT_FSIZE): a 120 s stereo 48 kHz float32 render is ~46 MB.+ maxFileBytes: 128 * 1024 * 1024,+ wallTimeoutMs: 180_000,+});++/** In-container paths: frozen source (read-only), job-private output, stock-only class library config. */+export const SUPERCOLLIDER_CONTAINER_PATHS = Object.freeze({+ input: '/in',+ output: '/out',+ libraryConfig: '/opt/portos/sclang_conf.yaml',+ home: '/tmp',+});++/** Container user when the host has no POSIX uid (Windows) or runs as root: `nobody`. */+export const SUPERCOLLIDER_FALLBACK_USER = '65534:65534';++const SCRIPT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}\.scd$/;+const CONTAINER_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;++// `--mount` is a comma-separated key=value list, so a comma (or a control+// character) in a host path would let the path inject mount options.+function assertMountablePath(path, label) {+ if (typeof path !== 'string' || !path) throw new Error(`${label} is required`);+ if (!/^(\/|[A-Za-z]:[\\/])/.test(path)) throw new Error(`${label} must be absolute`);+ if (/[,\0-\x1f"]/.test(path)) throw new Error(`${label} contains a character docker cannot mount`);+}++/**+ * The container user for a host process: its own uid:gid, so bind-mounted+ * output stays owned by the PortOS user, except root (never run generated code+ * as uid 0) and hosts without POSIX ids.+ */+export function superColliderContainerUser({ uid, gid } = {}) {+ if (!Number.isInteger(uid) || !Number.isInteger(gid) || uid === 0) return SUPERCOLLIDER_FALLBACK_USER;+ return `${uid}:${gid}`;+}++/**+ * `docker run` argv for ONE contained `sclang` execution of `/in/<script>`.+ *+ * Boundary: no network, no capabilities, no privilege escalation, read-only+ * root, private tmpfs home/temp, CPU/memory/PID/file-size limits, a non-root+ * user, an environment of explicit values only (the docker CLI never forwards+ * the server's own variables), no Docker socket, the frozen input directory+ * read-only and only the job output directory writable. `--pull never` keeps a+ * missing local image from being fetched by name from a registry; `--init`+ * reaps the `scsynth` that `sclang` spawns; `--rm` plus the caller's+ * `docker rm -f <name>` remove the whole container — every descendant+ * included — on exit, timeout or cancel. `scriptArgs` reach the script as+ * `thisProcess.argv`; they are argv entries, never shell text.+ */+export function buildSuperColliderRunArgs({+ image = SUPERCOLLIDER_IMAGE,+ containerName,+ inputDir,+ outputDir,+ script = 'score.scd',+ scriptArgs = [],+ user = SUPERCOLLIDER_FALLBACK_USER,+ limits = SUPERCOLLIDER_CONTAINER_LIMITS,+}) {+ if (!CONTAINER_NAME_RE.test(String(containerName ?? ''))) throw new Error('containerName must be a docker container name');+ if (!SCRIPT_NAME_RE.test(String(script))) throw new Error('script must be a plain .scd file name');+ if (!/^\d+:\d+$/.test(String(user)) || String(user).startsWith('0:')) throw new Error('user must be a non-root uid:gid');+ assertMountablePath(inputDir, 'inputDir');+ assertMountablePath(outputDir, 'outputDir');+ const argv = scriptArgs.map((arg) => {+ const text = String(arg);+ if (text.includes('\0')) throw new Error('script arguments cannot contain NUL');+ return text;+ });+ const { home, input, output, libraryConfig } = SUPERCOLLIDER_CONTAINER_PATHS;+ return [+ 'run', '--rm', '--pull', 'never', '--init',+ '--name', containerName,+ '--label', `${SUPERCOLLIDER_CONTAINER_LABEL}=1`,+ '--network', 'none',+ '--cap-drop', 'ALL',+ '--security-opt', 'no-new-privileges',+ '--read-only',+ '--user', user,+ '--cpus', limits.cpus,+ '--memory', limits.memory,+ '--memory-swap', limits.memory,+ '--pids-limit', String(limits.pids),+ '--ulimit', `fsize=${limits.maxFileBytes}:${limits.maxFileBytes}`,+ '--ulimit', 'core=0:0',+ '--tmpfs', `${home}:rw,nosuid,nodev,noexec,size=${limits.tmpfsBytes},mode=1777`,+ '--env', `HOME=${home}`,+ '--env', `XDG_CONFIG_HOME=${home}/.config`,+ '--env', `XDG_DATA_HOME=${home}/.local/share`,+ '--env', `XDG_CACHE_HOME=${home}/.cache`,+ '--env', 'LANG=C.UTF-8',+ '--workdir', home,+ '--mount', `type=bind,source=${inputDir},target=${input},readonly`,+ '--mount', `type=bind,source=${outputDir},target=${output}`,+ '--entrypoint', 'sclang',+ image,+ '-l', libraryConfig,+ `${input}/${script}`,+ ...argv,+ ];+}++/**+ * The shipped synthetic readiness probe: a stock-UGen SynthDef rendered+ * through a non-realtime Score at the runner-supplied path, duration and rate+ * (`thisProcess.argv`). It writes distinct tones per channel, so evidence shows+ * both channels carry audio. Any error exits non-zero instead of leaving+ * `sclang` idling until the wall-time limit.+ */+export const SUPERCOLLIDER_SMOKE_SOURCE = `var argv = thisProcess.argv;+var outPath = argv[0];+var duration = argv[1].asFloat;+var sampleRate = argv[2].asInteger;+{+ var def = SynthDef(\\portosSmoke, { |out = 0, freq = 220, amp = 0.25|+ var env = EnvGen.kr(Env.linen(0.05, duration - 0.3, 0.2, amp));+ Out.ar(out, SinOsc.ar([freq, freq * 1.5]) * env);+ });+ var options = ServerOptions.new.numOutputBusChannels_(2).numInputBusChannels_(0);+ Score([+ [0.0, ['/d_recv', def.asBytes]],+ [0.0, ['/s_new', \\portosSmoke, 1000, 0, 0, \\freq, 220]],+ [duration, ['/n_free', 1000]]+ ]).recordNRT(nil, outPath, nil, sampleRate, "WAV", "int16", options, "", duration, { |exitCode| exitCode.exit });+}.try { |error| error.reportError; 1.exit };+`;++/** What the probe renders, and what its measured output must show. */+export const SUPERCOLLIDER_SMOKE = Object.freeze({+ script: 'smoke.scd',+ output: 'smoke.wav',+ durationSec: 2,+ timeoutMs: 120_000,+ // Duration tolerance covers NRT block rounding; -40 dBFS is unmistakably not silence.+ durationToleranceMs: 50,+ minPeak: 0.01,+});++const sha256 = (text) => createHash('sha256').update(text).digest('hex');++/**+ * Fingerprint of the containment policy plus the probe, recorded with each+ * smoke result. Evidence from a different fingerprint is stale even if someone+ * edited the run args without bumping SUPERCOLLIDER_POLICY_VERSION.+ */+export const SUPERCOLLIDER_POLICY_FINGERPRINT = sha256(JSON.stringify({+ version: SUPERCOLLIDER_POLICY_VERSION,+ args: buildSuperColliderRunArgs({ containerName: 'fingerprint', inputDir: '/in-host', outputDir: '/out-host' }),+ smoke: SUPERCOLLIDER_SMOKE_SOURCE,+ probe: SUPERCOLLIDER_SMOKE,+ format: SUPERCOLLIDER_RENDER_FORMAT,+}));++/**+ * SHA-256 over the recipe files, name-sorted with line endings normalized, so a+ * Windows CRLF checkout of the same recipe hashes the same.+ * @param {{name: string, content: string}[]} files+ */+export function hashSuperColliderRecipe(files) {+ const hash = createHash('sha256');+ for (const { name, content } of [...files].sort((a, b) => a.name.localeCompare(b.name))) {+ hash.update(`${name}\0${String(content).replace(/\r\n?/g, '\n')}\0`);+ }+ return hash.digest('hex');+}++/**+ * `docker build` argv that stamps the runtime version and recipe hash on the+ * image. `noCache` is the repair path: rebuild every layer instead of reusing+ * a cached (possibly broken) one.+ */+export function buildSuperColliderBuildArgs({ recipeDir, recipeHash, noCache = false }) {+ return [+ 'build',+ ...(noCache ? ['--no-cache'] : []),+ '--tag', SUPERCOLLIDER_IMAGE,+ '--label', `${SUPERCOLLIDER_IMAGE_LABELS.runtimeVersion}=${SUPERCOLLIDER_RUNTIME_VERSION}`,+ '--label', `${SUPERCOLLIDER_IMAGE_LABELS.recipeHash}=${recipeHash}`,+ recipeDir,+ ];+}++/** Parse `docker version --format '{{json .}}'` → `{ clientVersion, serverVersion, os, arch }` (nulls when absent). */+export function parseDockerVersion(stdout) {+ let parsed = null;+ try { parsed = JSON.parse(String(stdout || '').trim()); } catch { parsed = null; }+ return {+ clientVersion: parsed?.Client?.Version ?? null,+ serverVersion: parsed?.Server?.Version ?? null,+ os: parsed?.Server?.Os ?? null,+ arch: parsed?.Server?.Arch ?? null,+ };+}++/** Parse `docker image inspect --format '{{json .}}'` → the image fields status needs, or null. */+export function parseDockerImage(stdout) {+ let parsed = null;+ try { parsed = JSON.parse(String(stdout || '').trim()); } catch { return null; }+ if (Array.isArray(parsed)) parsed = parsed[0];+ if (!parsed?.Id) return null;+ const labels = parsed.Config?.Labels ?? {};+ return {+ id: parsed.Id,+ created: parsed.Created ?? null,+ sizeBytes: Number.isFinite(parsed.Size) ? parsed.Size : null,+ os: parsed.Os ?? null,+ arch: parsed.Architecture ?? null,+ runtimeVersion: labels[SUPERCOLLIDER_IMAGE_LABELS.runtimeVersion] ?? null,+ recipeHash: labels[SUPERCOLLIDER_IMAGE_LABELS.recipeHash] ?? null,+ };+}++/**+ * Judge a measured probe render (`measureWavAudio` output) against the fixed+ * format and duration. Returns null when it passes, else the reason.+ */+export function superColliderSmokeFailure(measurement, { durationSec = SUPERCOLLIDER_SMOKE.durationSec } = {}) {+ if (!measurement) return 'the probe wrote no readable WAV';+ const { sampleRate, channels } = SUPERCOLLIDER_RENDER_FORMAT;+ if (measurement.channels !== channels) return `expected ${channels} channels, got ${measurement.channels}`;+ if (measurement.sampleRate !== sampleRate) return `expected ${sampleRate} Hz, got ${measurement.sampleRate} Hz`;+ if (Math.abs(measurement.durationMs - durationSec * 1000) > SUPERCOLLIDER_SMOKE.durationToleranceMs) {+ return `expected ${durationSec * 1000} ms of audio, got ${measurement.durationMs} ms`;+ }+ if (measurement.nonFinite > 0) return `${measurement.nonFinite} non-finite samples`;+ if (measurement.peak < SUPERCOLLIDER_SMOKE.minPeak) return 'the render is silent';+ return null;+}++/** Does recorded evidence describe THIS runtime, policy and image? */+function isSuperColliderEvidenceCurrent(evidence, image) {+ return Boolean(evidence && image?.id+ && evidence.runtimeVersion === SUPERCOLLIDER_RUNTIME_VERSION+ && evidence.policyVersion === SUPERCOLLIDER_POLICY_VERSION+ && evidence.policyFingerprint === SUPERCOLLIDER_POLICY_FINGERPRINT+ && evidence.imageId === image.id);+}++/**+ * The one readiness verdict: `{ state, ready, message, action, docker, image,+ * runtime, smoke }`. `state` is one of docker-missing, docker-stopped,+ * docker-unsupported, image-missing, image-stale, unverified, smoke-failed,+ * ready. Status only READS cached evidence — it never builds or renders.+ *+ * @param {object} input+ * @param {{installed: boolean, running: boolean, serverVersion?: string|null, os?: string|null, arch?: string|null, error?: string|null}} input.docker+ * @param {ReturnType<typeof parseDockerImage>} [input.image]+ * @param {object|null} [input.evidence] - the last recorded smoke result+ * @param {string} input.recipeHash - hash of the checked-in recipe+ */+export function evaluateSuperColliderStatus({ docker, image = null, evidence = null, recipeHash }) {+ const imageCurrent = Boolean(image+ && image.runtimeVersion === SUPERCOLLIDER_RUNTIME_VERSION+ && image.recipeHash === recipeHash);+ const evidenceCurrent = imageCurrent && isSuperColliderEvidenceCurrent(evidence, image);+ const verdict = (state, message, action = SUPERCOLLIDER_SETUP_COMMAND) => ({+ state,+ ready: state === 'ready',+ message,+ action: state === 'ready' ? null : action,+ docker,+ image: image ? { ...image, current: imageCurrent } : null,+ runtime: {+ version: SUPERCOLLIDER_RUNTIME_VERSION,+ supercollider: SUPERCOLLIDER_VERSION,+ policyVersion: SUPERCOLLIDER_POLICY_VERSION,+ image: SUPERCOLLIDER_IMAGE,+ },+ smoke: evidence ? { ...evidence, current: evidenceCurrent } : null,+ });++ if (!docker?.installed) {+ return verdict('docker-missing', 'Docker is not installed. Install Docker Desktop (macOS/Windows) or Docker Engine (Linux) and start it — PortOS never installs or reconfigures Docker for you.',+ 'Install and start Docker, then run: ' + SUPERCOLLIDER_SETUP_COMMAND);+ }+ if (!docker.running) {+ return verdict('docker-stopped', `Docker is installed but its engine is not reachable${docker.error ? ` (${docker.error})` : ''}. Start Docker and try again.`,+ 'Start Docker, then run: ' + SUPERCOLLIDER_SETUP_COMMAND);+ }+ if (docker.os !== 'linux') {+ return verdict('docker-unsupported', `Docker is serving ${docker.os || 'unknown'} containers; the SuperCollider runtime needs Linux containers.`,+ 'Switch Docker to Linux containers, then run: ' + SUPERCOLLIDER_SETUP_COMMAND);+ }+ if (!SUPERCOLLIDER_SUPPORTED_ARCHITECTURES.includes(docker.arch)) {+ return verdict('docker-unsupported', `Docker reports architecture ${docker.arch || 'unknown'}; the SuperCollider runtime supports ${SUPERCOLLIDER_SUPPORTED_ARCHITECTURES.join(' and ')}.`, null);+ }+ if (!image) {+ return verdict('image-missing', `The managed SuperCollider ${SUPERCOLLIDER_VERSION} image has not been built on this machine.`);+ }+ if (!imageCurrent) {+ return verdict('image-stale', `The SuperCollider image was built from an older recipe (${image.runtimeVersion || 'unknown version'}); rebuild it for ${SUPERCOLLIDER_RUNTIME_VERSION}.`);+ }+ if (!evidenceCurrent) {+ return verdict('unverified', evidence+ ? 'The last synthetic render probe ran against a different image, runtime or containment policy; re-run setup to verify this one.'+ : 'The SuperCollider image is built but has not passed the synthetic render probe yet.');+ }+ if (!evidence.ok) {+ return verdict('smoke-failed', `The synthetic render probe failed: ${evidence.error || 'unknown error'}.`,+ `${SUPERCOLLIDER_SETUP_COMMAND} --rebuild`);+ }+ return verdict('ready', `SuperCollider ${SUPERCOLLIDER_VERSION} is ready (probe passed ${evidence.checkedAt}).`);+}diff --git a/server/lib/superColliderRuntime.test.js b/server/lib/superColliderRuntime.test.jsnew file mode 100644index 0000000000..d6313e4c8c--- /dev/null+++ b/server/lib/superColliderRuntime.test.js@@ -0,0 +1,123 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'fs';+import { join } from 'path';+import { PATHS } from './paths.js';+import {+ SUPERCOLLIDER_IMAGE,+ SUPERCOLLIDER_POLICY_FINGERPRINT,+ SUPERCOLLIDER_POLICY_VERSION,+ SUPERCOLLIDER_RECIPE_DIR,+ SUPERCOLLIDER_RUNTIME_VERSION,+ SUPERCOLLIDER_VERSION,+ buildSuperColliderRunArgs,+ evaluateSuperColliderStatus,+ hashSuperColliderRecipe,+ superColliderContainerUser,+} from './superColliderRuntime.js';++const recipeFile = (name) => readFileSync(join(PATHS.root, SUPERCOLLIDER_RECIPE_DIR, name), 'utf8');+const runArgs = (overrides = {}) => buildSuperColliderRunArgs({+ containerName: 'portos-sc-test', inputDir: '/srv/jobs/a/in', outputDir: '/srv/jobs/a/out', user: '1000:1000', ...overrides,+});+const flagValues = (args, flag) => args.flatMap((arg, i) => (arg === flag ? [args[i + 1]] : []));++describe('SuperCollider containment policy', () => {+ it('runs generated source with no network, privileges, writable root, host env or docker socket', () => {+ const args = runArgs({ scriptArgs: ['/out/render.wav', 4, 48000] });+ expect(args.slice(0, 3)).toEqual(['run', '--rm', '--pull']);+ expect(flagValues(args, '--pull')).toEqual(['never']);+ expect(flagValues(args, '--network')).toEqual(['none']);+ expect(flagValues(args, '--cap-drop')).toEqual(['ALL']);+ expect(flagValues(args, '--security-opt')).toEqual(['no-new-privileges']);+ expect(args).toContain('--read-only');+ expect(args).toContain('--init');+ expect(flagValues(args, '--user')).toEqual(['1000:1000']);+ for (const flag of ['--cpus', '--memory', '--memory-swap', '--pids-limit']) expect(flagValues(args, flag)).toHaveLength(1);+ // A bare `--env NAME` would forward the server's own value (credentials included).+ expect(flagValues(args, '--env').every((pair) => /^[A-Z_]+=/.test(pair))).toBe(true);+ expect(flagValues(args, '--env')).toContain('HOME=/tmp');+ expect(args.some((arg) => /docker\.sock|privileged|--volume|^-v$/.test(arg))).toBe(false);+ expect(flagValues(args, '--mount')).toEqual([+ 'type=bind,source=/srv/jobs/a/in,target=/in,readonly',+ 'type=bind,source=/srv/jobs/a/out,target=/out',+ ]);+ // Stock-only class library; the script's argv are plain argv entries after it.+ expect(args.slice(args.indexOf(SUPERCOLLIDER_IMAGE))).toEqual([+ SUPERCOLLIDER_IMAGE, '-l', '/opt/portos/sclang_conf.yaml', '/in/score.scd', '/out/render.wav', '4', '48000',+ ]);+ });++ it('refuses inputs that would widen the boundary', () => {+ expect(() => runArgs({ user: '0:0' })).toThrow('non-root');+ expect(() => runArgs({ outputDir: '/srv/out,target=/etc' })).toThrow('cannot mount');+ expect(() => runArgs({ inputDir: 'relative/in' })).toThrow('absolute');+ expect(() => runArgs({ script: '../escape.scd' })).toThrow('plain .scd');+ expect(() => runArgs({ containerName: '--privileged' })).toThrow('container name');+ expect(runArgs({ inputDir: 'C:\\portos\\in' })).toContain('type=bind,source=C:\\portos\\in,target=/in,readonly');+ });++ it('maps the host user, but never runs as root', () => {+ expect(superColliderContainerUser({ uid: 1000, gid: 1000 })).toBe('1000:1000');+ expect(superColliderContainerUser({ uid: 0, gid: 0 })).toBe('65534:65534');+ expect(superColliderContainerUser({})).toBe('65534:65534');+ });+});++describe('SuperCollider recipe pins', () => {+ it('agrees with the runtime constants and pins every input', () => {+ const dockerfile = recipeFile('Dockerfile');+ expect(dockerfile).toContain(`ARG SC_VERSION=${SUPERCOLLIDER_VERSION}\n`);+ expect(SUPERCOLLIDER_RUNTIME_VERSION.startsWith(`${SUPERCOLLIDER_VERSION}-portos.`)).toBe(true);+ const sha = dockerfile.match(/ARG SC_SOURCE_SHA256=([0-9a-f]{64})\n/)?.[1];+ expect(sha).toBeTruthy();+ expect(recipeFile('NOTICE.md')).toContain(sha);+ expect(dockerfile).toMatch(/ARG DEBIAN_IMAGE=debian:[\w.-]+@sha256:[0-9a-f]{64}\n/);+ expect(dockerfile).toMatch(/ARG DEBIAN_SNAPSHOT=\d{8}T\d{6}Z\n/);+ expect(dockerfile).toContain('sha256sum -c');+ expect(recipeFile('sclang_conf.yaml')).toMatch(/excludeDefaultPaths: true/);+ });++ it('hashes a CRLF checkout of the recipe like the LF original', () => {+ const lf = [{ name: 'Dockerfile', content: 'FROM a\nRUN b\n' }, { name: 'NOTICE.md', content: 'x\n' }];+ const crlf = [...lf].reverse().map((file) => ({ ...file, content: file.content.replace(/\n/g, '\r\n') }));+ expect(hashSuperColliderRecipe(crlf)).toBe(hashSuperColliderRecipe(lf));+ expect(hashSuperColliderRecipe([{ name: 'Dockerfile', content: 'FROM c\n' }])).not.toBe(hashSuperColliderRecipe(lf));+ });+});++describe('evaluateSuperColliderStatus', () => {+ const recipeHash = 'recipe-1';+ const docker = { installed: true, running: true, serverVersion: '27.0.0', os: 'linux', arch: 'arm64', error: null };+ const image = { id: 'sha256:image-1', runtimeVersion: SUPERCOLLIDER_RUNTIME_VERSION, recipeHash, os: 'linux', arch: 'arm64' };+ const evidence = {+ ok: true, error: null, checkedAt: '2026-01-01T00:00:00.000Z', imageId: image.id,+ runtimeVersion: SUPERCOLLIDER_RUNTIME_VERSION, policyVersion: SUPERCOLLIDER_POLICY_VERSION, policyFingerprint: SUPERCOLLIDER_POLICY_FINGERPRINT,+ };+ const state = (input) => evaluateSuperColliderStatus({ docker, image, evidence, recipeHash, ...input });++ it('is ready only with a reachable Linux engine, the current image and current passing evidence', () => {+ expect(state({})).toMatchObject({ state: 'ready', ready: true, action: null, smoke: { current: true } });+ expect(state({ docker: { installed: false, running: false } })).toMatchObject({ state: 'docker-missing', ready: false });+ expect(state({ docker: { ...docker, running: false, error: 'Cannot connect' } }).message).toContain('Cannot connect');+ expect(state({ docker: { ...docker, os: 'windows' } }).state).toBe('docker-unsupported');+ expect(state({ docker: { ...docker, arch: 's390x' } })).toMatchObject({ state: 'docker-unsupported', action: null });+ expect(state({ image: null }).state).toBe('image-missing');+ expect(state({ evidence: null }).state).toBe('unverified');+ expect(state({ evidence: { ...evidence, ok: false, error: 'the render is silent' } })).toMatchObject({ state: 'smoke-failed', message: expect.stringContaining('silent') });+ });++ it('voids evidence and images from another runtime, recipe, policy or image', () => {+ expect(state({ image: { ...image, runtimeVersion: '3.13.0-portos.1' } }).state).toBe('image-stale');+ expect(state({ recipeHash: 'recipe-2' }).state).toBe('image-stale');+ for (const stale of [+ { runtimeVersion: '3.13.0-portos.1' },+ { policyVersion: SUPERCOLLIDER_POLICY_VERSION - 1 },+ { policyFingerprint: 'edited-policy' },+ { imageId: 'sha256:rebuilt' },+ ]) {+ expect(state({ evidence: { ...evidence, ...stale } })).toMatchObject({ state: 'unverified', smoke: { current: false } });+ }+ // A stale failure is not reported as a current one either.+ expect(state({ evidence: { ...evidence, ok: false, imageId: 'sha256:rebuilt' } }).state).toBe('unverified');+ });+});diff --git a/server/lib/wavAudioFile.js b/server/lib/wavAudioFile.jsindex ee56101830..f7adde970e 100644--- a/server/lib/wavAudioFile.js+++ b/server/lib/wavAudioFile.js@@ -34,37 +34,110 @@ export async function writeWavAudioFile(wav, dir, basename) {}/**- * Compute the playback duration (ms) of a PCM WAV buffer by reading its- * canonical RIFF header — `data` chunk size ÷ `fmt ` byte rate. Used by the- * narration timeline (karaoke-style highlight sync) where the client needs a- * per-segment duration without decoding the audio itself, and to validate an- * uploaded code-engine take (a non-WAV body measures 0).- *- * Pure + defensive: scans the sub-chunk list (the `fmt ` and `data` chunks- * aren't guaranteed to be adjacent or first), and returns 0 for anything that- * isn't a parseable WAV so a malformed buffer degrades to "unknown length"- * instead of throwing into the synth path.+ * Locate a RIFF/WAVE buffer's `fmt ` and `data` chunks. Scans the whole+ * sub-chunk list (the two are not guaranteed to be adjacent or first) and+ * clamps `data` to the bytes actually present — a truncated stream can carry a+ * larger declared size than the buffer holds. Null for anything not RIFF/WAVE.*/-export function wavDurationMs(buffer) {- if (!Buffer.isBuffer(buffer) || buffer.length < 12) return 0;- if (buffer.toString('ascii', 0, 4) !== 'RIFF' || buffer.toString('ascii', 8, 12) !== 'WAVE') return 0;- let byteRate = 0;- let dataSize = 0;+function findWavChunks(buffer) {+ if (!Buffer.isBuffer(buffer) || buffer.length < 12) return null;+ if (buffer.toString('ascii', 0, 4) !== 'RIFF' || buffer.toString('ascii', 8, 12) !== 'WAVE') return null;+ let fmt = null;+ let data = null;let offset = 12;while (offset + 8 <= buffer.length) {const id = buffer.toString('ascii', offset, offset + 4);const size = buffer.readUInt32LE(offset + 4);const body = offset + 8;- if (id === 'fmt ' && body + 16 <= buffer.length) {- byteRate = buffer.readUInt32LE(body + 8);- } else if (id === 'data') {- // Clamp to the bytes actually present — a truncated stream can carry a- // larger declared size than the buffer holds.- dataSize = Math.min(size, buffer.length - body);- }+ if (id === 'fmt ' && body + 16 <= buffer.length) fmt = { offset: body, size };+ else if (id === 'data') data = { offset: body, size: Math.min(size, buffer.length - body) };// Chunks are word-aligned: an odd size carries a trailing pad byte.offset = body + size + (size % 2);}- if (!byteRate || !dataSize) return 0;- return Math.round((dataSize / byteRate) * 1000);+ return { fmt, data };+}++/**+ * Compute the playback duration (ms) of a PCM WAV buffer by reading its+ * canonical RIFF header — `data` chunk size ÷ `fmt ` byte rate. Used by the+ * narration timeline (karaoke-style highlight sync) where the client needs a+ * per-segment duration without decoding the audio itself, and to validate an+ * uploaded code-engine take (a non-WAV body measures 0).+ *+ * Pure + defensive: returns 0 for anything that isn't a parseable WAV so a+ * malformed buffer degrades to "unknown length" instead of throwing into the+ * synth path.+ */+export function wavDurationMs(buffer) {+ const chunks = findWavChunks(buffer);+ if (!chunks?.fmt || !chunks.data) return 0;+ const byteRate = buffer.readUInt32LE(chunks.fmt.offset + 8);+ if (!byteRate || !chunks.data.size) return 0;+ return Math.round((chunks.data.size / byteRate) * 1000);+}++const WAVE_FORMAT_PCM = 1;+const WAVE_FORMAT_IEEE_FLOAT = 3;+const WAVE_FORMAT_EXTENSIBLE = 0xfffe;++/** Sample decoder for one (format, bit depth) pair, normalized to [-1, 1]; null when unsupported. */+function sampleReader(format, bits) {+ if (format === WAVE_FORMAT_PCM && bits === 16) return (buf, at) => buf.readInt16LE(at) / 32768;+ if (format === WAVE_FORMAT_PCM && bits === 24) return (buf, at) => buf.readIntLE(at, 3) / 8388608;+ if (format === WAVE_FORMAT_PCM && bits === 32) return (buf, at) => buf.readInt32LE(at) / 2147483648;+ if (format === WAVE_FORMAT_IEEE_FLOAT && bits === 32) return (buf, at) => buf.readFloatLE(at);+ if (format === WAVE_FORMAT_IEEE_FLOAT && bits === 64) return (buf, at) => buf.readDoubleLE(at);+ return null;+}++/**+ * Decode a rendered WAV and measure what is actually in it, so a native+ * renderer's output is judged by its samples rather than by the score it was+ * asked to play: `{ channels, sampleRate, bitsPerSample, float, frames,+ * durationMs, peak, rms, nonFinite }`. `peak`/`rms` are over every finite+ * sample, normalized to full scale; `nonFinite` counts NaN/Infinity samples (a+ * float render can carry them). Accepts PCM 16/24/32-bit and IEEE float 32/64,+ * including WAVE_FORMAT_EXTENSIBLE. Null for anything else — never throws.+ */+export function measureWavAudio(buffer) {+ const chunks = findWavChunks(buffer);+ if (!chunks?.fmt || !chunks.data) return null;+ const { offset } = chunks.fmt;+ let format = buffer.readUInt16LE(offset);+ const channels = buffer.readUInt16LE(offset + 2);+ const sampleRate = buffer.readUInt32LE(offset + 4);+ const blockAlign = buffer.readUInt16LE(offset + 12);+ const bitsPerSample = buffer.readUInt16LE(offset + 14);+ // EXTENSIBLE carries the real format as the first two bytes of its subformat GUID.+ if (format === WAVE_FORMAT_EXTENSIBLE && chunks.fmt.size >= 40 && offset + 26 <= buffer.length) {+ format = buffer.readUInt16LE(offset + 24);+ }+ const read = sampleReader(format, bitsPerSample);+ const bytesPerSample = bitsPerSample / 8;+ if (!read || !channels || !sampleRate || blockAlign !== channels * bytesPerSample) return null;+ const frames = Math.floor(chunks.data.size / blockAlign);+ let peak = 0;+ let sumSquares = 0;+ let finite = 0;+ let nonFinite = 0;+ const end = chunks.data.offset + frames * blockAlign;+ for (let at = chunks.data.offset; at < end; at += bytesPerSample) {+ const sample = read(buffer, at);+ if (!Number.isFinite(sample)) { nonFinite += 1; continue; }+ const magnitude = Math.abs(sample);+ if (magnitude > peak) peak = magnitude;+ sumSquares += sample * sample;+ finite += 1;+ }+ return {+ channels,+ sampleRate,+ bitsPerSample,+ float: format === WAVE_FORMAT_IEEE_FLOAT,+ frames,+ durationMs: Math.round((frames / sampleRate) * 1000),+ peak,+ rms: finite ? Math.sqrt(sumSquares / finite) : 0,+ nonFinite,+ };}diff --git a/server/lib/wavAudioFile.test.js b/server/lib/wavAudioFile.test.jsnew file mode 100644index 0000000000..13b94c47c4--- /dev/null+++ b/server/lib/wavAudioFile.test.js@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest';+import { measureWavAudio, wavDurationMs } from './wavAudioFile.js';++// Minimal RIFF/WAVE writer: `samples` is interleaved, already in [-1, 1].+function wav({ samples, channels = 2, sampleRate = 48000, format = 'int16', extensible = false, leadingChunk = false }) {+ const spec = {+ int16: { tag: 1, bits: 16, write: (b, v, at) => b.writeInt16LE(Math.round(v * 32767), at) },+ int24: { tag: 1, bits: 24, write: (b, v, at) => b.writeIntLE(Math.round(v * 8388607), at, 3) },+ float32: { tag: 3, bits: 32, write: (b, v, at) => b.writeFloatLE(v, at) },+ uint8: { tag: 1, bits: 8, write: (b, v, at) => b.writeUInt8(Math.round(v * 127) + 128, at) },+ }[format];+ const bytes = spec.bits / 8;+ const fmt = Buffer.alloc(extensible ? 40 : 16);+ fmt.writeUInt16LE(extensible ? 0xfffe : spec.tag, 0);+ fmt.writeUInt16LE(channels, 2);+ fmt.writeUInt32LE(sampleRate, 4);+ fmt.writeUInt32LE(sampleRate * channels * bytes, 8);+ fmt.writeUInt16LE(channels * bytes, 12);+ fmt.writeUInt16LE(spec.bits, 14);+ if (extensible) { fmt.writeUInt16LE(22, 16); fmt.writeUInt16LE(spec.tag, 24); }+ const data = Buffer.alloc(samples.length * bytes);+ samples.forEach((v, i) => spec.write(data, v, i * bytes));+ const chunk = (id, body) => Buffer.concat([Buffer.from(id, 'ascii'), Buffer.from(Uint32Array.of(body.length).buffer), body]);+ const body = Buffer.concat([+ Buffer.from('WAVE', 'ascii'),+ ...(leadingChunk ? [chunk('LIST', Buffer.from('info'))] : []),+ chunk('fmt ', fmt),+ chunk('data', data),+ ]);+ return Buffer.concat([Buffer.from('RIFF', 'ascii'), Buffer.from(Uint32Array.of(body.length).buffer), body]);+}++const stereoTone = (frames, amplitude) => Array.from({ length: frames * 2 }, (_, i) => amplitude * Math.sin(i / 7));++describe('measureWavAudio', () => {+ it('decodes integer PCM into format, duration and level', () => {+ const measured = measureWavAudio(wav({ samples: stereoTone(4800, 0.5), leadingChunk: true }));+ expect(measured).toMatchObject({ channels: 2, sampleRate: 48000, bitsPerSample: 16, float: false, frames: 4800, durationMs: 100, nonFinite: 0 });+ expect(measured.peak).toBeGreaterThan(0.45);+ expect(measured.peak).toBeLessThanOrEqual(0.5);+ expect(measured.rms).toBeGreaterThan(0.3);+ // wavDurationMs reads the same chunk scan.+ expect(wavDurationMs(wav({ samples: stereoTone(4800, 0.5), leadingChunk: true }))).toBe(100);+ });++ it('reads EXTENSIBLE 24-bit and counts non-finite float samples', () => {+ expect(measureWavAudio(wav({ samples: stereoTone(480, 0.25), format: 'int24', extensible: true })))+ .toMatchObject({ bitsPerSample: 24, frames: 480, durationMs: 10 });+ const float = measureWavAudio(wav({ samples: [0.5, NaN, -0.75, Infinity], format: 'float32' }));+ expect(float).toMatchObject({ float: true, frames: 2, nonFinite: 2, peak: 0.75 });+ });++ it('reports silence as zero level and rejects what it cannot decode', () => {+ expect(measureWavAudio(wav({ samples: new Array(960).fill(0) }))).toMatchObject({ peak: 0, rms: 0 });+ expect(measureWavAudio(wav({ samples: [0.1, 0.2], format: 'uint8' }))).toBeNull();+ expect(measureWavAudio(Buffer.from('not a wav file at all'))).toBeNull();+ expect(measureWavAudio(null)).toBeNull();+ });+});diff --git a/server/services/README.md b/server/services/README.mdindex 490e486a20..633268d5f2 100644--- a/server/services/README.md+++ b/server/services/README.md@@ -12,6 +12,7 @@ image-generation paths below are useful entry points when tracing render jobs.| `databaseMaintenanceQuiescence.js` | Internal coordinator stage after producer shutdown: terminate verified running detached-writer groups, prove every registry record quiescent from process-table evidence, archive it with the operation, and refuse pending, legacy, orphaned, ambiguous or unregistered writers. || `imageGen/prepareParams.js` | Shared image request preparation and the canonical local image model selector. Use `selectLocalImageModelFromSettings()` for model identity and `resolveLocalImageModel()` when the caller must also enforce local runtime, hardware, and edit-image requirements. || `imageGen/index.js` | Mode-aware image backend dispatcher and shared image-generation helpers. Direct queue consumers still resolve local model identity before enqueueing. |+| `superColliderRuntime.js` | Managed SuperCollider runtime I/O (#9412): Docker probe, recipe-hash-stamped image build, `runSuperColliderContainer` (contained `sclang` run with forced container removal), the synthetic render probe and its cached evidence, `getSuperColliderStatus` and idempotent `setupSuperColliderRuntime`. Never runs at boot. || `universeBuilderRender.js` | Universe Builder batch render jobs. || `pipeline/visualStageHelpers.js` | Shared pipeline visual prompt, LoRA compatibility, and image-job enqueue helpers. || `creativeStyleSources.js` | Resolves a universe style guide or mood board into art-direction text plus local reference images; shared by Code Animation and Creative Commissions. |diff --git a/server/services/backup.js b/server/services/backup.jsindex bab2fb303d..e009b308b3 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -181,6 +181,10 @@ export const DEFAULT_EXCLUDES = [// would claim gigabytes of models that machine does not have, and offer delete// buttons for them. It is fully re-derivable by a rescan from Models → Status.{ path: '/model-manifest.json', reason: 'Tracked downloaded-model inventory — machine-local and re-derivable by rescanning the model stores; a restored copy would describe another machine\'s disks', overridable: false },+ // Anchored, like every entry here. Readiness evidence is bound to THIS+ // machine's local image id (a restored copy would read as stale anyway) and+ // the rest is in-flight render scratch; setup re-derives all of it.+ { path: '/supercollider/', reason: 'SuperCollider runtime readiness evidence and in-flight render scratch — machine-local, re-derived by npm run setup:supercollider', overridable: false },// Sprite animation-run raw intermediates: 30–96 ffmpeg-extracted PNGs per// run, byte-for-byte regenerable from the archived source video by the// deterministic postprocess (walkPostprocess.js). The source video, packageddiff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex 09ba0e25c3..0a6bad5f30 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -170,6 +170,7 @@ export const CATEGORIES = {'spotify': { label: 'Spotify Sync', description: 'Machine-local Spotify sync cursor and cache — purging resets the cursor and can leave a gap in imported history', archivable: true, deletable: false },'sprites': { label: 'Sprites', description: 'Sprite reference art, walk frames, and runtime atlases — the only copy of the generated art; records live in Postgres', archivable: false, deletable: false },'story-builder': { label: 'Story Builder', description: 'Story Builder project records', archivable: true, deletable: false },+ 'supercollider': { label: 'SuperCollider Runtime', description: 'Machine-local readiness evidence for the managed SuperCollider image and in-flight render scratch — re-created by npm run setup:supercollider, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },'telegram': { label: 'Telegram', description: 'Telegram bot data', archivable: true, deletable: true, purgeScope: 'category' },'templates': { label: 'Visual Templates', description: 'Shipped layout assets used as render anchors', archivable: false, deletable: false },'tools': { label: 'Tools', description: 'Tool execution data', archivable: true, deletable: true, purgeScope: 'category' },diff --git a/server/services/superColliderRuntime.js b/server/services/superColliderRuntime.jsnew file mode 100644index 0000000000..ab3680befa--- /dev/null+++ b/server/services/superColliderRuntime.js@@ -0,0 +1,307 @@+/**+ * Managed SuperCollider runtime I/O (#9412): Docker discovery, the PortOS image+ * build, the contained `sclang` runner, the synthetic readiness probe and its+ * cached evidence. The contract it applies — image naming, containment args,+ * readiness states — is `lib/superColliderRuntime.js`.+ *+ * Nothing here runs on server boot or calls an AI provider. Status reads the+ * Docker engine and image metadata plus the CACHED probe result; only an+ * explicit setup (`npm run setup:supercollider`, or a future setup route)+ * builds the image or renders the probe.+ *+ * Evidence lives in `data/supercollider/runtime-evidence.json`: machine-local,+ * re-derivable by re-running setup, and bound to the local image id — a copy+ * restored onto another machine reads as stale there rather than as ready.+ */++import { existsSync } from 'fs';+import { lstat, mkdir, readdir, readFile, rm, writeFile, chmod } from 'fs/promises';+import { join } from 'path';+import { randomUUID } from 'crypto';+import { PATHS } from '../lib/paths.js';+import { atomicWrite } from '../lib/fileCore.js';+import { readJSONFile } from '../lib/jsonIo.js';+import { bufferedSpawn, spawnFailureDetail } from '../lib/bufferedSpawn.js';+import { runStreamingCommand } from '../lib/streamingSpawn.js';+import { whichFirst } from '../lib/processEnv.js';+import { measureWavAudio } from '../lib/wavAudioFile.js';+import {+ SUPERCOLLIDER_CONTAINER_LIMITS,+ SUPERCOLLIDER_CONTAINER_PATHS,+ SUPERCOLLIDER_FALLBACK_USER,+ SUPERCOLLIDER_IMAGE,+ SUPERCOLLIDER_POLICY_FINGERPRINT,+ SUPERCOLLIDER_POLICY_VERSION,+ SUPERCOLLIDER_RECIPE_DIR,+ SUPERCOLLIDER_RENDER_FORMAT,+ SUPERCOLLIDER_RUNTIME_VERSION,+ SUPERCOLLIDER_SMOKE,+ SUPERCOLLIDER_SMOKE_SOURCE,+ buildSuperColliderBuildArgs,+ buildSuperColliderRunArgs,+ evaluateSuperColliderStatus,+ hashSuperColliderRecipe,+ parseDockerImage,+ parseDockerVersion,+ superColliderContainerUser,+ superColliderSmokeFailure,+} from '../lib/superColliderRuntime.js';++const DOCKER_PROBE_TIMEOUT_MS = 15_000;+const DOCKER_RM_TIMEOUT_MS = 30_000;+const BUILD_TIMEOUT_MS = 90 * 60_000;+const MAX_DIAGNOSTIC_CHARS = 600;+const EVIDENCE_SCHEMA = 1;++// Docker Desktop's CLI is not always on a PM2-launched server's PATH.+const DOCKER_FALLBACK_PATHS = [+ '/usr/local/bin/docker',+ '/opt/homebrew/bin/docker',+ '/Applications/Docker.app/Contents/Resources/bin/docker',+];++/** Keep diagnostics bounded: one line, at most MAX_DIAGNOSTIC_CHARS, tail-preferring. */+function clipDiagnostic(text) {+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim();+ return flat.length > MAX_DIAGNOSTIC_CHARS ? `…${flat.slice(-MAX_DIAGNOSTIC_CHARS)}` : flat;+}++/**+ * The docker CLI adapter every function here talks through: `capture` runs a+ * short command and buffers its output; `stream` runs a long one line by line+ * with timeout/cancel. Tests pass a fake with the same two methods.+ */+function createDockerCli(bin) {+ return {+ bin,+ capture: (args, { timeoutMs = DOCKER_PROBE_TIMEOUT_MS } = {}) => bufferedSpawn(bin, args, { timeoutMs, killGraceMs: 2_000, shell: false }),+ stream: (args, onLine, options = {}) => runStreamingCommand(bin, args, onLine, options),+ };+}++/** The local docker CLI, or null when it is not installed. */+async function resolveDockerCli() {+ const bin = await whichFirst('docker') || DOCKER_FALLBACK_PATHS.find((path) => existsSync(path)) || null;+ return bin ? createDockerCli(bin) : null;+}++function resolveDeps({ docker, dataDir = PATHS.data, codeRoot = PATHS.root } = {}) {+ return { docker, dataDir, codeRoot, evidencePath: join(dataDir, 'supercollider', 'runtime-evidence.json') };+}++async function dockerFor(deps) {+ return deps.docker === undefined ? resolveDockerCli() : deps.docker;+}++/** `{ installed, running, clientVersion, serverVersion, os, arch, error }` for a docker CLI (null = not installed). */+async function probeDocker(cli) {+ if (!cli) return { installed: false, running: false, clientVersion: null, serverVersion: null, os: null, arch: null, error: null };+ const result = await cli.capture(['version', '--format', '{{json .}}']);+ // The client prints its half even when the engine is down, so the server+ // version — not the exit code alone — is what proves the engine answered.+ const version = parseDockerVersion(result.stdout);+ const running = Boolean(version.serverVersion);+ return {+ installed: true,+ running,+ ...version,+ error: running ? null : clipDiagnostic(result.timedOut ? 'docker did not answer in time' : spawnFailureDetail(result, 'docker engine not reachable')),+ };+}++/** The managed image's metadata, or null when it is not built. */+async function inspectSuperColliderImage(cli, image = SUPERCOLLIDER_IMAGE) {+ const result = await cli.capture(['image', 'inspect', '--format', '{{json .}}', image]);+ return result.success ? parseDockerImage(result.stdout) : null;+}++/** Hash of the checked-in recipe directory (`docker/supercollider/`). */+async function readSuperColliderRecipeHash({ codeRoot = PATHS.root } = {}) {+ const dir = join(codeRoot, SUPERCOLLIDER_RECIPE_DIR);+ const entries = await readdir(dir, { withFileTypes: true });+ const files = await Promise.all(entries.filter((entry) => entry.isFile())+ .map(async (entry) => ({ name: entry.name, content: await readFile(join(dir, entry.name), 'utf8') })));+ return hashSuperColliderRecipe(files);+}++async function readSuperColliderEvidence(options = {}) {+ const { evidencePath } = resolveDeps(options);+ const evidence = await readJSONFile(evidencePath, null, { allowArray: false, logError: false });+ return evidence?.schema === EVIDENCE_SCHEMA ? evidence : null;+}++/**+ * The readiness verdict (`evaluateSuperColliderStatus`). Asks the Docker engine+ * and reads cached evidence; never builds, pulls or renders.+ */+export async function getSuperColliderStatus(options = {}) {+ const deps = resolveDeps(options);+ const cli = await dockerFor(deps);+ const docker = await probeDocker(cli);+ const [image, evidence, recipeHash] = await Promise.all([+ docker.running ? inspectSuperColliderImage(cli) : null,+ readSuperColliderEvidence(deps),+ readSuperColliderRecipeHash(deps),+ ]);+ return evaluateSuperColliderStatus({ docker, image, evidence, recipeHash });+}++/**+ * Read one file a contained run wrote into its output directory, refusing+ * anything but a regular file within `maxBytes` — the container controls that+ * directory, so a symlink there could otherwise point the host at its own files.+ * Null when absent or refused.+ */+export async function readContainedOutput(outputDir, name, { maxBytes = SUPERCOLLIDER_CONTAINER_LIMITS.maxFileBytes } = {}) {+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)) return null;+ const path = join(outputDir, name);+ const info = await lstat(path).catch(() => null);+ if (!info?.isFile() || info.size > maxBytes) return null;+ return readFile(path);+}++/**+ * Run `sclang` on `<inputDir>/<script>` inside one disposable container under+ * the shared containment policy. The container is force-removed afterwards+ * whatever happened — the docker CLI dying does not stop a container, so a+ * timeout or cancel that only killed the CLI would leave the render running.+ * Never rejects for a failed run: `{ ok, error, timedOut, cancelled, containerName }`.+ *+ * @param {object} params+ * @param {{capture: Function, stream: Function}} params.docker+ * @param {string} params.inputDir - host directory holding the frozen source (mounted read-only)+ * @param {string} params.outputDir - job-private host directory (the only writable mount)+ * @param {string} [params.script]+ * @param {Array<string|number>} [params.scriptArgs] - `thisProcess.argv` inside sclang+ * @param {string} [params.image] - tag or image id+ * @param {number} [params.timeoutMs]+ * @param {AbortSignal} [params.signal]+ * @param {(line: string) => void} [params.onLine]+ */+export async function runSuperColliderContainer({+ docker, inputDir, outputDir, script, scriptArgs = [], image = SUPERCOLLIDER_IMAGE,+ timeoutMs = SUPERCOLLIDER_CONTAINER_LIMITS.wallTimeoutMs, signal, onLine,+}) {+ const containerName = `portos-sc-${randomUUID()}`;+ const user = superColliderContainerUser({ uid: process.getuid?.(), gid: process.getgid?.() });+ // The `nobody` fallback does not own the host directory; let it write there.+ if (user === SUPERCOLLIDER_FALLBACK_USER) await chmod(outputDir, 0o777).catch(() => {});+ const args = buildSuperColliderRunArgs({ image, containerName, inputDir, outputDir, script, scriptArgs, user });+ const result = await docker.stream(args, onLine, { timeoutMs, isCancelled: () => Boolean(signal?.aborted) });+ const removal = await docker.capture(['rm', '--force', containerName], { timeoutMs: DOCKER_RM_TIMEOUT_MS });+ if (!removal.success && !/no such container/i.test(`${removal.stderr}`)) {+ console.error(`❌ SuperCollider container ${containerName} cleanup failed: ${clipDiagnostic(spawnFailureDetail(removal, 'docker rm failed'))}`);+ }+ const error = result.success ? null : clipDiagnostic(result.error);+ return {+ ok: result.success,+ error,+ timedOut: Boolean(error?.startsWith('timed out')),+ cancelled: error === 'cancelled',+ containerName,+ };+}++/**+ * Render the shipped synthetic probe through the production runner against+ * `image`, measure the WAV it wrote, and record the result as the readiness+ * evidence for this runtime/policy/image. The job directory is removed either+ * way. Resolves the evidence record.+ */+async function runSuperColliderSmoke({ docker, image, dockerInfo = null, ...options }) {+ const { dataDir, evidencePath } = resolveDeps(options);+ const jobDir = join(dataDir, 'supercollider', 'jobs', `smoke-${randomUUID()}`);+ const inputDir = join(jobDir, 'in');+ const outputDir = join(jobDir, 'out');+ let failure;+ let measurement = null;+ try {+ await mkdir(inputDir, { recursive: true });+ await mkdir(outputDir, { recursive: true });+ await writeFile(join(inputDir, SUPERCOLLIDER_SMOKE.script), SUPERCOLLIDER_SMOKE_SOURCE);+ const run = await runSuperColliderContainer({+ docker,+ image: image.id,+ inputDir,+ outputDir,+ script: SUPERCOLLIDER_SMOKE.script,+ scriptArgs: [`${SUPERCOLLIDER_CONTAINER_PATHS.output}/${SUPERCOLLIDER_SMOKE.output}`, SUPERCOLLIDER_SMOKE.durationSec, SUPERCOLLIDER_RENDER_FORMAT.sampleRate],+ timeoutMs: SUPERCOLLIDER_SMOKE.timeoutMs,+ });+ if (run.ok) {+ measurement = measureWavAudio(await readContainedOutput(outputDir, SUPERCOLLIDER_SMOKE.output));+ failure = superColliderSmokeFailure(measurement);+ } else {+ failure = `the probe render failed: ${run.error}`;+ }+ } finally {+ await rm(jobDir, { recursive: true, force: true });+ }+ const evidence = {+ schema: EVIDENCE_SCHEMA,+ ok: !failure,+ error: failure ? clipDiagnostic(failure) : null,+ checkedAt: new Date().toISOString(),+ runtimeVersion: SUPERCOLLIDER_RUNTIME_VERSION,+ policyVersion: SUPERCOLLIDER_POLICY_VERSION,+ policyFingerprint: SUPERCOLLIDER_POLICY_FINGERPRINT,+ imageId: image.id,+ platform: { os: dockerInfo?.os ?? image.os ?? null, arch: dockerInfo?.arch ?? image.arch ?? null, dockerVersion: dockerInfo?.serverVersion ?? null },+ measurement: measurement && {+ durationMs: measurement.durationMs,+ channels: measurement.channels,+ sampleRate: measurement.sampleRate,+ peak: Number(measurement.peak.toFixed(4)),+ rms: Number(measurement.rms.toFixed(4)),+ },+ };+ await atomicWrite(evidencePath, evidence);+ return evidence;+}++const DOCKER_UNAVAILABLE_STATES = new Set(['docker-missing', 'docker-stopped', 'docker-unsupported']);+let setupInFlight = null;++/**+ * Explicit, idempotent setup: build the image only when it is missing, stale+ * or `rebuild` is asked for (after `confirmBuild` agrees), then run the probe+ * only when the build changed something or no current passing evidence+ * exists. A second run against a ready runtime does neither. Concurrent calls+ * share one run.+ *+ * Resolves `{ outcome, built, probed, status, error }`, outcome one of+ * ready, docker-unavailable, declined, build-failed, smoke-failed.+ */+export function setupSuperColliderRuntime(options = {}) {+ setupInFlight ??= runSetup(options).finally(() => { setupInFlight = null; });+ return setupInFlight;+}++async function runSetup({ rebuild = false, confirmBuild = async () => true, onLine, ...options }) {+ const deps = resolveDeps(options);+ const docker = await dockerFor(deps);+ const statusDeps = { ...options, docker };+ let status = await getSuperColliderStatus(statusDeps);+ const done = (outcome, extra = {}) => ({ outcome, built: false, probed: false, status, error: null, ...extra });+ if (DOCKER_UNAVAILABLE_STATES.has(status.state)) return done('docker-unavailable');++ let built = false;+ if (rebuild || !status.image?.current) {+ if (!await confirmBuild(status)) return done('declined');+ const recipeHash = await readSuperColliderRecipeHash(deps);+ const args = buildSuperColliderBuildArgs({ recipeDir: join(deps.codeRoot, SUPERCOLLIDER_RECIPE_DIR), recipeHash, noCache: rebuild });+ const result = await docker.stream(args, onLine, { timeoutMs: BUILD_TIMEOUT_MS });+ status = await getSuperColliderStatus(statusDeps);+ if (!result.success) return done('build-failed', { error: clipDiagnostic(result.error) });+ if (!status.image?.current) return done('build-failed', { error: 'docker build finished but the expected image is not present' });+ built = true;+ }++ let probed = false;+ if (built || rebuild || !(status.smoke?.current && status.smoke.ok)) {+ await runSuperColliderSmoke({ docker, image: status.image, dockerInfo: status.docker, ...options });+ probed = true;+ status = await getSuperColliderStatus(statusDeps);+ }+ return done(status.ready ? 'ready' : 'smoke-failed', { built, probed, error: status.ready ? null : status.smoke?.error ?? status.message });+}diff --git a/server/services/superColliderRuntime.test.js b/server/services/superColliderRuntime.test.jsnew file mode 100644index 0000000000..75e4fccdab--- /dev/null+++ b/server/services/superColliderRuntime.test.js@@ -0,0 +1,138 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'fs';+import { readFile, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { SUPERCOLLIDER_IMAGE_LABELS, SUPERCOLLIDER_RUNTIME_VERSION } from '../lib/superColliderRuntime.js';+import { getSuperColliderStatus, setupSuperColliderRuntime } from './superColliderRuntime.js';++// Interleaved int16 stereo WAV at 48 kHz.+function stereoWav(seconds, amplitude) {+ const frames = Math.round(seconds * 48000);+ const data = Buffer.alloc(frames * 4);+ for (let i = 0; i < frames * 2; i += 1) data.writeInt16LE(Math.round(amplitude * 32767 * Math.sin(i / 9)), i * 2);+ const header = Buffer.alloc(44);+ header.write('RIFF', 0, 'ascii'); header.writeUInt32LE(36 + data.length, 4); header.write('WAVE', 8, 'ascii');+ header.write('fmt ', 12, 'ascii'); header.writeUInt32LE(16, 16); header.writeUInt16LE(1, 20); header.writeUInt16LE(2, 22);+ header.writeUInt32LE(48000, 24); header.writeUInt32LE(48000 * 4, 28); header.writeUInt16LE(4, 32); header.writeUInt16LE(16, 34);+ header.write('data', 36, 'ascii'); header.writeUInt32LE(data.length, 40);+ return Buffer.concat([header, data]);+}++/**+ * A docker CLI double with the adapter's two methods. It keeps one image,+ * "builds" it from the labels it is handed, and on `run` lets `render` write+ * into the host directory mounted at /out — the same contract the real+ * container has.+ */+function fakeDocker({ running = true, render = (out) => writeFileSync(join(out, 'smoke.wav'), stereoWav(2, 0.25)), runResult = { success: true } } = {}) {+ const calls = [];+ let image = null;+ let builds = 0;+ const label = (args, key) => args.flatMap((arg, i) => (arg === '--label' && args[i + 1].startsWith(`${key}=`) ? [args[i + 1].slice(key.length + 1)] : []))[0];+ return {+ calls,+ capture: async (args) => {+ calls.push(args[0] === 'image' ? 'inspect' : args[0]);+ if (args[0] === 'version') {+ return running+ ? { success: true, stdout: JSON.stringify({ Client: { Version: '27.0.0' }, Server: { Version: '27.0.0', Os: 'linux', Arch: 'arm64' } }), stderr: '' }+ : { success: false, code: 1, stdout: JSON.stringify({ Client: { Version: '27.0.0' }, Server: null }), stderr: 'Cannot connect to the Docker daemon' };+ }+ if (args[0] === 'image') {+ return image ? { success: true, stdout: JSON.stringify(image), stderr: '' } : { success: false, code: 1, stdout: '', stderr: 'No such image' };+ }+ return { success: true, stdout: '', stderr: '' }; // rm --force+ },+ stream: async (args) => {+ calls.push(args[0]);+ if (args[0] === 'build') {+ builds += 1;+ image = {+ Id: `sha256:image-${builds}`, Os: 'linux', Architecture: 'arm64', Size: 300e6,+ Config: { Labels: {+ [SUPERCOLLIDER_IMAGE_LABELS.runtimeVersion]: label(args, SUPERCOLLIDER_IMAGE_LABELS.runtimeVersion),+ [SUPERCOLLIDER_IMAGE_LABELS.recipeHash]: label(args, SUPERCOLLIDER_IMAGE_LABELS.recipeHash),+ } },+ };+ return { success: true };+ }+ const out = args.find((arg) => arg.endsWith('target=/out')).match(/source=(.*),target=\/out$/)[1];+ calls.runArgs = args;+ render(out);+ return runResult;+ },+ };+}++describe('SuperCollider runtime setup', () => {+ let dataDir;+ beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'portos-supercollider-')); });+ afterEach(() => rmSync(dataDir, { recursive: true, force: true }));+ const evidencePath = () => join(dataDir, 'supercollider', 'runtime-evidence.json');++ it('builds and proves the runtime once, then a second setup skips both', async () => {+ const docker = fakeDocker();+ expect((await getSuperColliderStatus({ docker, dataDir })).state).toBe('image-missing');++ const first = await setupSuperColliderRuntime({ docker, dataDir });+ expect(first).toMatchObject({ outcome: 'ready', built: true, probed: true, status: { state: 'ready' } });+ expect(first.status.smoke.measurement).toMatchObject({ durationMs: 2000, channels: 2, sampleRate: 48000 });+ expect(docker.calls.filter((call) => call === 'build' || call === 'run')).toEqual(['build', 'run']);+ // The probe runs against the exact image it certifies, under the shared policy.+ expect(docker.calls.runArgs).toEqual(expect.arrayContaining(['sha256:image-1', '--network', 'none', '/in/smoke.scd', '/out/smoke.wav', '2', '48000']));+ expect(docker.calls).toContain('rm');+ // The job directory is gone; only the evidence remains.+ expect(readdirSync(join(dataDir, 'supercollider', 'jobs'))).toEqual([]);++ docker.calls.length = 0;+ const second = await setupSuperColliderRuntime({ docker, dataDir });+ expect(second).toMatchObject({ outcome: 'ready', built: false, probed: false });+ expect(docker.calls).not.toContain('build');+ expect(docker.calls).not.toContain('run');+ });++ it('re-probes, without rebuilding, when the recorded evidence belongs to another runtime version', async () => {+ const docker = fakeDocker();+ await setupSuperColliderRuntime({ docker, dataDir });+ const evidence = JSON.parse(await readFile(evidencePath(), 'utf8'));+ await writeFile(evidencePath(), JSON.stringify({ ...evidence, runtimeVersion: '3.13.0-portos.1' }));+ expect((await getSuperColliderStatus({ docker, dataDir })).state).toBe('unverified');++ docker.calls.length = 0;+ const result = await setupSuperColliderRuntime({ docker, dataDir });+ expect(result).toMatchObject({ outcome: 'ready', built: false, probed: true });+ expect(JSON.parse(await readFile(evidencePath(), 'utf8')).runtimeVersion).toBe(SUPERCOLLIDER_RUNTIME_VERSION);+ });++ it('never reports readiness from a silent, failed or symlinked probe output', async () => {+ const silent = await setupSuperColliderRuntime({ docker: fakeDocker({ render: (out) => writeFileSync(join(out, 'smoke.wav'), stereoWav(2, 0)) }), dataDir });+ expect(silent).toMatchObject({ outcome: 'smoke-failed', status: { state: 'smoke-failed', ready: false } });+ expect(silent.error).toContain('silent');++ // The container owns /out; a symlink there must not make the host read its own files.+ const hostFile = join(dataDir, 'host-audio.wav');+ writeFileSync(hostFile, stereoWav(2, 0.25));+ const linked = await setupSuperColliderRuntime({ docker: fakeDocker({ render: (out) => symlinkSync(hostFile, join(out, 'smoke.wav')) }), dataDir });+ expect(linked.status.smoke).toMatchObject({ ok: false, error: 'the probe wrote no readable WAV' });++ const docker = fakeDocker({ render: () => {}, runResult: { success: false, error: 'timed out after 120s' } });+ const timedOut = await setupSuperColliderRuntime({ docker, dataDir });+ expect(timedOut.status.smoke.error).toBe('the probe render failed: timed out after 120s');+ expect(docker.calls.slice(-4)).toEqual(['run', 'rm', 'version', 'inspect']); // container force-removed after the timeout+ });++ it('stops before building when Docker is unavailable or the build is declined', async () => {+ const stopped = fakeDocker({ running: false });+ const result = await setupSuperColliderRuntime({ docker: stopped, dataDir });+ expect(result).toMatchObject({ outcome: 'docker-unavailable', status: { state: 'docker-stopped' } });+ expect(result.status.message).toContain('Cannot connect to the Docker daemon');+ expect(stopped.calls).not.toContain('build');++ expect((await setupSuperColliderRuntime({ docker: null, dataDir })).status.state).toBe('docker-missing');++ const declined = fakeDocker();+ expect(await setupSuperColliderRuntime({ docker: declined, dataDir, confirmBuild: async () => false })).toMatchObject({ outcome: 'declined', built: false });+ expect(declined.calls).not.toContain('build');+ });+});