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

+27 -43
View File
@@ -1,12 +1,13 @@
import os from 'os'
import path from 'path'
import { existsSync } from 'node:fs'
import { cp, mkdtemp, readdir, rename, rm } from 'fs/promises'
import { Database as SQLiteDatabase, type Database } from 'bun:sqlite'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
import { Database as SQLiteDatabase } from 'bun:sqlite'
import { getOpenCodeConfigFilePath, getWorkspacePath } from '@opencode-manager/shared/config/env'
import { parse as parseJsonc } from 'jsonc-parser'
import { SettingsService } from './settings'
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent } from './file-operations'
import { parseOpenCodeConfigContent, withOpenCodeConfigLock, writeOpenCodeConfigFile } from './opencode-config-file'
import { captureLastKnownGoodOpenCodeConfig } from './opencode-config-apply'
import { ensureDirectoryExists, fileExists, readFileContent } from './file-operations'
import type { SettingsService } from './settings'
const OPENCODE_STATE_DB_FILENAMES = new Set(['opencode.db', 'opencode.db-shm', 'opencode.db-wal'])
@@ -19,10 +20,11 @@ export interface OpenCodeImportStatus {
}
export interface SyncOpenCodeImportOptions {
db: Database
userId?: string
overwriteState?: boolean
protectExistingState?: boolean
importConfig?: boolean
status?: OpenCodeImportStatus
settingsService?: SettingsService
}
export interface SyncOpenCodeImportResult extends OpenCodeImportStatus {
@@ -53,14 +55,11 @@ export function getImportPathCandidates(envKey: string, fallbackPath: string): s
return Array.from(new Set(candidates))
}
export async function getFirstExistingPath(paths: string[]): Promise<string | null> {
for (const candidate of paths) {
if (await fileExists(candidate)) {
return candidate
}
}
return null
export function getFirstExistingConfigSourcePath(): string | null {
return getImportPathCandidates(
'OPENCODE_IMPORT_CONFIG_PATH',
path.join(os.homedir(), '.config', 'opencode', 'opencode.json')
).find(candidate => existsSync(candidate)) ?? null
}
async function getFirstExistingPathWithDatabase(paths: string[]): Promise<string | null> {
@@ -140,9 +139,7 @@ export async function getOpenCodeImportStatus(): Promise<OpenCodeImportStatus> {
const workspaceStatePath = path.join(getWorkspacePath(), '.opencode', 'state', 'opencode')
const workspaceStateExists = await fileExists(path.join(workspaceStatePath, 'opencode.db'))
const configSourcePath = await getFirstExistingPath(
getImportPathCandidates('OPENCODE_IMPORT_CONFIG_PATH', path.join(os.homedir(), '.config', 'opencode', 'opencode.json'))
)
const configSourcePath = getFirstExistingConfigSourcePath()
const stateSourcePath = await getFirstExistingPathWithDatabase(
getImportPathCandidates('OPENCODE_IMPORT_STATE_PATH', path.join(os.homedir(), '.local', 'share', 'opencode'))
)
@@ -156,38 +153,25 @@ export async function getOpenCodeImportStatus(): Promise<OpenCodeImportStatus> {
}
}
async function importOpenCodeConfigFromSource(db: Database, userId: string, sourcePath: string, workspaceConfigPath: string): Promise<boolean> {
async function importOpenCodeConfigFromSource(sourcePath: string, settingsService?: SettingsService): Promise<boolean> {
const rawContent = await readFileContent(sourcePath)
const parsed = parseJsonc(rawContent)
const validation = OpenCodeConfigSchema.safeParse(parsed)
const { isValid } = parseOpenCodeConfigContent(rawContent)
if (!validation.success) {
if (!isValid) {
throw new Error('Importable OpenCode config is invalid')
}
const settingsService = new SettingsService(db)
const existingDefault = settingsService.getOpenCodeConfigByName('default', userId)
if (existingDefault) {
settingsService.updateOpenCodeConfig('default', {
content: rawContent,
isDefault: true,
}, userId)
} else {
settingsService.createOpenCodeConfig({
name: 'default',
content: rawContent,
isDefault: true,
}, userId)
}
await writeFileContent(workspaceConfigPath, rawContent)
await withOpenCodeConfigLock(async () => {
if (settingsService) {
await captureLastKnownGoodOpenCodeConfig(settingsService)
}
await writeOpenCodeConfigFile(rawContent)
})
return true
}
export async function syncOpenCodeImport(options: SyncOpenCodeImportOptions): Promise<SyncOpenCodeImportResult> {
const initialStatus = await getOpenCodeImportStatus()
const userId = options.userId || 'default'
const initialStatus = options.status ?? await getOpenCodeImportStatus()
const overwriteState = options.overwriteState === true
let configImported = false
let stateImported = false
@@ -198,8 +182,8 @@ export async function syncOpenCodeImport(options: SyncOpenCodeImportOptions): Pr
)
}
if (initialStatus.configSourcePath) {
configImported = await importOpenCodeConfigFromSource(options.db, userId, initialStatus.configSourcePath, initialStatus.workspaceConfigPath)
if (options.importConfig !== false && initialStatus.configSourcePath) {
configImported = await importOpenCodeConfigFromSource(initialStatus.configSourcePath, options.settingsService)
}
if (initialStatus.stateSourcePath && (overwriteState || !initialStatus.workspaceStateExists)) {