diff --git a/backend/src/services/sandbox/command.ts b/backend/src/services/sandbox/command.ts index 2f9c75d5..394f10ca 100644 --- a/backend/src/services/sandbox/command.ts +++ b/backend/src/services/sandbox/command.ts @@ -153,6 +153,8 @@ export function buildSandboxCreateArgs(): string[] { sandboxSecretMaskPath(), '-w', getReposPath(), + '--entrypoint', + '/usr/bin/env', ENV.SANDBOX.IMAGE, '--', 'sleep', @@ -312,6 +314,7 @@ function parseSandboxCreateArgs(args: string[]): { mountDirs: string[] tmpfs: string | null workdir: string + entrypoint: string[] image: string cmd: string[] } { @@ -323,6 +326,7 @@ function parseSandboxCreateArgs(args: string[]): { let user = '' let tmpfs: string | null = null let workdir = '' + let entrypoint: string[] = [] let image = '' let cmd: string[] = [] for (let i = 1; i < args.length; i++) { @@ -349,12 +353,13 @@ function parseSandboxCreateArgs(args: string[]): { case '--mount-dir': if (value !== undefined) mountDirs.push(value); i += 1; break case '--tmpfs': tmpfs = value ?? null; i += 1; break case '-w': workdir = value ?? ''; i += 1; break + case '--entrypoint': if (value !== undefined) entrypoint = [value]; i += 1; break case '-d': break default: if (image === '' && !token.startsWith('-')) image = token } } - return { name, labels, memory, cpus, user, mountDirs, tmpfs, workdir, image, cmd } + return { name, labels, memory, cpus, user, mountDirs, tmpfs, workdir, entrypoint, image, cmd } } export function buildCanonicalSandboxSpec(): Record { @@ -392,7 +397,7 @@ export function buildCanonicalSandboxSpec(): Record { workdir: args.workdir, shell: null, scripts: {}, - entrypoint: null, + entrypoint: args.entrypoint, cmd: args.cmd, hostname: null, user: args.user, diff --git a/backend/src/services/sandbox/runtime.ts b/backend/src/services/sandbox/runtime.ts index 1a1a9ae2..ce6f48f6 100644 --- a/backend/src/services/sandbox/runtime.ts +++ b/backend/src/services/sandbox/runtime.ts @@ -421,8 +421,8 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise { expect(compose).toMatch(/^volumes:\n(?:.*\n)*?\s+opencode-workspace:/m) }) + it('mounts a dedicated named volume at /home/node/.opencode/bin with a top-level declaration', () => { + const compose = read(composePath) + expect(compose).toContain('opencode-bin:/home/node/.opencode/bin') + expect(compose).toMatch(/^volumes:\n(?:.*\n)*?\s+opencode-bin:/m) + }) + + it('persists only the opencode bin directory, not the whole ~/.opencode home', () => { + const compose = read(composePath) + expect(compose).not.toMatch(/:\/home\/node\/\.opencode(?:\s|$)/) + }) + + it('lists the opencode-bin volume in the installation docs table', () => { + const docs = read(join(repoRoot, 'docs/getting-started/installation.md')) + expect(docs).toContain('| `opencode-bin` | `/home/node/.opencode/bin` |') + }) + it('keeps the docker docs compose snippet in sync with docker-compose.yml', () => { const compose = read(composePath) const docs = read(dockerDocsPath) @@ -188,6 +204,26 @@ describe('workspace ownership configuration', () => { }) }) +describe('docker lifecycle scripts', () => { + it('keeps docker:down non-destructive and docker:reset destructive', () => { + const pkg = read(join(repoRoot, 'package.json')) + expect(pkg).toContain('"docker:down": "docker-compose down"') + expect(pkg).toContain('"docker:reset": "docker-compose down -v"') + }) + + it('documents the preserved-volume shutdown and the destructive reset', () => { + const docs = read(dockerDocsPath) + expect(docs).toContain('named volumes are preserved') + expect(docs).toContain('docker-compose down -v') + }) + + it('documents a targeted opencode-bin volume reset that preserves the other volumes', () => { + const docs = read(join(repoRoot, 'docs/troubleshooting.md')) + expect(docs).toContain('docker volume rm _opencode-bin') + expect(docs).toContain('without touching the workspace or database volumes') + }) +}) + describe('sandbox compose overlay', () => { const overlayPath = join(repoRoot, 'docker-compose.sandbox.yml') const overlay = read(overlayPath) diff --git a/backend/test/scripts/docker-entrypoint.test.ts b/backend/test/scripts/docker-entrypoint.test.ts index 42452b89..6d43aaca 100644 --- a/backend/test/scripts/docker-entrypoint.test.ts +++ b/backend/test/scripts/docker-entrypoint.test.ts @@ -32,7 +32,9 @@ const extractMinOpenCodeVersion = () => { const installPrelude = () => [ extractMinOpenCodeVersion(), extractShellFunction('version_gte'), + extractShellFunction('read_opencode_version'), extractShellFunction('install_opencode'), + extractShellFunction('reconcile_persisted_opencode'), ].join('\n') beforeEach(() => { @@ -50,6 +52,12 @@ exit 2`) writeStub('groupadd', `echo "groupadd $*" >> "$OCM_STUB_LOG"`) writeStub('usermod', `echo "usermod $*" >> "$OCM_STUB_LOG"`) writeStub('runuser', `echo "runuser $*" >> "$OCM_STUB_LOG" +if [ "${'${OCM_STUB_RUNUSER_EXEC:-0}'}" = "1" ]; then + while [ "$#" -gt 0 ] && [ "$1" != "--" ]; do shift; done + [ "$#" -gt 0 ] && shift + OCM_EXECUTED_AS_NODE=1 "$@" + exit $? +fi exit ${'${OCM_STUB_RUNUSER_EXIT:-0}'}`) }) @@ -181,6 +189,7 @@ const runOpenCodeSection = (snippet: string, env: Record = {}) = ...process.env, PATH: `${stubDir}:${homeDir}/.opencode/bin:/usr/bin:/bin`, OCM_STUB_LOG: logPath, + OCM_STUB_RUNUSER_EXEC: '1', HOME: homeDir, OPENCODE_BUNDLED_VERSION: '1.18.16', ...env, @@ -277,3 +286,95 @@ describe('install_opencode', () => { expect(urls).not.toContain('/releases/latest/download/') }) }) + +const writeBinary = (dir: string, version: string) => { + const binPath = join(dir, 'opencode') + writeFileSync(binPath, `#!/bin/bash\necho "opencode version ${version}"\n`) + chmodSync(binPath, 0o755) + return binPath +} + +const homeBinPath = () => join(stubDir, 'home/.opencode/bin/opencode') +const bundledBinPath = () => join(stubDir, 'bundled/opencode') +const bundledFirstPath = () => `${join(stubDir, 'home/.opencode/bin')}:${join(stubDir, 'bundled')}:${stubDir}:/usr/bin:/bin` + +describe('persisted opencode reconciliation', () => { + it('probes the persisted binary version through runuser, never directly', () => { + mkdirSync(join(stubDir, 'home/.opencode/bin'), { recursive: true }) + writeFileSync(homeBinPath(), `#!/bin/bash +if [ -z "$OCM_EXECUTED_AS_NODE" ]; then + echo "persisted binary executed outside runuser" >&2 + exit 1 +fi +echo "opencode version 1.22.0"`) + chmodSync(homeBinPath(), 0o755) + const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`) + expect(res.status).toBe(0) + expect(stubCalls()).toContain(`runuser -u node -- ${homeBinPath()} --version`) + expect(res.stdout).toContain('retaining it') + expect(existsSync(homeBinPath())).toBe(true) + }) + + it('retains a persisted home binary equal to the bundled version', () => { + mkdirSync(join(stubDir, 'home/.opencode/bin'), { recursive: true }) + writeBinary(join(stubDir, 'home/.opencode/bin'), '1.18.16') + const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`) + expect(res.status).toBe(0) + expect(res.stdout).toContain('retaining it') + expect(existsSync(homeBinPath())).toBe(true) + expect(res.stdout).toContain('OpenCode is installed (version: 1.18.16)') + expect(curlLog()).toHaveLength(0) + }) + + it('retains a persisted home binary newer than the bundled version', () => { + mkdirSync(join(stubDir, 'home/.opencode/bin'), { recursive: true }) + writeBinary(join(stubDir, 'home/.opencode/bin'), '1.22.0') + const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`) + expect(res.status).toBe(0) + expect(res.stdout).toContain('retaining it') + expect(existsSync(homeBinPath())).toBe(true) + expect(res.stdout).toContain('OpenCode is installed (version: 1.22.0)') + expect(curlLog()).toHaveLength(0) + }) + + it('retains a persisted home binary older than the bundled version but above the minimum', () => { + mkdirSync(join(stubDir, 'home/.opencode/bin'), { recursive: true }) + writeBinary(join(stubDir, 'home/.opencode/bin'), '1.10.0') + const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`) + expect(res.status).toBe(0) + expect(res.stdout).toContain('retaining it') + expect(existsSync(homeBinPath())).toBe(true) + expect(res.stdout).toContain('OpenCode is installed (version: 1.10.0)') + expect(curlLog()).toHaveLength(0) + }) + + it('replaces a persisted home binary below the minimum version with the bundled version', () => { + stubInstallTools() + mkdirSync(join(stubDir, 'home/.opencode/bin'), { recursive: true }) + writeBinary(join(stubDir, 'home/.opencode/bin'), '1.0.0') + const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`) + expect(res.status).toBe(0) + expect(res.stdout).toContain('retaining it') + expect(res.stdout).toContain('below minimum required version') + expect(res.stdout).toContain('Reinstalling bundled OpenCode version 1.18.16...') + const urls = curlLog().join(' ') + expect(urls).toMatch(/\/releases\/download\/v1\.18\.16\//) + expect(urls).not.toContain('/releases/latest/download/') + }) + + it('removes a malformed persisted home binary and selects the bundled binary without downloading', () => { + mkdirSync(join(stubDir, 'home/.opencode/bin'), { recursive: true }) + writeBinary(join(stubDir, 'home/.opencode/bin'), 'garbage') + mkdirSync(join(stubDir, 'bundled'), { recursive: true }) + writeBinary(join(stubDir, 'bundled'), '1.18.16') + const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`, { + PATH: bundledFirstPath(), + }) + expect(res.status).toBe(0) + expect(res.stdout).toContain('malformed or unversioned') + expect(existsSync(homeBinPath())).toBe(false) + expect(existsSync(bundledBinPath())).toBe(true) + expect(res.stdout).toContain('OpenCode is installed (version: 1.18.16)') + expect(curlLog()).toHaveLength(0) + }) +}) diff --git a/backend/test/services/sandbox/command.test.ts b/backend/test/services/sandbox/command.test.ts index 7c2956f7..4b27ed52 100644 --- a/backend/test/services/sandbox/command.test.ts +++ b/backend/test/services/sandbox/command.test.ts @@ -103,6 +103,15 @@ describe('sandbox command builders', () => { expect(sandboxSecretMaskPath()).toBe(getAssistantOpenCodeDir()) }) + it('pins --entrypoint to /usr/bin/env before the image so msb never inherits the OCI entrypoint', () => { + const args = buildSandboxCreateArgs() + + const entrypointIndex = args.indexOf('--entrypoint') + expect(entrypointIndex).toBeGreaterThan(-1) + expect(args[entrypointIndex + 1]).toBe('/usr/bin/env') + expect(args.indexOf(ENV.SANDBOX.IMAGE)).toBeGreaterThan(entrypointIndex + 1) + }) + it('never mounts the SSH/config/state workspace directories', () => { const joined = buildSandboxCreateArgs().join(' ') const workspacePath = path.dirname(getReposPath()) @@ -133,7 +142,7 @@ describe('sandbox command builders', () => { expect(runtime.workdir).toBe(getReposPath()) expect(runtime.user).toBe(resolveSandboxExecUser()) expect(runtime.cmd).toEqual(['sleep', 'infinity']) - expect(runtime.entrypoint).toBeNull() + expect(runtime.entrypoint).toEqual(['/usr/bin/env']) expect(spec.patches).toEqual([]) expect(network.enabled).toBe(true) expect(network.ports).toEqual([]) diff --git a/backend/test/services/sandbox/runtime.test.ts b/backend/test/services/sandbox/runtime.test.ts index a31e92b6..2557c112 100644 --- a/backend/test/services/sandbox/runtime.test.ts +++ b/backend/test/services/sandbox/runtime.test.ts @@ -125,7 +125,7 @@ describe('SandboxRuntimeService', () => { workdir: reposRoot, shell: null, scripts: {}, - entrypoint: null, + entrypoint: ['/usr/bin/env'], cmd: ['sleep', 'infinity'], hostname: null, user: resolveSandboxExecUser(), @@ -934,6 +934,35 @@ describe('SandboxRuntimeService', () => { expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(1) }) + it('reuses a running sandbox carrying the explicit /usr/bin/env runtime entrypoint', async () => { + enableEnforcement() + const runtime = realInspectConfig().runtime as Record + mockExecuteCommand.mockImplementation(async (args: string[]) => { + if (args.includes('ls')) { + return { + exitCode: 0, + stdout: JSON.stringify([{ name: WORKSPACE_SANDBOX_NAME, status: 'running' }]), + stderr: '', + } + } + if (args.includes('inspect')) { + return { + exitCode: 0, + stdout: runningInspectOutput(realInspectConfig({ runtime: { ...runtime, entrypoint: ['/usr/bin/env'] } })), + stderr: '', + } + } + return { exitCode: 0, stdout: '', stderr: '' } + }) + + const plan = await service.planCommand(repoADir, 'echo hi') + + expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') }) + expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(0) + expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0) + expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(1) + }) + it('reuses a running sandbox carrying the microsandbox runtime tmpfs at /tmp sized from the canonical memory', async () => { enableEnforcement() mockExecuteCommand.mockImplementation(async (args: string[]) => { @@ -1686,6 +1715,35 @@ describe('SandboxRuntimeService', () => { expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('runtime.cmd')) }) + it('removes and recreates a running sandbox inheriting the image OCI entrypoint instead of /usr/bin/env', async () => { + enableEnforcement() + const runtime = realInspectConfig().runtime as Record + mockExecuteCommand.mockImplementation(async (args: string[]) => { + if (args.includes('ls')) { + return { + exitCode: 0, + stdout: JSON.stringify([{ name: WORKSPACE_SANDBOX_NAME, status: 'running' }]), + stderr: '', + } + } + if (args.includes('inspect')) { + return attestedAfterRecreate({ + exitCode: 0, + stdout: runningInspectOutput(realInspectConfig({ runtime: { ...runtime, entrypoint: ['docker-entrypoint.sh'] } })), + stderr: '', + }) + } + return { exitCode: 0, stdout: '', stderr: '' } + }) + + const plan = await service.planCommand(repoADir, 'echo hi') + + expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') }) + expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1) + expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1) + expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('runtime.entrypoint')) + }) + it('removes and recreates a running sandbox carrying image patches', async () => { enableEnforcement() mockExecuteCommand.mockImplementation(async (args: string[]) => { @@ -2306,6 +2364,35 @@ describe('SandboxRuntimeService', () => { expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(2) }) + it('trusts a freshly created sandbox whose runtime entrypoint is the explicit /usr/bin/env value', async () => { + enableEnforcement() + const runtime = realInspectConfig().runtime as Record + let inspectCalls = 0 + mockExecuteCommand.mockImplementation(async (args: string[]) => { + if (args.includes('ls')) { + return { exitCode: 0, stdout: '[]', stderr: '' } + } + if (args.includes('inspect')) { + inspectCalls += 1 + if (inspectCalls === 1) { + return { exitCode: 1, stdout: '', stderr: 'sandbox not found' } + } + return { + exitCode: 0, + stdout: runningInspectOutput(realInspectConfig({ runtime: { ...runtime, entrypoint: ['/usr/bin/env'] } })), + stderr: '', + } + } + return { exitCode: 0, stdout: '', stderr: '' } + }) + + const plan = await service.planCommand(repoADir, 'echo hi') + + expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') }) + expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1) + expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(2) + }) + function assertRecreateForInspectMutation( mutatedConfig: Record, expectedReasonPart: string, diff --git a/docker-compose.yml b/docker-compose.yml index 9abe6a52..2935e843 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -49,6 +49,7 @@ services: volumes: - ${OCM_WORKSPACE_HOST_PATH:-opencode-workspace}:/workspace - opencode-data:/app/data + - opencode-bin:/home/node/.opencode/bin restart: unless-stopped healthcheck: test: ["CMD", "curl", "-f", "http://localhost:5003/api/health"] @@ -62,3 +63,5 @@ volumes: driver: local opencode-data: driver: local + opencode-bin: + driver: local diff --git a/docs/configuration/docker.md b/docs/configuration/docker.md index af6500f9..df007645 100644 --- a/docs/configuration/docker.md +++ b/docs/configuration/docker.md @@ -81,6 +81,7 @@ services: volumes: - ${OCM_WORKSPACE_HOST_PATH:-opencode-workspace}:/workspace - opencode-data:/app/data + - opencode-bin:/home/node/.opencode/bin restart: unless-stopped healthcheck: test: ["CMD", "curl", "-f", "http://localhost:5003/api/health"] @@ -94,6 +95,8 @@ volumes: driver: local opencode-data: driver: local + opencode-bin: + driver: local ``` ## Environment Variables @@ -127,8 +130,10 @@ VAPID_SUBJECT=mailto:you@example.com The container entrypoint (`scripts/docker-entrypoint.sh`) automatically: 1. **Verifies Bun** is installed (installed at build time, fallback install if missing) -2. **Verifies OpenCode** is installed (installed at build time, fallback install if missing) -3. **Upgrades OpenCode** if below minimum version (1.0.137) +2. **Reconciles the persisted OpenCode home binary** (`/home/node/.opencode/bin/opencode`): + - any valid persisted binary is retained, including a user-selected version older than the image-bundled `OPENCODE_BUNDLED_VERSION`; + - a persisted binary that is malformed or unversioned is removed (only that binary), so `PATH` falls back to the image-bundled `/usr/local/bin/opencode` without a download +3. **Installs OpenCode** only when no usable binary is present: if opencode is missing entirely, or if the surviving binary is still below the minimum version (1.0.137), the pinned bundled version is downloaded into the persisted `bin` volume 4. **Validates AUTH_SECRET** is set (required for startup) 5. **Aligns the `node` account** to `PUID`/`PGID` (default `1000`) before chowning the workspace, the `/app/data` directory, and the `node` home directory. If `PUID`/`PGID` are already used by another account in the image, startup aborts with an explicit error. Group alignment runs first, so a free `PGID` combined with an occupied `PUID` mutates `/etc/group` before the UID collision is detected and aborts startup; realign to the original ids or pick a free pair before retrying. @@ -261,6 +266,23 @@ Contains: Uses a named volume for data persistence. +### OpenCode Binary + +```yaml +volumes: + - opencode-bin:/home/node/.opencode/bin +``` + +Persists the OpenCode binary that OpenCode's own `upgrade --method curl` command (run from the UI's OpenCode settings) installs into `~/.opencode/bin`, so an upgrade survives container recreations. The volume is limited to the binary and leaves existing workspace and XDG persistence behavior for config, auth, and chat state unchanged. + +On startup the entrypoint reconciles the persisted binary: + +- any valid persisted binary is retained, including a user-selected version older than the image-bundled `OPENCODE_BUNDLED_VERSION`; +- a malformed or unversioned persisted binary is removed so `PATH` falls back to the image-bundled `/usr/local/bin/opencode`, avoiding a download; +- a persisted binary still below the minimum version (1.0.137) is replaced by the pinned bundled version, which is downloaded into this volume. + +A fresh volume starts empty and the image-bundled binary is used until an upgrade installs into the volume. + ### Import Existing OpenCode Chats From Your Host If you already use standalone OpenCode on your machine and want Dockerized OpenCode Manager to show those chats on first setup, bind your host OpenCode config/state into the container and bind your repo root to the same absolute path that standalone OpenCode used. @@ -405,9 +427,12 @@ services: # Start docker-compose up -d -# Stop +# Stop (containers removed; named volumes are preserved) docker-compose down +# Stop and remove containers and all named volumes (workspace, database, OpenCode binary) +docker-compose down -v + # Restart docker-compose restart @@ -418,6 +443,8 @@ docker-compose logs -f docker-compose logs --tail 100 ``` +The package scripts mirror these: `pnpm docker:down` stops and removes containers while preserving all named volumes, and `pnpm docker:reset` is the destructive variant that also deletes the workspace, database, and OpenCode binary volumes. + ### Maintenance ```bash diff --git a/docs/features/sandboxing.md b/docs/features/sandboxing.md index 7be5b330..f7262e24 100644 --- a/docs/features/sandboxing.md +++ b/docs/features/sandboxing.md @@ -61,6 +61,8 @@ All projects share one microVM named `ocm-workspace`: - Each command supplies its own working directory through `msb exec -w`. - A session outside the mounted roots is refused rather than executed on the host. - The Manager verifies the microVM image, resources, user, network policy, mounts (including the `/tmp` tmpfs size and mount options), labels, and secret mask before reuse. +- MSB pulls the configured `SANDBOX_IMAGE` (default `node:24`) automatically; no custom image build is needed. +- The Manager pins a neutral `/usr/bin/env` entrypoint, so the image's own OCI entrypoint is never inherited. - A stale or unverifiable microVM is removed and recreated. - Manager shutdown and an enforced-to-disabled restart stop the managed microVM. diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index 16e04cef..44891b1b 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -23,7 +23,7 @@ The container automatically: - Installs OpenCode if not present - Builds and serves the frontend -- Creates persistent volumes for workspace and database +- Creates persistent volumes for the workspace, database, and OpenCode binary - Configures health checks and auto-restart ### Docker Commands @@ -32,9 +32,12 @@ The container automatically: # Start the container docker-compose up -d -# Stop and remove container +# Stop and remove containers (named volumes are preserved) docker-compose down +# Stop and remove containers and all named volumes (workspace, database, OpenCode binary) +docker-compose down -v + # Rebuild the image docker-compose build @@ -54,6 +57,7 @@ docker exec -it opencode-manager sh |--------|---------------|---------| | `opencode-workspace` | `/workspace` | Repository storage | | `opencode-data` | `/app/data` | Database and config | +| `opencode-bin` | `/home/node/.opencode/bin` | OpenCode binary, persisted across container recreations | ## Local Development diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index a9886c8f..b3097217 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -27,6 +27,29 @@ lsof -i :5003 docker-compose build --no-cache ``` +### Reset a Broken OpenCode Binary + +**Symptoms:** Container won't start after an OpenCode upgrade, or the OpenCode settings show a malformed binary + +The OpenCode binary lives in its own named volume (`opencode-bin`). To remove only that volume and let the entrypoint reinstall the pinned bundled version on next start, without touching the workspace or database volumes: + +```bash +docker-compose down +# is the Compose project name, usually the directory containing docker-compose.yml +docker volume rm _opencode-bin +docker-compose up -d +``` + +Or via the package scripts: + +```bash +pnpm docker:down +docker volume rm _opencode-bin +pnpm docker:up +``` + +Do not use `docker-compose down -v` (or `pnpm docker:reset`) here: that also deletes the workspace and database volumes. + ### Port Already in Use **Symptoms:** Error about port 5003 being in use diff --git a/package.json b/package.json index 62ae0a24..2d1d2992 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,8 @@ "generate:openapi": "bun scripts/generate-openapi.ts", "docker:build": "docker-compose build", "docker:up": "docker-compose up -d", - "docker:down": "docker-compose down -v", + "docker:down": "docker-compose down", + "docker:reset": "docker-compose down -v", "docker:logs": "docker-compose logs -f", "docker:restart": "docker-compose restart" }, diff --git a/scripts/docker-entrypoint.sh b/scripts/docker-entrypoint.sh index 112f6be4..b39dbbf5 100644 --- a/scripts/docker-entrypoint.sh +++ b/scripts/docker-entrypoint.sh @@ -48,6 +48,15 @@ version_gte() { printf '%s\n%s\n' "$2" "$1" | sort -V -C } +read_opencode_version() { + local binary + binary="$(command -v "${1:-opencode}" 2>/dev/null || true)" + if [ -z "$binary" ] || [ ! -x "$binary" ]; then + return 0 + fi + runuser -u node -- "$binary" --version 2>&1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || true +} + install_opencode() { local opencode_version="${OPENCODE_BUNDLED_VERSION:-}" if [ -z "$opencode_version" ]; then @@ -74,6 +83,19 @@ install_opencode() { rm -rf "$staging" } +reconcile_persisted_opencode() { + local persisted_path="$HOME/.opencode/bin/opencode" + [ -e "$persisted_path" ] || return 0 + local persisted_version + persisted_version="$(read_opencode_version "$persisted_path")" + if [ -z "$persisted_version" ]; then + echo "Persisted OpenCode at $persisted_path is malformed or unversioned; removing it to fall back to the bundled binary" + rm -f "$persisted_path" + return 0 + fi + echo "Persisted OpenCode $persisted_version is usable; retaining it" +} + echo "Checking Bun installation..." if ! command -v bun >/dev/null 2>&1; then @@ -93,6 +115,8 @@ fi echo "Checking OpenCode installation..." +reconcile_persisted_opencode + if ! command -v opencode >/dev/null 2>&1; then echo "OpenCode not found. Installing..." install_opencode @@ -104,7 +128,8 @@ if ! command -v opencode >/dev/null 2>&1; then echo "OpenCode installed successfully" fi -OPENCODE_VERSION=$(opencode --version 2>&1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || echo "unknown") +OPENCODE_VERSION="$(read_opencode_version)" +[ -n "$OPENCODE_VERSION" ] || OPENCODE_VERSION="unknown" echo "OpenCode is installed (version: $OPENCODE_VERSION)" if [ "$OPENCODE_VERSION" != "unknown" ]; then @@ -115,7 +140,8 @@ if [ "$OPENCODE_VERSION" != "unknown" ]; then echo "Reinstalling bundled OpenCode version ${OPENCODE_BUNDLED_VERSION}..." install_opencode - OPENCODE_VERSION=$(opencode --version 2>&1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || echo "unknown") + OPENCODE_VERSION="$(read_opencode_version)" + [ -n "$OPENCODE_VERSION" ] || OPENCODE_VERSION="unknown" echo "OpenCode reinstalled as version: $OPENCODE_VERSION" fi fi