containers: each agent clones the monorepo into its own volume
Some checks failed
CI / Native — ubuntu-latest (push) Failing after 7m48s
CI / WASM — Web (push) Failing after 7m16s
CI / Formatting (push) Failing after 1m15s
CI / Native — macos-latest (push) Has been cancelled
CI / Native — windows-latest (push) Has been cancelled

The last structural fix for the collision class that has bitten three times. Both
containers now clone the repository into their OWN named volume instead of
bind-mounting a human's working tree, so an agent's local git config cannot
capture a human's commits, a credential helper cannot leak a container-only path
onto the host, and a `git add -A` cannot sweep another party's in-flight files.

Cloned once at startup and never auto-pulled: pulling under a running agent
moves files out from under whatever it is mid-edit, which is the same bug again.

Accepted knowingly: Claude Code keys per-project memory off the working
directory, so moving off the host path starts that memory empty. The corpus in
docs/ is the memory that matters and it travels with the clone.

Other changes:
* docker/agent -> docker/decoder; the launcher is sylph-decoder. Roles, not
  "the agent", now that there is more than one.
* /reborn is gone -- one repository now, so the port reads HANDOFF from its own
  checkout rather than through a live read-only mount of someone else's tree.
* Canary mounts separately at /canary; it stays a fork tracking upstream.
* A shared `sylpheed-exchange` volume at /exchange, with tools/ on PATH so
  `share` is available in both.
* The decoder's credential file gets the .host-copy treatment the port already
  had -- `credential.helper=store` rewrites by rename-over-target, which is
  EBUSY on a bind mount and reports a fatal that is not one.
* Budget split deliberately: decoder 5 cpu / 6 GB, port 3 / 4, leaving room for
  the planned Referee. "Half the host" was right when there was one agent.

Prompts move to docs/agents/ and are rewritten around the protocol: the oracle
is the running game, dynamic RE stays with the decoder, each iteration must
attempt to refute one claim of the other, and neither may verify its way out of
its own role.
This commit is contained in:
MechaCat02
2026-08-29 11:48:30 +02:00
parent a8815f2826
commit 06676d3dc0
21 changed files with 233 additions and 256 deletions

View File

@@ -0,0 +1,4 @@
**
!bin
!bin/**
!entrypoint.sh

145
docker/decoder/Dockerfile Normal file
View File

@@ -0,0 +1,145 @@
# Autonomous RE agent container for Project Sylpheed.
#
# Builds and runs BOTH halves of the project — Xenia Canary (C++/CMake/Ninja)
# as the behaviour oracle, and Sylpheed Reborn (Rust/Bevy) as the port — plus
# the dynamic-RE toolkit that drives the emulator and reads its guest memory.
#
# Three things here exist because their absence cost the previous agent real
# hours, and they are load-bearing rather than nice-to-have:
#
# 1. A REAL toolchain. The old box shipped runtime sonames only (libgtk-3.so.0
# but no libgtk-3.so), no cmake/ninja/clang and no libstdc++fs, so a full
# build was impossible and `tools/re-capture/rebuild_canary.sh` had to
# hand-relink object files. With -dev packages present that script is
# obsolete; use `build-canary`.
# 2. numpy and Pillow. Their absence silently disabled entities2.py,
# flight_probe.py and every image oracle, and the failure looked like a
# logic bug rather than a missing package.
# 3. A display that outlives the turn. Xvfb kept dying "on its own every few
# minutes"; it was being reaped because nothing owned it. Here it is a
# child of PID 1 and lives exactly as long as the container.
#
# Clang is pinned to 19 to match the host that produced the checked-in build
# caches (Ubuntu clang 19.1.1).
FROM ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive \
LANG=C.UTF-8 \
TZ=Etc/UTC
# ── System packages ──────────────────────────────────────────────────────────
RUN apt-get update && apt-get install -y --no-install-recommends \
# toolchain
build-essential cmake ninja-build pkg-config git curl wget ca-certificates \
clang-19 lld-19 llvm-19 libc++-19-dev libc++abi-19-dev \
# Canary: GTK window, SDL input/audio, Vulkan, compression
libgtk-3-dev libsdl2-dev liblz4-dev libvulkan-dev libx11-xcb-dev \
libxcb1-dev libxrandr-dev libssl-dev libfuse2t64 \
# Shader toolchain: the GPU build shells out to `glslangValidator` and the
# SPIR-V tools to compile xenia's own shaders. Missing them does not fail
# configure — it fails ~500 objects in, as a Python FileNotFoundError.
glslang-tools spirv-tools spirv-headers \
# Vulkan runtime — lavapipe (software) plus the real ICDs for /dev/dri
mesa-vulkan-drivers vulkan-tools libvulkan1 libgl1-mesa-dri libglx-mesa0 \
# Reborn / Bevy: audio, input, windowing
libasound2-dev libudev-dev libwayland-dev libxkbcommon-dev \
libx11-dev libxi-dev libxcursor-dev libxinerama-dev libxext-dev \
# headless display + window manager + the screenshot path
xvfb x11-utils x11-xserver-utils openbox xdotool imagemagick ffmpeg \
# dynamic RE
python3 python3-numpy python3-pil python3-pip \
gdb strace ltrace binutils file xxd ripgrep jq unzip zip p7zip-full \
procps psmisc lsof less nano tini sudo \
# expect drives Claude Code's one-time interactive gates for an
# unattended run — see bin/claude-autonomous.
expect \
&& rm -rf /var/lib/apt/lists/*
# Pin the unversioned tool names to 19 so CMake, and anything that shells out to
# `clang`, agree with what the caches were built by.
RUN for t in clang clang++ lld ld.lld llvm-ar llvm-ranlib llvm-nm clang-cpp; do \
src="/usr/bin/${t}-19"; \
[ -e "$src" ] && update-alternatives --install "/usr/bin/${t}" "$t" "$src" 200 || true; \
done
# duckdb reads the static-analysis database (sylpheed.db); it is not packaged.
# PEP 668 marks the system env externally-managed, and this image has no other
# Python consumer to protect, so installing into it is the honest simple option.
RUN pip3 install --no-cache-dir --break-system-packages duckdb
# ── Node + Claude Code ───────────────────────────────────────────────────────
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
&& apt-get install -y --no-install-recommends nodejs \
&& npm install -g @anthropic-ai/claude-code \
&& npm cache clean --force \
&& rm -rf /var/lib/apt/lists/*
# ── The agent user ───────────────────────────────────────────────────────────
# NOT root, and not negotiable: Claude Code refuses --dangerously-skip-permissions
# when it has root privileges. uid/gid 1000 matches the host account so files
# written into the bind-mounted repos keep the right ownership.
ARG AGENT_UID=1000
ARG AGENT_GID=1000
# Ubuntu 24.04 ships its own `ubuntu` account at uid/gid 1000, so the common
# case — matching a host user who is also 1000 — collides with it. Remove the
# stock account first; nothing in this image uses it.
RUN if getent passwd "${AGENT_UID}" >/dev/null; then \
userdel -r "$(getent passwd "${AGENT_UID}" | cut -d: -f1)" 2>/dev/null || true; \
fi; \
if getent group "${AGENT_GID}" >/dev/null; then \
groupdel "$(getent group "${AGENT_GID}" | cut -d: -f1)" 2>/dev/null || true; \
fi; \
groupadd -g "${AGENT_GID}" agent \
&& useradd -m -u "${AGENT_UID}" -g "${AGENT_GID}" -s /bin/bash -d /sylph-home/re agent \
&& mkdir -p /sylph-home/re /work \
&& chown -R "${AGENT_UID}:${AGENT_GID}" /sylph-home \
&& echo 'agent ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/agent
COPY bin/ /usr/local/bin/
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/* /usr/local/bin/entrypoint.sh
USER agent
WORKDIR /work
# ── Rust ─────────────────────────────────────────────────────────────────────
# CARGO_TARGET_DIR deliberately points OUTSIDE the bind-mounted repo: the host
# also builds Reborn, and sharing target/ makes the two invalidate each other's
# incremental state on every switch.
ENV RUSTUP_HOME=/sylph-home/re/.rustup \
CARGO_HOME=/sylph-home/re/.cargo \
CARGO_TARGET_DIR=/sylph-home/re/target-container \
PATH=/sylph-home/re/.cargo/bin:/usr/local/bin:/usr/bin:/bin
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
| sh -s -- -y --default-toolchain stable --profile minimal \
--component clippy --component rustfmt \
&& rustup target add wasm32-unknown-unknown
# trunk serves the Reborn viewer's wasm build; the release binary avoids a
# ten-minute `cargo install`.
RUN curl -fsSL https://github.com/trunk-rs/trunk/releases/download/v0.21.4/trunk-x86_64-unknown-linux-gnu.tar.gz \
| tar -xz -C /sylph-home/re/.cargo/bin trunk
# Create the volume mount points HERE, owned by `agent`. Docker seeds an empty
# named volume from whatever the image has at that path — including ownership —
# but if the path does not exist it creates a root-owned directory instead, and
# the first write fails with something as unhelpful as
# "CMake Error: Unable to (re)create the private pkgRedirects directory".
RUN mkdir -p /sylph-home/re/target-container /sylph-home/re/canary-build /sylph-home/re/.claude
# ── Runtime environment ──────────────────────────────────────────────────────
# DISPLAY :98 and HOME /sylph-home/re are what tools/re-capture/*.sh already
# assume; keeping them means the existing toolkit runs unmodified.
ENV HOME=/sylph-home/re \
DISPLAY=:98 \
SCREEN_GEOMETRY=1280x720x24 \
PROJECT_DIR=/work \
XENIA_PAD_FILE=/tmp/xenia_pad.txt \
XENIA_BUILD_DIR=/sylph-home/re/canary-build \
SDL_AUDIODRIVER=dummy \
LIBGL_ALWAYS_SOFTWARE=1 \
PATH=/work/tools:/work/tools/re-capture/bin:/work/tools/re-capture:/sylph-home/re/.cargo/bin:/usr/local/bin:/usr/bin:/bin
ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/entrypoint.sh"]
CMD ["bash"]

251
docker/decoder/README.md Normal file
View File

@@ -0,0 +1,251 @@
# The RE agent container
A container an autonomous Claude Code agent can be turned loose in: it builds
and runs **both** halves of the project — Xenia Canary as the behaviour oracle
and Sylpheed Reborn as the port — and carries the dynamic-RE toolkit that drives
the emulator, reads its guest memory and photographs its screen.
```bash
./sylph-agent build # build the image
./sylph-agent doctor # prove it can do the four things it exists for
./sylph-agent shell # poke around
./sylph-agent agent # Claude Code, --dangerously-skip-permissions
./sylph-agent loose # turn it loose: detached, /loop, self-paced
./sylph-agent remote # link to chat with it from anywhere
./sylph-agent attach # chat with it locally
./sylph-agent logs -f # watch it
./sylph-agent stop # stop it
```
## On the loose
`./sylph-agent loose` starts Claude Code **detached**, with
`--dangerously-skip-permissions`, running `/loop` on the task in
[`loop-task.md`](loop-task.md) — work the RE backlog one item at a time, commit
to `auto/*` branches, never push, record withdrawn results rather than deleting
them. Pass your own task as an argument, or set `SYLPH_LOOP_INTERVAL=30m` for a
fixed cadence instead of letting it self-pace.
It runs `-d` **without** `--rm`, so the transcript survives the container
exiting — for an unattended run that is the only record of what happened.
### Talking to it
Two channels, both live while it works:
* **`./sylph-agent remote`** prints a `https://claude.ai/code/session_…` link.
`loose` starts Claude Code with `--remote-control`, so the session registers
with your account and you can chat with it from claude.ai or your phone —
which is the point of a detached run. Disable with `SYLPH_REMOTE=0`, rename
with `SYLPH_REMOTE_NAME`.
Registration takes a minute or two after launch, so `remote` waits for it
rather than reporting "not found" to what is really "not yet".
* **`./sylph-agent attach`** joins the container's own terminal. Type to talk to
it; **Ctrl-P Ctrl-Q** detaches and leaves it running. Do not press Ctrl-C —
that goes to the agent.
The pty is forced to 200×50 (`stty_init` in `bin/claude-autonomous`). A detached
`docker run -t` is 80×24, and Claude Code hard-wraps to the terminal width,
which truncated the Remote Control URL to `…/session_01…` in the one place you
need to read it — and made `docker logs` almost unreadable besides.
**It cannot push.** No git credentials are mounted, deliberately: a human
reviews before anything leaves the box. Review with
`git -C <project>/Syplheed-Reborn log --oneline main..auto/<topic>`.
### The four gates
Claude Code has four one-time prompts, and each one is a silent, permanent hang
for an agent with nobody at the keyboard — no error, no log line, just a
container that looks healthy and does nothing. All four are handled:
| gate | how |
|---|---|
| theme picker | `hasCompletedOnboarding` + `lastOnboardingVersion` in `~/.claude.json` |
| "do you trust this folder?" | `projects.<path>.hasTrustDialogAccepted` |
| Bypass Permissions disclaimer | answered in a pty by [`bin/claude-autonomous`](bin/claude-autonomous) — it has no config key, by design |
| fullscreen-renderer upsell | `fullscreenUpsellSeenCount`, because it fires *mid-session*, after the pty wrapper has handed over |
Config keys were read out of the shipped binary's own strings rather than
guessed. The pty wrapper matches **single words**: Claude Code draws its UI with
absolute-column escapes between words, so `Yes, I accept` arrives as
`Yes,\x1b[13GI\x1b[15Gaccept` and a multi-word pattern never matches — which
looks exactly like the wrapper not running at all. It stops matching once the
session is live, so nothing later can be answered by accident.
## The resource cap
The container gets **half the machine**, computed at launch so it stays half on
any box:
| | how |
|---|---|
| CPU | `--cpus $(nproc)/2` |
| memory | `--memory` = half `MemTotal`, **`--memory-swap` equal to it** |
| `/dev/shm` | a third of the memory cap, min 1 GiB, mounted **exec** |
| build jobs | derived *inside* the container from **available memory**, not cores |
Two of those deserve a word.
**No swap headroom.** `--memory-swap` is set equal to `--memory`, so the
container cannot swap. That is deliberate: a swapping build thrashes the whole
host, which is precisely the failure the cap exists to prevent. A build that
would have swapped gets OOM-killed inside the container instead, and the host
stays usable.
**`/dev/shm` is not incidental.** Xenia backs the guest address space with
`/dev/shm/xenia_memory_*`, and the whole live-memory toolkit (`gmem.py`,
`gpoke.py`, `mission_state.py`) reads it from there. Docker's default is 64 MiB,
which is far too small for a 512 MiB console — and it fails as an obscure mmap
error rather than an out-of-space message.
**Build parallelism is memory-bound.** A full-parallel build of this tree has
OOM-killed the host outright, so the entrypoint computes jobs from *available
memory* (≈1.5 GiB per C++ TU) and exports it as `SYLPH_JOBS`, `CARGO_BUILD_JOBS`
and `CMAKE_BUILD_PARALLEL_LEVEL`. Override with `SYLPH_CPUS` / `SYLPH_MEM_GB`.
## Inside
| command | what |
|---|---|
| `build-canary [Release\|Debug]` | configure + build Canary |
| `build-reborn [build\|test\|ci]` | build/test Reborn, with the disc env wired up |
| `run-canary [flags…]` | launch Canary with the settings this title needs |
| `screenshot [out.png]` | grab the display |
| `sylph-doctor` | self-check |
| `tools/re-capture/*` | the RE toolkit, already on `PATH` |
Layout: project at `/work`, `HOME=/sylph-home/re`, `DISPLAY=:98` — the values
`tools/re-capture/*.sh` already assume, so the existing toolkit runs unmodified.
Build outputs live **outside** the bind mount (`CARGO_TARGET_DIR`,
`XENIA_BUILD_DIR`, both named Docker volumes). The host builds the same trees,
and sharing `target/` or `build/` makes host and container reconfigure and
relink everything the other just did.
## Screenshots
Two layers, and the distinction matters:
* `/usr/local/bin/screenshot` — raw full-root PNG (ImageMagick, falling back to
ffmpeg's x11grab, then xwd).
* `tools/re-capture/bin/screenshot` — **first on `PATH`**, wraps the above and
crops to the *game surface*.
The crop is not cosmetic. Xenia's window is a GTK window whose menu bar pushes
the 1280×720 game image down ~25 px, and every pixel oracle in the toolkit was
measured against the bare game image. When that offset was unaccounted for, one
run sat 300 s in front of a plainly visible MAIN MENU reporting "no main menu".
The wrapper derives the offset from the window's own height rather than a
per-display constant.
For finding a screen at all, prefer `screen_id.py`, which classifies by
whole-image statistics instead of named pixels.
## Vulkan
`mesa-vulkan-drivers` + `vulkan-tools` are installed, so Vulkan works with **no
host GPU** via lavapipe (software — correct, slow). When the host has
`/dev/dri`, the launcher passes the device through and adds the host's `render`
and `video` GIDs, and the entrypoint uses the hardware ICD. Force software with
`SYLPH_VULKAN=sw`. `vulkaninfo --summary` (or `sylph-doctor`) says which you got — and the
entrypoint reports the device that **actually enumerated**, not the one it asked
for, because "I passed `/dev/dri`" and "I have hardware Vulkan" are different
claims.
⚠️ **On an NVIDIA host, `/dev/dri` alone does nothing** — Mesa cannot drive an
NVIDIA card and the proprietary userspace lives outside the image. You need the
NVIDIA Container Toolkit; the launcher detects the situation and tells you the
three commands. Until then Canary runs on lavapipe, which is correct but has not
been observed to reach a rendered frame in a couple of minutes — everything
*else* (guest memory, the JIT, the live-memory toolkit) works fine on it.
## Input, and why there is no virtual gamepad
`run-canary` passes `--hid=file --pad_file=/tmp/xenia_pad.txt`; drive it with
`tools/re-capture/pad.py`. There is deliberately **no `/dev/uinput`**: input
devices are not namespaced, so a virtual pad created in a container registers
with the *host's* input stack and every scripted press leaks onto the user's
desktop.
The trap that wasted a session: 360 menus poll `XamInputGetKeystrokeEx`, not
`GetState` — with `GetKeystroke` stubbed the pad looks completely dead on a
title screen while its own log shows the press arriving.
## Settings that are requirements, not preferences
`run-canary` bakes these in; changing them will cost you an afternoon.
* **`--apu=sdl` with `SDL_AUDIODRIVER=dummy`** — and **no `--audio` flag**,
which is not a cvar here (see below). There is no PulseAudio, so `--apu=nop`
looks like the safe muted choice. It is not: the log fills with
`CreateDriver failed for index=0`, the guest never gets past the intro movie,
and the window stays black for 8+ minutes. SDL against a dummy device is
silent *and* lets the title advance.
* **One emulator at a time**, enforced with a lockfile. Two at once perturbs
both and the box.
* Stale `/dev/shm/xenia_memory_*` from a killed run is removed at launch —
otherwise the memory readers find two candidates and pick the dead one.
## Claude Code
Runs as an unprivileged `agent` user, because `--dangerously-skip-permissions`
is **refused under root**. `./sylph-agent agent` sets `SYLPH_AUTONOMOUS=1` and
the entrypoint adds the flag.
Auth comes from the host `~/.claude`, bind-mounted read-write (token refresh
needs to write). **That directory also holds your memory and project state**, so
the container agent and you share it. Point `SYLPH_CLAUDE_HOME` at a separate
directory to isolate it, or set `ANTHROPIC_API_KEY` instead.
`~/.claude.json` is different: mounted **read-only** at a staging path and
copied in, so the container cannot rewrite your host config — and so a version
skew between the container's Claude Code and yours cannot re-trigger onboarding.
The project is bind-mounted **twice**, at `/work` and at its own host path. The
host path is what makes memory carry over: Claude Code derives its per-project
state key from the working directory, so running at `/work` would hand the agent
an empty project instead of the accumulated one. Verified — a loose run reports
`MEMORY=yes` and reads back the same branch and backlog you see.
## Host prerequisites
* **A Vulkan SDK** (LunarG), for *building* only. Canary's shader step calls
`spirv-opt --canonicalize-ids`, which Ubuntu's packaged SPIRV-Tools (v2025.1)
does not have — the build then dies ~500 objects in, and the error you see is
a Python `TypeError`, not the real message. The launcher mounts the host's SDK
read-only at its own path and sets `VULKAN_SDK`; that also guarantees the
container produces byte-identical shaders to a host build.
* **`nvidia-container-toolkit`**, for hardware Vulkan — see below.
## Things that will waste your afternoon
Each of these was hit while bringing this container up.
* **An unknown xenia flag hangs; it does not error.** `ParseLaunchArguments`
calls `ShowSimpleMessageBox` *before logging is initialised*, and that SDL
dialog blocks on `XIfEvent` forever with nobody to click it. The symptom is a
10×10 window, a completely empty log and no guest memory — which reads like a
hang deep in the emulator. `--audio` is **not** a cvar in this tree despite
appearing in the RE notes; `--apu=sdl` is the real one. If Canary appears to
hang at startup, suspect a typo'd flag first.
* **`/dev/shm` must be `exec`.** Docker mounts it `noexec`, and xenia maps its
JIT code cache out of a shm file. With `noexec` it dies at startup with
"Unable to allocate code cache generated code storage / Cannot initalize
processor", which reads like an address-space clash. The launcher uses
`--tmpfs /dev/shm:rw,exec,…` rather than `--shm-size`.
* **gdb needs root inside the container.** `--cap-add SYS_PTRACE` is passed, but
the *host's* `kernel.yama.ptrace_scope=1` still blocks attaching to a
non-descendant. Use `sudo gdb -p <pid>` (passwordless), or launch the target
under gdb so it is a child.
* **Named volumes need their mount points to exist in the image**, or Docker
creates them root-owned and the first write fails obscurely.
## Known limitation
`build-reborn ci` runs the native legs only. `just ci`'s wasm check does not
build, for a pre-existing reason unrelated to any change under test: the
workspace pins `tokio = { features = ["full"] }`, which pulls `mio`, which
refuses to compile for `wasm32-unknown-unknown`.

52
docker/decoder/bin/build-canary Executable file
View File

@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Configure + build Xenia Canary inside the container.
#
# The build directory is $XENIA_BUILD_DIR (outside the bind-mounted repo) on
# purpose. The host builds this same tree, and CMake caches an absolute compiler
# path and a generator: sharing repo/build between host and container makes each
# one reconfigure and relink everything the other just did.
#
# Parallelism comes from $SYLPH_JOBS, which the entrypoint derives from
# AVAILABLE MEMORY as well as core count — a full-parallel build of this tree
# has OOM-killed the host outright.
#
# build-canary [Release|Debug] [extra cmake --build args]
set -euo pipefail
CONFIG="${1:-Release}"; shift || true
SRC="${PROJECT_DIR:-/work}/xenia-canary"
BUILD="${XENIA_BUILD_DIR:-/sylph-home/re/canary-build}"
JOBS="${SYLPH_JOBS:-2}"
[ -d "$SRC" ] || { echo "build-canary: no source at $SRC" >&2; exit 1; }
# Submodules: this tree has drifted before, and a checkout that changes a
# gitlink fails silently into a half-built third_party. Report rather than fix,
# because one submodule here carries an in-tree cmake build whose untracked
# artifacts block an update.
if ! git -C "$SRC" submodule status --recursive 2>/dev/null | grep -qv '^ '; then
:
else
echo "build-canary: note — submodules are not all at their recorded commits:" >&2
git -C "$SRC" submodule status 2>/dev/null | grep -v '^ ' | sed 's/^/ /' >&2
fi
if [ ! -f "$BUILD/CMakeCache.txt" ]; then
echo "==> configuring $BUILD ($CONFIG, Ninja Multi-Config, clang $(clang --version | head -1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+'))"
cmake -S "$SRC" -B "$BUILD" -G "Ninja Multi-Config" \
-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \
-DXENIA_BUILD_TESTS=OFF -DXENIA_BUILD_MISC=OFF \
-DXENIA_ENABLE_LTO=OFF
fi
echo "==> building $CONFIG with -j$JOBS"
cmake --build "$BUILD" --config "$CONFIG" --parallel "$JOBS" --target xenia_canary "$@"
BIN="$BUILD/bin/Linux/$CONFIG/xenia_canary"
if [ -x "$BIN" ]; then
echo "==> $BIN"
echo " run it with: run-canary"
else
echo "build-canary: target did not produce $BIN" >&2
exit 1
fi

47
docker/decoder/bin/build-reborn Executable file
View File

@@ -0,0 +1,47 @@
#!/usr/bin/env bash
# Build / test Sylpheed Reborn inside the container.
#
# CARGO_TARGET_DIR points outside the bind-mounted repo (see the Dockerfile), so
# this never fights the host's incremental state.
#
# build-reborn cargo build --workspace
# build-reborn test cargo test --workspace, disc tests enabled
# build-reborn ci fmt + clippy + test
# build-reborn <cargo args...>
set -euo pipefail
SRC="${PROJECT_DIR:-/work}/Syplheed-Reborn"
JOBS="${SYLPH_JOBS:-2}"
cd "$SRC"
# The disc-gated integration tests self-skip when this is unset, and a green run
# then means almost nothing — point them at the extracted disc if it is there.
if [ -z "${SYLPHEED_DISC:-}" ]; then
for c in "${PROJECT_DIR:-/work}/sylph_extract" "$SRC/../sylph_extract"; do
[ -d "$c/dat" ] && { export SYLPHEED_DISC="$(readlink -f "$c")"; break; }
done
fi
[ -n "${SYLPHEED_DISC:-}" ] && export SYLPHEED_RES3D="$SYLPHEED_DISC/hidden/resource3d"
if [ -z "${SYLPHEED_ISO:-}" ]; then
iso="$(find "${PROJECT_DIR:-/work}" -maxdepth 2 -iname '*.iso' -print -quit 2>/dev/null || true)"
[ -n "$iso" ] && export SYLPHEED_ISO="$iso"
fi
echo "==> SYLPHEED_DISC=${SYLPHEED_DISC:-<unset — disc tests will SKIP>}" >&2
export CARGO_BUILD_JOBS="$JOBS"
case "${1:-build}" in
build) shift || true; exec cargo build --workspace "$@" ;;
test) shift || true; exec cargo test --workspace "$@" ;;
ci)
cargo fmt --all -- --check
cargo clippy --workspace -- -D warnings
cargo test --workspace
# NOTE: `just ci` also checks wasm32. That leg does not build, and not for
# any reason in this crate: the workspace pins tokio with features=["full"],
# which pulls mio, which refuses to compile for wasm32. Left out here rather
# than reported as a failure of the change under test.
echo "==> native CI green (wasm leg skipped — see the note in this script)"
;;
*) exec cargo "$@" ;;
esac

View File

@@ -0,0 +1,72 @@
#!/usr/bin/expect -f
# Start Claude Code for an unattended run, answering the first-run gates.
#
# Claude Code has three one-time interactive prompts, and every one of them is a
# silent, permanent hang for an agent with nobody at the keyboard — no error, no
# log line, just a container that looks healthy and does nothing:
#
# 1. the theme picker (first run, or whenever the installed version is
# newer than lastOnboardingVersion)
# 2. "do you trust this folder?" (per workspace)
# 3. the Bypass Permissions disclaimer (for --dangerously-skip-permissions)
#
# `seed-claude-config.py` pre-sets the config keys for 1 and 2. The disclaimer
# has no such key — it is meant to be accepted by a person once — so it is
# answered here instead. That is the honest reading of `sylph-agent loose`: the
# operator accepted it by choosing to run this, and the container is exactly the
# sandbox the warning asks for.
#
# ── Why the patterns are single words ──
# Claude Code draws its UI with ABSOLUTE COLUMN escapes between words, so the
# prompt arrives on the wire as
#
# 2.\x1b[8GYes,\x1b[13GI\x1b[15Gaccept
#
# A multi-word pattern like {Yes, I accept} therefore never matches, and the
# wrapper sits there looking like it is not running at all. Match one word.
set timeout 90
log_user 1
# Give the pty a wide, tall geometry. A detached `docker run -t` defaults to
# 80x24, and Claude Code hard-wraps to the terminal width — which truncates the
# Remote Control URL to "https://claude.ai/code/session_01…" in the one place
# you need to read it, and makes `docker logs` nearly unusable generally.
set stty_init "rows 50 cols 200"
set answered_theme 0
set answered_trust 0
set answered_bypass 0
spawn -noecho claude --dangerously-skip-permissions {*}$argv
expect {
-re {Choose} {
if {!$answered_theme} { set answered_theme 1; send "\r" }
exp_continue
}
-re {trust} {
if {!$answered_trust} {
set answered_trust 1
send_user "\n\[claude-autonomous] accepting the workspace trust prompt\n"
send "1\r"
}
exp_continue
}
-re {accept} {
if {!$answered_bypass} {
set answered_bypass 1
send_user "\n\[claude-autonomous] accepting the Bypass Permissions disclaimer\n"
send "2\r"
}
exp_continue
}
timeout {
# No new gate for a while: the session is up (or never had one). Stop
# matching so nothing later in the run can be answered by accident.
}
eof { exit }
}
# Hand the terminal over for the rest of the run.
interact

82
docker/decoder/bin/push-work Executable file
View File

@@ -0,0 +1,82 @@
#!/usr/bin/env bash
# Push the current topic branch to origin — the ONLY sanctioned way out of the
# container.
#
# Why a wrapper instead of plain `git push`:
#
# * **`main` and shared branches are refused.** The agent commits to
# `auto/<topic>`; a human merges. A token that can push anywhere is one
# confused iteration away from rewriting the consolidated line.
# * **Force-push is refused**, always. Nothing here needs it, and history
# rewriting is the one mistake that cannot be undone by merging.
# * It pushes the CURRENT branch only, by name, so a stray `--all` cannot
# publish another agent's worktree branch mid-experiment.
#
# Credentials come from a file mounted read-only at ~/.git-credentials (see
# `sylph-agent`). They are never printed, never logged, and never passed on a
# command line.
#
# push-work push the current branch, and any annotated tags on it
#
# --follow-tags publishes ANNOTATED tags reachable from the pushed commits. That
# is what makes a pinned decoder state durable: the port depends on commits of
# ours by revision, and a commit reachable only from a topic branch is orphaned
# by a squash-merge. Lightweight tags are deliberately not pushed.
# push-work --dry-run say what it would do
set -euo pipefail
DRY=0
[ "${1:-}" = "--dry-run" ] && DRY=1
repo_root=$(git rev-parse --show-toplevel 2>/dev/null) || {
echo "push-work: not inside a git repository" >&2; exit 1; }
cd "$repo_root"
branch=$(git rev-parse --abbrev-ref HEAD)
if [ "$branch" = "HEAD" ]; then
echo "push-work: detached HEAD — check out a branch first" >&2; exit 1
fi
case "$branch" in
auto/*) ;;
*)
echo "push-work: refusing to push '$branch'." >&2
echo " Only auto/* topic branches may leave the container; a human merges" >&2
echo " them into main. Move your work: git switch -c auto/<topic>" >&2
exit 1 ;;
esac
if [ ! -s "$HOME/.git-credentials" ]; then
echo "push-work: no credentials mounted at ~/.git-credentials." >&2
echo " The host must start the container with SYLPH_GIT_CREDENTIALS pointing" >&2
echo " at a file containing one line:" >&2
echo " https://<user>:<token>@git.mc02.dev" >&2
exit 1
fi
# `store` reads the file we mounted; nothing is written back (it is read-only).
# Applied to THIS COMMAND ONLY, via `-c`, never `git config --local`.
#
# Writing it to --local config persists it in the repository, and this repo is a
# bind mount the host also uses -- so the host's git inherited
# `store --file=/sylph-home/re/.git-credentials`, a path that exists only inside
# the container, and every host push then failed with
# `unable to get credential storage lock: No such file or directory`.
#
# A tool that configures a shared repository to suit itself breaks every other
# user of that repository. Keep it to the invocation.
CRED_HELPER="store --file=$HOME/.git-credentials"
ahead=$(git rev-list --count "origin/$branch..$branch" 2>/dev/null || git rev-list --count HEAD)
echo "push-work: $branch — $ahead commit(s) to publish"
if [ "$DRY" = 1 ]; then
echo "push-work: --dry-run, stopping here"
exit 0
fi
# --force-with-lease is deliberately NOT offered. If this is rejected as
# non-fast-forward, someone else moved the branch: fetch and merge, do not
# overwrite.
git -c "credential.helper=$CRED_HELPER" push --follow-tags --set-upstream origin "$branch"
echo "push-work: pushed $branch"

99
docker/decoder/bin/run-canary Executable file
View File

@@ -0,0 +1,99 @@
#!/usr/bin/env bash
# Launch Xenia Canary with the settings this title actually needs.
#
# Four of these are not preferences — they are measured requirements, and every
# one of them cost a debugging session before it was pinned down:
#
# --apu=sdl + SDL_AUDIODRIVER=dummy
# There is no PulseAudio here, so `--apu=nop` looks like the safe muted
# choice. It is not: the log then fills with "CreateDriver failed for
# index=0", the guest never gets past the intro movie, and the window
# stays black for 8+ minutes. The SDL driver against a dummy device is
# both silent AND lets the title advance.
#
# NO --audio flag
# The RE notes say "--audio --apu=sdl". `--audio` is NOT a cvar in this
# tree, and an unknown argument is not a friendly error: xenia calls
# ShowSimpleMessageBox from ParseLaunchArguments, BEFORE logging is
# initialised, and that SDL dialog blocks on XIfEvent forever. Headless,
# the symptom is a 10x10 window, an empty log, and no guest memory —
# which reads like a hang deep in the emulator rather than a typo.
# If this ever appears to hang at startup, suspect a bad flag first.
#
# --hid=file --pad_file=...
# The old vgamepad path made its device through /dev/uinput, which is NOT
# namespaced — a pad created inside a container registers with the HOST's
# input stack and every scripted press leaks to the user's desktop. This
# driver reads a text file instead. Drive it with tools/re-capture/pad.py.
# Trap worth remembering: 360 menus poll XamInputGetKeystrokeEx, not
# GetState, so a stubbed GetKeystroke looks like a completely dead pad.
#
# one instance at a time
# Two emulators (or ours + canary) at once perturbs both and the box.
# Enforced with a lockfile rather than left to discipline.
#
# Usage: run-canary [extra xenia flags...]
# ISO from $SYLPH_ISO, else the first *.iso under $PROJECT_DIR.
# Binary from $XENIA_BIN, else the container build, else the repo build.
set -u
LOCK=/tmp/xenia-canary.lock
exec 9>"$LOCK"
if ! flock -n 9; then
echo "run-canary: an emulator is already running (lock $LOCK)." >&2
echo " Only one at a time — kill it first: pkill -x xenia_canary" >&2
exit 1
fi
PROJECT_DIR="${PROJECT_DIR:-/work}"
# ── Binary ───────────────────────────────────────────────────────────────────
pick_bin() {
[ -n "${XENIA_BIN:-}" ] && { echo "$XENIA_BIN"; return; }
for c in \
"${XENIA_BUILD_DIR:-/sylph-home/re/canary-build}/bin/Linux/Release/xenia_canary" \
"${XENIA_BUILD_DIR:-/sylph-home/re/canary-build}/bin/Linux/Debug/xenia_canary" \
"$PROJECT_DIR/xenia-canary/build/bin/Linux/Release/xenia_canary" \
"$PROJECT_DIR/xenia-canary/build/bin/Linux/Debug/xenia_canary"; do
[ -x "$c" ] && { echo "$c"; return; }
done
}
BIN="$(pick_bin)"
if [ -z "${BIN:-}" ]; then
echo "run-canary: no xenia_canary binary found. Build one with: build-canary" >&2
exit 1
fi
# ── ISO ──────────────────────────────────────────────────────────────────────
ISO="${SYLPH_ISO:-}"
if [ -z "$ISO" ]; then
# Prefer a REAL file over a symlink and take the largest: the tree carries
# `xenia-rs/sylpheed.iso` as a symlink to the retail image, and a symlink has
# already cost a session once (Wine could not resolve it -> "path invalid").
ISO="$(find "$PROJECT_DIR" -maxdepth 2 -type f -iname '*.iso' -printf '%s\t%p\n' 2>/dev/null \
| sort -rn | head -1 | cut -f2-)"
fi
if [ -z "$ISO" ] || [ ! -f "$ISO" ]; then
echo "run-canary: no ISO. Set SYLPH_ISO=/path/to/game.iso" >&2
exit 1
fi
ISO="$(readlink -f "$ISO")"
export SDL_AUDIODRIVER="${SDL_AUDIODRIVER:-dummy}"
export DISPLAY="${DISPLAY:-:98}"
PAD="${XENIA_PAD_FILE:-/tmp/xenia_pad.txt}"
: > "$PAD"
# Guest memory is backed by /dev/shm; a stale file from a killed run confuses
# the memory readers (gmem.py finds two candidates and picks the dead one).
rm -f /dev/shm/xenia_memory_* /dev/shm/xenia_code_cache_* 2>/dev/null || true
echo "run-canary: $BIN" >&2
echo " iso: $ISO" >&2
echo " pad: $PAD display: $DISPLAY shm: $(df -h /dev/shm | awk 'NR==2{print $2}')" >&2
exec "$BIN" "$ISO" \
--apu=sdl \
--hid=file --pad_file="$PAD" \
--mute=true \
"$@"

51
docker/decoder/bin/screenshot Executable file
View File

@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Raw full-root PNG grab of the headless display.
#
# This is deliberately the *uncropped* root window, because
# `tools/re-capture/bin/screenshot` is a wrapper that calls this one as its raw
# grabber and then crops to the game surface — xenia's window is a GTK window
# whose menu bar pushes the 1280x720 game image down ~25 px, and every pixel
# oracle in the toolkit was measured against the bare game image. That wrapper
# directory is first on PATH, so scripts calling `screenshot` get the cropped
# game surface and this stays the honest raw grab underneath it.
#
# screenshot [out.png] default: $HOME/shots/shot-NNNN.png
set -u
OUT="${1:-}"
if [ -z "$OUT" ]; then
dir="${HOME:-/tmp}/shots"; mkdir -p "$dir"
n_file="$dir/.counter"
n=$(( $(cat "$n_file" 2>/dev/null || echo 0) + 1 )); echo "$n" > "$n_file"
OUT="$dir/shot-$(printf '%04d' "$n").png"
fi
mkdir -p "$(dirname "$OUT")"
if ! xdpyinfo >/dev/null 2>&1; then
echo "screenshot: no display on ${DISPLAY:-<unset>}" >&2
exit 1
fi
# ImageMagick first. `import` talks X11 directly and captures a window that is
# mid-redraw without tearing the way a video grabber can.
if command -v import >/dev/null 2>&1 && import -silent -window root "$OUT" 2>/dev/null; then
echo "$OUT"; exit 0
fi
# Fallback: ffmpeg's x11grab. Needs an explicit size, so read it off the server
# rather than assuming the geometry.
if command -v ffmpeg >/dev/null 2>&1; then
size=$(xdpyinfo | awk '/dimensions:/{print $2; exit}')
if ffmpeg -loglevel error -y -f x11grab -draw_mouse 0 \
-video_size "$size" -i "$DISPLAY" -frames:v 1 "$OUT" 2>/dev/null; then
echo "$OUT"; exit 0
fi
fi
# Last resort: xwd, which is always present with x11-utils.
if command -v xwd >/dev/null 2>&1 && command -v convert >/dev/null 2>&1; then
xwd -root -silent | convert xwd:- "$OUT" && { echo "$OUT"; exit 0; }
fi
echo "screenshot: no working capture backend" >&2
exit 1

View File

@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""Mark Claude Code's onboarding as complete in ~/.claude.json.
Claude Code re-runs its first-run wizard whenever `lastOnboardingVersion` does
not match the installed version. In a terminal that is a one-key prompt; for an
unattended agent it is a silent, permanent hang on the theme picker — no error,
no log line, and the container looks like it started fine.
It also pre-accepts the workspace's trust prompt. That is a SECOND, separate
first-run gate: even past onboarding, Claude Code asks "is this a project you
trust?" per directory, and this repo's settings pre-approve 442 tool permissions
so the prompt is emphatic about it. Unattended, it is another silent hang.
Pre-accepting is safe here precisely because the trust question is being
answered by the person who built and launched the container, for their own
repository — it is not a judgement being made on their behalf about someone
else's code.
Usage: seed-claude-config.py <path to .claude.json> <installed version> [workspace...]
"""
import json
import os
import sys
def main() -> int:
if len(sys.argv) < 3:
print(f"usage: {sys.argv[0]} <config.json> <version> [workspace...]",
file=sys.stderr)
return 2
path, version = sys.argv[1], sys.argv[2]
workspaces = sys.argv[3:]
cfg = {}
if os.path.exists(path) and os.path.getsize(path):
try:
with open(path) as f:
cfg = json.load(f)
except (OSError, ValueError):
# A corrupt or partial config is not worth failing the container
# over — start from empty rather than block the run.
cfg = {}
if not isinstance(cfg, dict):
cfg = {}
cfg["hasCompletedOnboarding"] = True
cfg["lastOnboardingVersion"] = version
cfg.setdefault("theme", "dark")
# The THIRD interactive gate: --dangerously-skip-permissions shows a
# "Bypass Permissions mode / you accept all responsibility" confirmation on
# first use. Key name taken from the shipped binary's own strings, not
# guessed. Accepting it here is the whole point of `sylph-agent loose` —
# the container is the sandbox that warning asks you to provide.
cfg["bypassPermissionsModeAccepted"] = True
# A FOURTH gate, and this one fires mid-session rather than at startup, so
# the pty wrapper has already handed over by then: an upsell asking whether
# to try the fullscreen renderer. It is shown while
# `fullscreenUpsellSeenCount` is below an internal threshold, so park it far
# above. Found by reading the shipped binary's strings, same as the others.
cfg["fullscreenUpsellSeenCount"] = 9999
# An auto-update mid-run would restart the process and lose the loop's
# scheduled wake-up, so pin the version the container was built with.
cfg["autoUpdates"] = False
projects = cfg.setdefault("projects", {})
if not isinstance(projects, dict):
projects = cfg["projects"] = {}
for ws in workspaces:
entry = projects.setdefault(ws, {})
if not isinstance(entry, dict):
entry = projects[ws] = {}
entry["hasTrustDialogAccepted"] = True
entry.setdefault("projectOnboardingSeenCount", 1)
entry["hasClaudeMdExternalIncludesApproved"] = True
entry["hasClaudeMdExternalIncludesWarningShown"] = True
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(cfg, f, indent=2)
os.replace(tmp, path)
return 0
if __name__ == "__main__":
sys.exit(main())

88
docker/decoder/bin/sylph-doctor Executable file
View File

@@ -0,0 +1,88 @@
#!/usr/bin/env bash
# Prove the container can actually do the four things it exists for, before an
# unattended agent spends an hour discovering otherwise.
#
# Every check here stands for a failure that has already happened once: a
# display that was not there, a missing numpy that looked like a logic bug, a
# /dev/shm too small for guest memory, a Vulkan stack with no ICD.
set -u
fail=0
ok() { printf ' \033[32m✔\033[0m %s\n' "$*"; }
bad() { printf ' \033[31m✖\033[0m %s\n' "$*"; fail=$((fail+1)); }
warn() { printf ' \033[33m!\033[0m %s\n' "$*"; }
echo "── resources ──"
# nproc shows the HOST's cores: --cpus is a quota, not a mask. Report both so
# "12 cpus" is never mistaken for 12 cpus' worth of throughput.
quota="unlimited"
if [ -r /sys/fs/cgroup/cpu.max ]; then
read -r q p < /sys/fs/cgroup/cpu.max
[ "$q" != max ] && quota="$(( q / p )) (quota)"
fi
echo " cpus: $(nproc) visible, $quota"
if [ -r /sys/fs/cgroup/memory.max ]; then
m=$(cat /sys/fs/cgroup/memory.max)
[ "$m" = max ] && warn "memory: UNLIMITED — the half-the-box cap is not applied" \
|| ok "memory cap: $(( m / 1024 / 1024 / 1024 )) GiB"
fi
shm=$(df -BM /dev/shm | awk 'NR==2{print $2}' | tr -d M)
# Guest memory for a 512 MB console plus the code cache does not fit in
# Docker's 64 MB default, and the symptom is an mmap error, not a disk-full one.
[ "${shm:-0}" -ge 512 ] && ok "/dev/shm: ${shm} MiB" || bad "/dev/shm only ${shm:-?} MiB — need >=512; pass --shm-size"
echo "── toolchain ──"
for t in clang clang++ cmake ninja cargo rustc python3 node claude; do
command -v "$t" >/dev/null && ok "$t ($("$t" --version 2>/dev/null | head -1))" || bad "$t missing"
done
echo "── python (dynamic RE) ──"
# numpy and PIL missing is the specific hole that silently disabled entities2.py
# and every image oracle in the toolkit.
for m in numpy PIL duckdb; do
python3 -c "import $m" 2>/dev/null && ok "python: $m" || bad "python: $m MISSING"
done
echo "── display ──"
if xdpyinfo >/dev/null 2>&1; then
ok "display $DISPLAY ($(xdpyinfo | awk '/dimensions:/{print $2; exit}'))"
pgrep -x openbox >/dev/null && ok "openbox running" || warn "no window manager — window geometry oracles will misread"
out=$(screenshot /tmp/_doctor.png 2>&1) && [ -s /tmp/_doctor.png ] \
&& ok "screenshot works -> $(identify -format '%wx%h' /tmp/_doctor.png 2>/dev/null || echo ok)" \
|| bad "screenshot failed: $out"
rm -f /tmp/_doctor.png
else
bad "no display on ${DISPLAY:-<unset>}"
fi
echo "── vulkan ──"
if command -v vulkaninfo >/dev/null 2>&1; then
dev=$(vulkaninfo --summary 2>/dev/null | grep -m3 -E 'deviceName' | sed 's/^ *//')
[ -n "$dev" ] && { ok "Vulkan devices:"; echo "$dev" | sed 's/^/ /'; } \
|| bad "vulkaninfo found no device (ICD missing?)"
else
bad "vulkaninfo missing"
fi
# Judge by what enumerated, not by whether a device node is present: an NVIDIA
# card needs the NVIDIA Container Toolkit, and /dev/dri alone does nothing.
case "${dev:-}" in
*llvmpipe*|*lavapipe*)
warn "SOFTWARE Vulkan only — correct but slow."
command -v nvidia-smi >/dev/null 2>&1 \
&& warn " host has an NVIDIA GPU: install nvidia-container-toolkit for hardware" ;;
"") ;;
*) ok "hardware Vulkan" ;;
esac
echo "── project ──"
[ -d /work/xenia-canary ] && ok "/work/xenia-canary" || bad "/work/xenia-canary not mounted"
[ -d /work/Syplheed-Reborn ] && ok "/work/Syplheed-Reborn" || bad "/work/Syplheed-Reborn not mounted"
iso=$(find /work -maxdepth 2 -type f -iname '*.iso' -printf '%s\t%p\n' 2>/dev/null | sort -rn | head -1 | cut -f2-)
[ -n "$iso" ] && ok "ISO: $iso" || warn "no ISO under /work — run-canary needs SYLPH_ISO"
[ -d /work/sylph_extract/dat ] && ok "extracted disc (disc-gated tests will run)" \
|| warn "no extracted disc — Reborn disc tests will SKIP"
[ -w /sylph-home/re/.claude ] && ok "~/.claude writable (token refresh works)" \
|| warn "~/.claude not writable — Claude Code may fail to refresh auth"
echo
[ "$fail" -eq 0 ] && { echo "all good."; exit 0; }
echo "$fail check(s) failed."; exit 1

163
docker/decoder/entrypoint.sh Executable file
View File

@@ -0,0 +1,163 @@
#!/usr/bin/env bash
# Bring up the headless display, then hand over to the command.
#
# Xvfb and openbox are started HERE, as children of PID 1 (tini), rather than by
# the toolkit scripts. That is the fix for the long-standing "Xvfb and the
# emulator die on their own every few minutes" note: nothing owned those
# processes, so nothing kept them alive, and a run could sit for 300 s in front
# of a visible MAIN MENU reporting "no main menu" because the display had gone.
# A container-lifetime display makes that failure mode impossible.
set -euo pipefail
log() { printf '[entrypoint] %s\n' "$*" >&2; }
DISPLAY="${DISPLAY:-:98}"
GEOM="${SCREEN_GEOMETRY:-1280x720x24}"
export DISPLAY
# ── Display ──────────────────────────────────────────────────────────────────
if ! xdpyinfo -display "$DISPLAY" >/dev/null 2>&1; then
rm -f "/tmp/.X${DISPLAY#:}-lock" "/tmp/.X11-unix/X${DISPLAY#:}" 2>/dev/null || true
# GLX and RANDR are both required: Canary's window is GTK+OpenGL even when the
# graphics backend is Vulkan, and xwininfo-based screen oracles need RANDR.
Xvfb "$DISPLAY" -screen 0 "$GEOM" -ac -nolisten tcp \
+extension GLX +extension RANDR >/tmp/xvfb.log 2>&1 &
for _ in $(seq 1 50); do
xdpyinfo -display "$DISPLAY" >/dev/null 2>&1 && break
sleep 0.2
done
fi
if ! xdpyinfo -display "$DISPLAY" >/dev/null 2>&1; then
log "FATAL: no display on $DISPLAY — see /tmp/xvfb.log"
exit 1
fi
# A window manager is not cosmetic here: without one the emulator window is
# never mapped at a known position, and every pixel oracle reads the wrong rows.
if ! pgrep -x openbox >/dev/null 2>&1; then
openbox >/tmp/openbox.log 2>&1 &
sleep 0.5
fi
log "display $DISPLAY ready ($GEOM)"
# ── Vulkan ───────────────────────────────────────────────────────────────────
# Prefer the real GPU when /dev/dri was passed through; fall back to lavapipe,
# which is slow but correct and needs no host device.
LVP=$(ls /usr/share/vulkan/icd.d/lvp_icd*.json 2>/dev/null | head -1)
if [ "${SYLPH_VULKAN:-auto}" = "sw" ] || [ ! -e /dev/dri/renderD128 ]; then
[ -n "$LVP" ] && export VK_ICD_FILENAMES="$LVP"
else
unset LIBGL_ALWAYS_SOFTWARE
fi
# Report what Vulkan ACTUALLY enumerated, not what we asked for. Announcing
# "host GPU via /dev/dri" because the device node exists is how an agent ends up
# believing it has hardware while running llvmpipe — an NVIDIA card needs the
# NVIDIA Container Toolkit, and /dev/dri alone does nothing for it.
if command -v vulkaninfo >/dev/null 2>&1; then
vkdev=$(vulkaninfo --summary 2>/dev/null | awk -F= '/deviceName/{gsub(/^ +| +$/,"",$2); print $2; exit}')
case "${vkdev:-}" in
"") log "Vulkan: NO DEVICE — vulkaninfo enumerated nothing" ;;
llvmpipe*|lavapipe*) log "Vulkan: $vkdev (SOFTWARE — correct but slow)" ;;
*) log "Vulkan: $vkdev (hardware)" ;;
esac
fi
# ── Build parallelism ────────────────────────────────────────────────────────
# Bounded by MEMORY, not just cores. A full-parallel build of this tree has
# OOM-killed the host outright, and inside a half-the-box container the ceiling
# is lower still. ~1.5 GiB per C++ TU is the rule of thumb that has held.
# nproc reports the HOST's core count: --cpus is a CFS quota, not a mask. Using
# it would oversubscribe a half-the-box container by exactly 2x, so read the
# quota the cgroup actually grants.
cpus=$(nproc)
if [ -r /sys/fs/cgroup/cpu.max ]; then
read -r _q _p < /sys/fs/cgroup/cpu.max || true
if [ "${_q:-max}" != max ] && [ "${_p:-0}" -gt 0 ]; then
cpus=$(( (_q + _p - 1) / _p ))
[ "$cpus" -lt 1 ] && cpus=1
fi
fi
mem_gib=$(awk '/MemAvailable/{printf "%d", $2/1048576}' /proc/meminfo)
# MemAvailable is the HOST's too under cgroup v2; prefer the container's cap.
if [ -r /sys/fs/cgroup/memory.max ]; then
_m=$(cat /sys/fs/cgroup/memory.max)
[ "$_m" != max ] && mem_gib=$(( _m / 1073741824 ))
fi
[ "${mem_gib:-0}" -lt 1 ] && mem_gib=1
by_mem=$(( mem_gib * 2 / 3 ))
[ "$by_mem" -lt 1 ] && by_mem=1
jobs=$(( cpus < by_mem ? cpus : by_mem ))
export SYLPH_JOBS="$jobs" CARGO_BUILD_JOBS="$jobs" CMAKE_BUILD_PARALLEL_LEVEL="$jobs"
log "build parallelism: $jobs (cpus=$cpus, mem=${mem_gib}GiB avail)"
mkdir -p "$HOME/shots" "$HOME/logs"
# ── The repository, cloned into THIS AGENT'S OWN volume ─────────────────────
# Not a bind mount of a human's working tree. That arrangement bit this project
# three times: an agent's `git config --local` captured a human's commits, a
# credential helper leaked a container-only path onto the host, and a `git add
# -A` swept an agent's in-flight files into somebody else's commit. Separate
# checkouts make all three impossible rather than discouraged.
#
# Cloned ONCE. Never auto-pulled: pulling under a running agent moves files out
# from under whatever it is mid-edit, which is the same class of bug again.
if [ ! -d /work/.git ]; then
echo "[entrypoint] cloning ${SYLPH_REPO_URL:-https://git.mc02.dev/fabi/Sylpheed.git} into /work"
git clone --quiet "${SYLPH_REPO_URL:-https://git.mc02.dev/fabi/Sylpheed.git}" /work || {
echo "[entrypoint] clone FAILED -- the agent has no repository" >&2; }
else
echo "[entrypoint] /work is at $(git -C /work rev-parse --short HEAD 2>/dev/null) on $(git -C /work rev-parse --abbrev-ref HEAD 2>/dev/null)"
fi
# The shared exchange, for transient files that must not enter git history.
mkdir -p /exchange/files 2>/dev/null || true
# ── Claude Code config ───────────────────────────────────────────────────────
# Seed ~/.claude.json from the host's read-only copy, then stamp onboarding as
# complete. Claude Code re-runs its first-run wizard whenever
# lastOnboardingVersion differs from the installed version — so a container with
# a newer Claude than the host stops on the theme picker, with no error and no
# log line, and an unattended agent sits there forever.
if [ -f "$HOME/.claude.host.json" ] && [ ! -s "$HOME/.claude.json" ]; then
cp "$HOME/.claude.host.json" "$HOME/.claude.json" 2>/dev/null || true
fi
# `credential.helper=store` rewrites this file by rename-over-target, which
# fails with EBUSY on a bind mount -- reported as `fatal: unable to write
# credential store`, while the push itself succeeds. A fatal line that is
# routinely wrong teaches the reader to ignore the one that is real.
if [ -f "$HOME/.git-credentials.host" ]; then
cp "$HOME/.git-credentials.host" "$HOME/.git-credentials" 2>/dev/null || true
chmod 600 "$HOME/.git-credentials" 2>/dev/null || true
fi
CLAUDE_VER=$(claude --version 2>/dev/null | grep -oE '^[0-9][0-9.]*' || echo 0.0.0)
python3 /usr/local/bin/seed-claude-config.py "$HOME/.claude.json" "$CLAUDE_VER" \
"$PWD" "${PROJECT_DIR:-/work}" "$HOME" || true
chmod 600 "$HOME/.claude.json" 2>/dev/null || true
# ── Claude Code ──────────────────────────────────────────────────────────────
if [ "${SYLPH_AUTONOMOUS:-0}" = "1" ]; then
# Drop the image's default CMD first, or `claude` is handed the literal string
# "bash" as its prompt and answers a question nobody asked.
if [ "$#" -eq 1 ] && [ "$1" = "bash" ]; then
set --
fi
# The flag the user asked for. It is refused under root, which is why this
# image runs as `agent`.
# Remote Control registers the session with your account so you can chat with
# the agent from claude.ai or your phone — the point of a detached run being
# that you are not sitting in front of it. The name is passed EXPLICITLY: the
# flag's value is optional, so a bare `--remote-control` would swallow the
# /loop prompt that follows as the session name.
if [ "${SYLPH_REMOTE:-1}" != "0" ]; then
set -- --remote-control "${SYLPH_REMOTE_NAME:-sylpheed-agent}" "$@"
log "Remote Control enabled as '${SYLPH_REMOTE_NAME:-sylpheed-agent}'"
fi
# claude-autonomous wraps `claude --dangerously-skip-permissions` in a pty and
# answers the one-time first-run gates. The Bypass Permissions disclaimer in
# particular has no config key that skips it, so unattended it hangs forever.
set -- claude-autonomous "$@"
log "starting Claude Code with --dangerously-skip-permissions in $(pwd)"
fi
exec "$@"

325
docker/decoder/sylph-decoder Executable file
View File

@@ -0,0 +1,325 @@
#!/usr/bin/env bash
# Host-side launcher for the Sylpheed RE agent container.
#
# Caps the container at HALF the machine's CPUs and memory, computed at run time
# so it stays half on whatever box it lands on.
#
# ./sylph-agent build build (or rebuild) the image
# ./sylph-agent shell interactive shell in the container
# ./sylph-agent agent [prompt] Claude Code, --dangerously-skip-permissions
# ./sylph-agent loose [task] turn it loose: detached, /loop, self-paced
# ./sylph-agent logs [-f] what the loose agent is doing
# ./sylph-agent remote print the Remote Control link (chat from anywhere)
# ./sylph-agent attach attach to the loose agent's session
# ./sylph-agent run <cmd...> one-shot command
# ./sylph-agent stop stop it
#
# Environment:
# SYLPH_PROJECT host project root (default: three levels up from this file)
# SYLPH_CLAUDE_HOME host dir mounted as the agent's ~/.claude
# (default: $HOME/.claude — shares auth AND memory with you)
# SYLPH_VULKAN=sw force software Vulkan (lavapipe) even if /dev/dri exists
# SYLPH_REMOTE=0 do NOT enable Remote Control (default: enabled for `loose`)
# SYLPH_REMOTE_NAME Remote Control session name (default: sylpheed-agent)
# SYLPH_GIT_CREDENTIALS file with `https://<user>:<token>@host` for push-work
# (default: $HOME/.sylph-git-credentials)
# SYLPH_LOOP_INTERVAL fixed loop cadence, e.g. 30m (default: 45m)
# SYLPH_CPUS / SYLPH_MEM_GB override the computed half
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
IMAGE="${SYLPH_IMAGE:-sylpheed-agent:latest}"
NAME="${SYLPH_NAME:-sylpheed-agent}"
PROJECT="${SYLPH_PROJECT:-$(cd "$HERE/../../.." && pwd)}"
# ── Half the box ─────────────────────────────────────────────────────────────
# LC_ALL=C is required, not tidiness: under a locale with a comma decimal
# separator (de_DE and friends) awk prints "6,0" and docker rejects it as
# --cpus with "failed to parse as a rational number".
HOST_CPUS=$(nproc)
HOST_MEM_KB=$(awk '/MemTotal/{print $2}' /proc/meminfo)
# Fixed, not "half the host": half was right when this was the only agent. There
# are now two, and a Referee is planned, so the budget is split deliberately
# instead of each container claiming half of a box it shares. The decoder gets
# the larger share because it builds and drives the emulator.
CPUS="${SYLPH_CPUS:-5}"
MEM_GB="${SYLPH_MEM_GB:-6}"
[ "$MEM_GB" -lt 2 ] && MEM_GB=2
# /dev/shm holds the emulator's guest memory (gmem.py reads it there). Docker's
# 64 MB default is far too small for a 512 MB console address space, and the
# failure is an obscure mmap error rather than an out-of-space message. tmpfs
# pages count against the memory cap, so take a third of it and no more.
SHM_GB=$(( MEM_GB / 3 )); [ "$SHM_GB" -lt 1 ] && SHM_GB=1
CLAUDE_JSON="${SYLPH_CLAUDE_JSON:-$HOME/.claude.json}"
if [ ! -f "$CLAUDE_JSON" ]; then
echo "==> WARNING: $CLAUDE_JSON does not exist." >&2
echo " Docker would create a DIRECTORY at that path inside the container," >&2
echo " and Claude Code would fail confusingly. Run \`claude\` once on the" >&2
echo " host first, or set SYLPH_CLAUDE_JSON." >&2
fi
usage() { sed -n '2,20p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; }
docker_args() {
local -n _out=$1
_out=(
--name "$NAME"
--hostname sylph-agent
# ── the cap ──
--cpus "$CPUS"
--memory "${MEM_GB}g"
--memory-swap "${MEM_GB}g" # no swap escape hatch: a swapping build
# thrashes the whole host, which is the
# failure this cap exists to prevent
--pids-limit 4096
# /dev/shm as an EXEC-capable tmpfs, not --shm-size. Docker's default mounts
# it `noexec`, and xenia maps its JIT code cache out of a shm file at a fixed
# address — so with noexec it dies at startup with "Unable to allocate code
# cache generated code storage / Cannot initalize processor", which reads
# like an address-space clash rather than a mount flag.
--tmpfs "/dev/shm:rw,exec,nosuid,nodev,size=${SHM_GB}g"
# Dynamic RE needs to attach to a live process: without SYS_PTRACE, gdb and
# strace are installed but inert ("Could not attach to process"), and the
# container's whole reason for existing is watching the emulator run.
# Docker's default seccomp profile also blocks calls the JIT and the guest
# memory mapper rely on.
--cap-add SYS_PTRACE
--security-opt seccomp=unconfined
--security-opt apparmor=unconfined
# ── the repository ──
# The agent's OWN clone, in its own volume -- not a bind mount of a human's
# working tree. That arrangement bit this project three times: an agent's
# `git config --local` captured a human's commits, a credential helper
# leaked a container-only path onto the host, and a `git add -A` swept an
# agent's in-flight files into someone else's commit. Separate checkouts
# make all three impossible rather than merely discouraged.
#
# The cost, accepted knowingly: Claude Code keys its per-project memory off
# the working directory, so moving from the host path to /work starts that
# memory empty. The corpus in docs/ is the memory that matters and it
# travels with the clone.
-v "sylpheed-decoder-repo:/work"
# Xenia Canary stays a separate repository -- it is a fork tracking upstream
# and carries our instrumentation. Read-write: building probes into it is
# real work, not a side effect.
-v "${SYLPH_CANARY:-$HOME/RE Project Sylpheed/xenia-canary}:/canary"
# The shared exchange: transient files with provenance, outside git history.
-v "sylpheed-exchange:/exchange"
-e "PROJECT_DIR=/work"
-e "SYLPH_EXCHANGE=/exchange"
-e "SYLPH_AGENT=decoder"
-e "SYLPH_REPO_URL=https://git.mc02.dev/fabi/Sylpheed.git"
-e "XENIA_SRC=/canary"
# ── claude ──
# The state dir is shared read-write: credentials live in
# .claude/.credentials.json, so token refresh needs to write, and this is
# also what carries the project memory across.
-v "${SYLPH_CLAUDE_HOME:-$HOME/.claude}:/sylph-home/re/.claude"
# ~/.claude.json sits BESIDE that directory and holds `hasCompletedOnboarding`.
# Mounted READ-ONLY at a staging path: the entrypoint copies it to
# ~/.claude.json and stamps onboarding as done. Sharing the file directly
# would (a) re-run the first-run theme wizard whenever the container's
# Claude Code version differs from the host's — a silent hang an unattended
# agent never gets past — and (b) let the container rewrite your host config.
-v "${SYLPH_CLAUDE_JSON:-$HOME/.claude.json}:/sylph-home/re/.claude.host.json:ro"
# persistent build caches, so a container restart is not a rebuild
-v sylph-agent-cargo:/sylph-home/re/.cargo
-v sylph-agent-target:/sylph-home/re/target-container
-v sylph-agent-canary-build:/sylph-home/re/canary-build
)
# ── Vulkan SDK ──
# xenia's shader step calls `spirv-opt --canonicalize-ids`, which Ubuntu's
# packaged SPIRV-Tools (v2025.1) does not have — the build then dies ~500
# objects in. The LunarG SDK has it. Mounting the host's copy at the same path
# is cheaper than baking a 200 MB SDK into the image AND guarantees the
# container produces byte-identical shaders to the host build.
SDK="${VULKAN_SDK:-}"
if [ -z "$SDK" ]; then
SDK=$(ls -d "$HOME"/vulkan-sdk/*/x86_64 2>/dev/null | sort -V | tail -1 || true)
fi
if [ -n "$SDK" ] && [ -x "$SDK/bin/spirv-opt" ]; then
_out+=(-v "$SDK:$SDK:ro" -e "VULKAN_SDK=$SDK")
else
echo "==> NOTE: no Vulkan SDK found on the host. Building Canary's shaders" >&2
echo " needs spirv-opt with --canonicalize-ids (LunarG SDK); Ubuntu's" >&2
echo " packaged SPIRV-Tools is too old. Running is unaffected." >&2
fi
# ── git push ──
# Read-only, and only ever used by `push-work`, which refuses anything but an
# auto/* branch and never force-pushes. Without this the agent's work only
# exists inside the container and dies with it.
GITCRED="${SYLPH_GIT_CREDENTIALS:-$HOME/.sylph-git-credentials}"
if [ -f "$GITCRED" ]; then
_out+=(-v "$GITCRED:/sylph-home/re/.git-credentials.host:ro")
else
echo "==> NOTE: no git credentials at $GITCRED — the agent cannot push," >&2
echo " so its work will be lost if the container is destroyed. Create it" >&2
echo " with a single line and chmod 600:" >&2
echo " https://<user>:<token>@git.mc02.dev" >&2
echo " or point SYLPH_GIT_CREDENTIALS elsewhere." >&2
fi
[ -n "${ANTHROPIC_API_KEY:-}" ] && _out+=(-e "ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY")
[ -n "${SYLPH_VULKAN:-}" ] && _out+=(-e "SYLPH_VULKAN=$SYLPH_VULKAN")
[ -n "${SYLPH_REMOTE:-}" ] && _out+=(-e "SYLPH_REMOTE=$SYLPH_REMOTE")
[ -n "${SYLPH_REMOTE_NAME:-}" ] && _out+=(-e "SYLPH_REMOTE_NAME=$SYLPH_REMOTE_NAME")
[ -n "${SYLPH_ISO:-}" ] && _out+=(-e "SYLPH_ISO=$SYLPH_ISO")
# ── GPU ──
# Three distinct cases, and conflating them is how you end up believing you
# have hardware Vulkan while actually running llvmpipe:
#
# NVIDIA needs the NVIDIA Container Toolkit (`--gpus all`). Passing
# /dev/dri alone does NOT work — Mesa cannot drive an NVIDIA card,
# and the proprietary userspace lives outside the image.
# Mesa (AMD/Intel) works with a plain /dev/dri passthrough plus the
# host's render/video GIDs.
# neither software Vulkan (lavapipe): correct, and slow.
if [ "${SYLPH_VULKAN:-auto}" = "sw" ]; then
_out+=(-e SYLPH_VULKAN=sw)
elif command -v nvidia-smi >/dev/null 2>&1 && nvidia-smi -L >/dev/null 2>&1; then
if docker info --format '{{json .Runtimes}}' 2>/dev/null | grep -q nvidia; then
_out+=(--gpus all)
else
echo "==> NOTE: NVIDIA GPU found but the NVIDIA Container Toolkit is not" >&2
echo " installed, so hardware Vulkan is unavailable and the container" >&2
echo " will use lavapipe (software — correct, slow). To enable it:" >&2
echo " sudo apt install nvidia-container-toolkit \\" >&2
echo " && sudo nvidia-ctk runtime configure --runtime=docker \\" >&2
echo " && sudo systemctl restart docker" >&2
_out+=(-e SYLPH_VULKAN=sw)
fi
elif [ -e /dev/dri/renderD128 ]; then
_out+=(--device /dev/dri)
for g in render video; do
gid=$(getent group "$g" | cut -d: -f3 || true)
[ -n "$gid" ] && _out+=(--group-add "$gid")
done
else
_out+=(-e SYLPH_VULKAN=sw)
fi
}
case "${1:-}" in
build)
shift
echo "==> building $IMAGE (uid $(id -u), gid $(id -g))"
exec docker build -t "$IMAGE" \
--build-arg "AGENT_UID=$(id -u)" --build-arg "AGENT_GID=$(id -g)" \
"$@" "$HERE"
;;
loose)
shift
# "On the loose": detached, self-paced, working the RE backlog until stopped.
#
# -d WITHOUT --rm so the transcript survives the container exiting; that is
# the only record of what an unattended run did. -t because /loop keeps the
# session alive and schedules its own wake-ups — a `-p`/print-mode run would
# answer once and exit, killing the loop on its first iteration.
TASK="${1:-}"
if [ -z "$TASK" ]; then
if [ -f "$HERE/../../docs/agents/decoder-loop.md" ]; then
TASK="$(cat "$HERE/../../docs/agents/decoder-loop.md")"
else
TASK="Work the RE backlog in Syplheed-Reborn/docs/re/BACKLOG.md."
fi
fi
# A FIXED interval by default, not self-pacing. Self-pacing requires the
# agent to call ScheduleWakeup itself at the end of every turn, and the one
# thing an agent deep in an experiment reliably forgets is the bookkeeping
# after it. With an interval the harness owns the cadence and a forgotten
# wakeup cannot end the run. Set SYLPH_LOOP_INTERVAL= (empty) to self-pace.
INTERVAL="${SYLPH_LOOP_INTERVAL-45m}"
declare -a ARGS; docker_args ARGS
ARGS+=(-e SYLPH_AUTONOMOUS=1 -w "$PROJECT")
echo "==> loose | cpus=$CPUS mem=${MEM_GB}g shm=${SHM_GB}g"
echo "==> project: $PROJECT (mounted at its own path, so memory carries over)"
echo "==> pacing: ${INTERVAL:-self-paced}"
docker rm -f "$NAME" >/dev/null 2>&1 || true
docker run -d -i -t "${ARGS[@]}" "$IMAGE" "/loop ${INTERVAL:+$INTERVAL }$TASK" >/dev/null
echo
echo " running detached as '$NAME'."
echo " ./sylph-agent remote link to chat with it from anywhere"
echo " ./sylph-agent logs -f follow it"
echo " ./sylph-agent attach chat with it locally (Ctrl-P Ctrl-Q to leave it running)"
echo " ./sylph-agent stop stop it"
echo
# Report what is actually true. This line used to claim unconditionally that
# the agent could not push, which was written before credentials were
# supported and then went stale — telling the operator their work was at risk
# when it was not, which is the exact failure the credential mount fixes.
if [ -f "${SYLPH_GIT_CREDENTIALS:-$HOME/.sylph-git-credentials}" ]; then
echo " It commits to auto/* branches and publishes them with push-work,"
echo " which refuses any other branch and never force-pushes. Review with:"
echo " git -C '$PROJECT/Syplheed-Reborn' fetch origin && git log --oneline origin/auto/..."
else
echo " It commits to auto/* branches and CANNOT PUSH — no git credentials"
echo " are mounted, so its work dies with the container. Review it with:"
echo " git -C '$PROJECT/Syplheed-Reborn' log --oneline auto/..."
fi
;;
logs) shift; exec docker logs "$@" "$NAME" ;;
remote)
# Fish the Remote Control link out of the session's own output. Claude Code
# prints it once, when the session registers with your account — which takes
# a minute or two after launch, so this waits rather than answering "not
# found" to a question that is really "not yet".
printf 'waiting for the session to register' >&2
for i in $(seq 1 90); do
url=$(docker logs "$NAME" 2>&1 \
| sed 's/\x1b\[[0-9;]*[a-zA-Z]//g; s/\r//g' \
| grep -oE 'https://claude\.ai/code/[A-Za-z0-9_-]+' | tail -1)
if [ -n "${url:-}" ]; then
printf '\n' >&2
echo "$url"
exit 0
fi
docker ps -q -f "name=$NAME" | grep -q . || {
printf '\n' >&2
echo "container is not running — start it with: ./sylph-agent loose" >&2
exit 1
}
printf '.' >&2
sleep 4
done
printf '\n' >&2
echo "no Remote Control URL after 6 minutes." >&2
echo " Launched with SYLPH_REMOTE=0? Or check: ./sylph-agent logs | tail" >&2
exit 1
;;
shell|agent|run)
mode=$1; shift
declare -a ARGS; docker_args ARGS
echo "==> $mode | cpus=$CPUS mem=${MEM_GB}g shm=${SHM_GB}g (host: ${HOST_CPUS} cpus, $((HOST_MEM_KB/1048576))g)"
echo "==> project: $PROJECT -> /work"
docker rm -f "$NAME" >/dev/null 2>&1 || true
# Allocate a TTY only when stdin actually is one: `docker run -it` fails
# outright ("cannot attach stdin to a TTY-enabled container") under a
# pipeline or a CI runner, which is exactly where `run` gets used.
TTY=(-i); [ -t 0 ] && TTY=(-it)
case "$mode" in
shell) exec docker run --rm "${TTY[@]}" "${ARGS[@]}" "$IMAGE" bash ;;
agent)
# The flag the user asked for. Refused under root, which is why the
# image runs as an unprivileged `agent` user.
ARGS+=(-e SYLPH_AUTONOMOUS=1)
exec docker run --rm "${TTY[@]}" "${ARGS[@]}" "$IMAGE" "$@"
;;
run) exec docker run --rm "${TTY[@]}" "${ARGS[@]}" "$IMAGE" "$@" ;;
esac
;;
stop) exec docker rm -f "$NAME" ;;
doctor)
declare -a ARGS; docker_args ARGS
exec docker run --rm "${ARGS[@]}" "$IMAGE" sylph-doctor
;;
""|-h|--help) usage 0 ;;
*) echo "unknown command: $1" >&2; usage 2 ;;
esac