refactor(config): make on-disk opencode.json the single source of truth (#354)

* refactor(config): make on-disk opencode.json the single source of truth

Make <workspace>/.config/opencode/opencode.json the only store for the active OpenCode configuration. One owner (opencode-config-file.ts) reads, validates, writes, archives, and seeds the file; one owner (opencode-config-apply.ts) decides how an edit is applied: restart pending, or a live patch with recovery. Settings routes, the internal assistant API, the health-watch supervisor, boot, and host import all go through them, so an edit that lands on the file without going through the database is visible immediately instead of at the next Manager boot.

Remove the named-config profiles. Migration 019 archives every opencode_configs row to .config/opencode-configs-archive/<name>.json, restores the default row to opencode.json when no file exists, then drops the table, its indexes, and repos.opencode_config_name. The /opencode-configs* and config/switch routes and the CreateConfigDialog/SwitchConfigDialog dialogs are gone, and the ocm tool gains GET/PUT /opencode-config backed by the same apply owner.

Harden the write path: serialize and atomically write config updates while preserving the file mode, keep withFileLock usable after a rejection, route reloadConfig's cleaned-config write through the file owner, stop boot from rewriting an existing valid config when importing state, prune the health-watch directory to its newest 20 entries, resolve archive paths with realpath, and share one frontend config query across dialogs.

* fix(mirror): canonicalize worktree paths before branch ownership check

* refactor(config): unify opencode config apply and rollback paths

- share one config route factory between public and internal mounts
- capture last-known-good before every config write and restore via one helper
- stop auto-restarting on save; flag restart-required fields and live-patch the rest
- add CONFIG_PATCH_TIMEOUT_MS for config patch requests
- extract canonicalPath helpers, health-watch artifact writer, and useProvidersWithModels hook

* refactor(model-state): use OpenCode state file as model state source of truth
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-19 00:28:34 -04:00
1 parent 7a3c5229df
commit 295d24ced7
116 files changed
+10291 -4208

No files matched your search

+1 -1
View File
@@ -330,7 +330,7 @@ services:
cap_add:
- NET_ADMIN
environment:
- SANDBOX_IMAGE=${SANDBOX_IMAGE:-docker.io/cstechdev/ocm-sandbox@sha256:30d4c0e7cfe087d23e7387e1d0633bbbe3bb64f222263a24f3d9ca7559bea8aa}
- SANDBOX_IMAGE=${SANDBOX_IMAGE:-docker.io/cstechdev/ocm-sandbox@sha256:7435dce147503b846bcd89ad5e9f7192f37b332c8e49087a7e619034352c47f4}
- SANDBOX_MEMORY=${SANDBOX_MEMORY:-4G}
- SANDBOX_CPUS=${SANDBOX_CPUS:-2}
- SANDBOX_EXEC_USER=${SANDBOX_EXEC_USER:-${PUID:-1000}}
+2 -1
View File
@@ -116,7 +116,7 @@ Sandboxed agent commands run inside a microVM managed by `msb` (see [Agent Sandb
|----------|-------------|---------|
| `MSB_PATH` | Path to the `msb` executable | `msb` |
| `MSB_LIBKRUNFW_PATH` | Path to the `libkrunfw` firmware library used by `msb` (set in the container image) | `/opt/microsandbox/lib/libkrunfw.so` |
| `SANDBOX_IMAGE` | OCI image the microVM boots from. Digest-pinned by default so a rebuilt guest image is actually adopted; see [Sandbox Guest Image](../features/sandboxing.md#sandbox-guest-image) for what the default ships and how to build your own | `docker.io/cstechdev/ocm-sandbox@sha256:30d4c0e7…` |
| `SANDBOX_IMAGE` | OCI image the microVM boots from. Digest-pinned by default so a rebuilt guest image is actually adopted; see [Sandbox Guest Image](../features/sandboxing.md#sandbox-guest-image) for what the default ships and how to build your own | `docker.io/cstechdev/ocm-sandbox@sha256:7435dce1…` |
| `SANDBOX_MEMORY` | MicroVM memory (e.g. `4G`) | `4G` |
| `SANDBOX_CPUS` | MicroVM CPU count | `2` |
| `SANDBOX_EXEC_USER` | Guest identity sandboxed commands run as: a numeric `uid`, a numeric `uid:gid`, or a guest username. A numeric uid must match the Manager's effective uid (`PUID`); the compose overlay defaults it to `${PUID:-1000}`. A guest username is resolved to the Manager's effective `uid:gid` so writes to the mounted project roots always succeed. When a configured numeric identity cannot write the workspace, enforcement is reported unavailable | `${PUID:-1000}` via the overlay, otherwise `node` |
@@ -131,6 +131,7 @@ Sandboxed agent commands run inside a microVM managed by `msb` (see [Agent Sandb
| `PROCESS_START_WAIT_MS` | Wait time for OpenCode process to start | `2000` |
| `PROCESS_VERIFY_WAIT_MS` | Wait time for process health verification | `1000` |
| `HEALTH_CHECK_TIMEOUT_MS` | OpenCode liveness probe timeout | `30000` |
| `CONFIG_PATCH_TIMEOUT_MS` | Timeout for an OpenCode config patch request | `15000` |
## File Limits
+3 -9
View File
@@ -16,17 +16,11 @@ A compact model switcher is embedded directly in the chat interface. Click the *
| **Variants** | Some models offer tier options (e.g., fast or pro). Variant items are highlighted and show a checkmark on the active selection. |
| **All Models…** | Opens the full model browser when you need a model not in recents or favorites. |
Model selections persist across page reloads.
Favorites, recents, and variant choices are stored in OpenCode's own state file (`.opencode/state/opencode/model.json` in the workspace), so they are shared with the OpenCode TUI and survive Manager restarts. The active model itself is not persisted: on page load it resolves the same way the OpenCode TUI does — the `model` set in `opencode.json`, otherwise your most recent valid model, otherwise the provider default. A model you pick during a session stays active until the page is reloaded.
### Per-Agent Model Selection
### Per-Agent and Per-Session Models
Each agent can use a different model independently:
1. Select an agent in the chat session header
2. Open the quick model switcher
3. Choose a model — it is now stored for that agent
When you switch agents, the model you last used with that agent is restored automatically. Your global model selection is unaffected.
Each agent can declare its own `model` in `opencode.json`, which becomes that agent's default. When you open an existing session, the model, agent, and variant used by its last message are restored from the session itself, so switching between sessions keeps each one's selection.
### Full Model Browser
+47 -2
View File
@@ -58,6 +58,8 @@ The `path` is relative to the internal API base (for example `/settings` or `/re
```
GET /settings
PATCH /settings
GET /opencode-config
PUT /opencode-config
POST /assistant/reload
GET /repos
GET /repos/*/git-info
@@ -200,6 +202,50 @@ Returns the updated settings object.
- `400`: Invalid request body or disallowed key
- `401`: Missing or invalid bearer token
### OpenCode Configuration
The OpenCode configuration file at `getOpenCodeConfigFilePath()` is the source of truth, and this endpoint is the only supported way to change it. The endpoint applies the same restart and live-patch rules as the Settings UI: changes to `agent`, `plugin`, `skills`, or `provider` mark an OpenCode server restart as required, and any other change is live-patched into the running OpenCode server.
**GET `/api/internal/opencode-config`**
Read the current configuration file state.
**Response (`OpenCodeConfigFile`):**
```ts
{
path: string // Absolute path of the configuration file
content: object // Parsed configuration
rawContent: string // Raw file content, including comments
isValid: boolean // Whether the file passes schema validation
validationIssues?: Array<{ path: string, message: string }>
updatedAt: number // Unix timestamp of the last write
}
```
**Status Codes:**
- `200`: Configuration file state returned
- `401`: Missing or invalid bearer token
- `404`: No config file found
- `500`: Server error
**PUT `/api/internal/opencode-config`**
Persist a complete configuration. Read the file first, change only the keys the user asked for, and send the complete object back.
**Request Body:**
```ts
{ content: object } // The complete configuration to persist
```
**Response:**
Returns the written `OpenCodeConfigFile`. Adds `restartRequired: true` when the change needs an OpenCode server restart, and `removedFields` when OpenCode dropped fields it does not accept.
**Status Codes:**
- `200`: Configuration written (live-patched or restart pending)
- `400`: Invalid request body, or configuration rejected with `validationIssues`
- `401`: Missing or invalid bearer token
- `500`: Server error
### Assistant
**POST `/api/internal/assistant/reload`**
@@ -251,7 +297,6 @@ Retrieve a list of all managed repositories, ordered by the user's repo preferen
clonedAt: number // Timestamp when repo was cloned
lastPulled?: number // Timestamp of last pull
lastAccessedAt?: number // Timestamp of last access
openCodeConfigName?: string // Associated OpenCode config name
isWorktree?: boolean // Whether repo is a worktree
isLocal?: boolean // Whether repo is local-only
}>
@@ -269,7 +314,7 @@ The assistant workspace includes four skills that document these capabilities:
1. **Schedule Management** (`.opencode/skills/schedule-management/SKILL.md`) — manage schedule jobs and runs through the `ocm` `request` action.
2. **Notifications** (`.opencode/skills/notifications/SKILL.md`) — send push notifications through the `ocm` `send_notification` action.
3. **Manager Settings** (`.opencode/skills/manager-settings/SKILL.md`) — read and patch user preferences and reload the assistant workspace through the `ocm` `request` action.
3. **Manager Settings** (`.opencode/skills/manager-settings/SKILL.md`) — read and patch user preferences, read and update the OpenCode configuration file, and reload the assistant workspace through the `ocm` `request` action.
4. **Repo Management** (`.opencode/skills/repo-management/SKILL.md`) — list managed repositories through the `ocm` `request` action.
These skills are automatically provisioned when assistant mode is initialized and contain detailed examples and usage patterns.
+3 -1
View File
@@ -21,9 +21,11 @@ Four skills are provisioned automatically when assistant mode is initialized:
|-------|----------------|
| `schedule-management` | Create, list, update, delete, and run scheduled jobs through the `ocm` `request` action |
| `notifications` | Send push notifications to registered user devices with the `ocm` `send_notification` action |
| `manager-settings` | Read and patch user preferences, and reload the assistant workspace, through the `ocm` `request` action |
| `manager-settings` | Read and patch user preferences, read and update the OpenCode configuration file, and reload the assistant workspace, through the `ocm` `request` action |
| `repo-management` | List all managed repositories through the `ocm` `request` action |
The assistant manages the Manager's global OpenCode configuration file through the `ocm` tool (`/opencode-config`), and the file on disk is the source of truth.
See [Assistant Internal API](assistant-internal-api.md) for the full API reference these skills expose.
## Assistant Persona
+18 -2
View File
@@ -40,6 +40,23 @@ Health monitoring is configured through environment variables:
| `OPENCODE_HEALTH_POLL_MS` | `30000` | Poll interval in milliseconds |
| `OPENCODE_HEALTH_FAILURE_THRESHOLD` | `2` | Failed checks before recovery starts |
## Configuration Recovery
The on-disk `opencode.json` is the source of truth. When the file exists at boot but fails validation, the Manager logs a warning and starts with the file unchanged — an invalid config file is never automatically replaced or rolled back during boot.
The health-watch ladder is the only automatic repair path. When the supervised OpenCode server fails repeated health checks, recovery runs these actions in order until the server is healthy:
1. **Restart** — restart the server process
2. **Debug capture** — capture a diagnostic snapshot, then restart
3. **Rollback to last known good** — archive the broken config and restore the last known good config
4. **Seed default config** — write the minimal seed config and restart
Because the ladder only runs after repeated failed health checks, a config file that fails validation but does not make the server unhealthy is left in place. Setting `OPENCODE_HEALTH_WATCH_ENABLED=false` disables the ladder entirely, leaving no automatic repair path.
The last known good config is captured from the current on-disk file before every write made through the Settings UI, the internal API, or a host config import, so any of those can be undone with `POST /api/settings/opencode-rollback` or by the ladder. Archived broken configs and debug snapshots are kept under `.opencode/state/health-watch/` in the workspace, pruned to the newest 20 files.
Earlier releases stored named configuration profiles in the Manager database. On first start after upgrading, each profile is archived to `.config/opencode-configs-archive/<name>.json` in the workspace, the default profile is restored to `opencode.json` if that file does not exist yet, and the database table is dropped.
## Restart with Session Resume
When you restart the OpenCode server (manually or through an upgrade), active sessions are handled gracefully:
@@ -68,9 +85,8 @@ If the upgrade fails but the server recovers to a usable state, a recovery notic
Besides the explicit **Restart** button, the server is automatically restarted when:
- **OpenCode configuration is saved** — Changes to models, agents, commands, or MCP servers that require a server restart
- **Assistant workspace is reloaded** — Via the `POST /assistant/reload` internal API endpoint
- **Config import completes** — Importing a standalone OpenCode config into the workspace
- **Version upgrade** — After installing a new OpenCode version
Configuration changes that only affect non-process settings (e.g., environment variable passthrough, AGENTS.md) use a non-disruptive config reload instead, which does not interrupt active sessions.
Saving the OpenCode configuration never restarts the server on its own. Changes to `agent`, `plugin`, `skills`, or `provider` are written to disk and flagged as **restart required**; the server keeps running on the previous configuration until you restart it. Every other change is live-patched into the running server without interrupting active sessions, and is only written to disk once the server has accepted it.