Repository navigation
refactor(config): make on-disk opencode.json the single source of truth #354
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
9c3b957
fe46503
5889ec5
5fa6680
b6979dd
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| import { existsSync, mkdirSync, writeFileSync } from 'node:fs' | ||
| import { randomBytes } from 'node:crypto' | ||
| import os from 'node:os' | ||
| import path from 'node:path' | ||
| import { getOpenCodeConfigFilePath, getOpenCodeConfigHome } from '@opencode-manager/shared/config/env' | ||
| import type { Migration } from '../migration-runner' | ||
| import { logger } from '../../utils/logger' | ||
|
|
||
| function firstExistingConfigSourcePath(): string | null { | ||
| const candidates = [ | ||
| process.env.OPENCODE_IMPORT_CONFIG_PATH, | ||
| path.join(os.homedir(), '.config', 'opencode', 'opencode.json'), | ||
| ] | ||
| .filter((value): value is string => Boolean(value)) | ||
| .map((value) => path.resolve(value)) | ||
|
|
||
| return Array.from(new Set(candidates)).find((candidate) => existsSync(candidate)) ?? null | ||
| } | ||
|
|
||
| function writeArchivedConfig(archiveDir: string, configName: string, content: string): void { | ||
| const base = configName.replace(/[^A-Za-z0-9._-]/g, '_') | ||
| try { | ||
| writeFileSync(path.join(archiveDir, `${base}.json`), content, { flag: 'wx' }) | ||
| return | ||
| } catch (error) { | ||
| if ((error as NodeJS.ErrnoException).code !== 'EEXIST') { | ||
| throw error | ||
| } | ||
| } | ||
|
|
||
| const suffix = `${Date.now()}-${randomBytes(4).toString('hex')}` | ||
| writeFileSync(path.join(archiveDir, `${base}-${suffix}.json`), content, { flag: 'wx' }) | ||
| } | ||
|
|
||
| function archiveConfigs(rows: Array<{ config_name: string; config_content: string }>): void { | ||
| const archiveDir = path.join(getOpenCodeConfigHome(), 'opencode-configs-archive') | ||
| mkdirSync(archiveDir, { recursive: true }) | ||
| for (const row of rows) { | ||
| try { | ||
| writeArchivedConfig(archiveDir, row.config_name, row.config_content) | ||
| } catch (error) { | ||
| logger.warn('Failed to archive an opencode config before dropping the table', error) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| const migration: Migration = { | ||
| version: 19, | ||
| name: 'drop-opencode-configs', | ||
|
|
||
| up(db) { | ||
| const rows = db.prepare('SELECT config_name, config_content, is_default FROM opencode_configs').all() as Array<{ config_name: string; config_content: string; is_default: number | null }> | ||
|
|
||
| try { | ||
| archiveConfigs(rows) | ||
| } catch (error) { | ||
| logger.warn('Failed to archive opencode configs before dropping the table', error) | ||
| } | ||
|
|
||
| const defaultRow = rows.find(row => row.is_default) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win Select the eligible default configuration deterministically. The old schema permits one default for each Select the intended user, such as 🤖 Prompt for AI Agents |
||
| if (defaultRow) { | ||
| try { | ||
| const configFilePath = getOpenCodeConfigFilePath() | ||
| if (!existsSync(configFilePath) && !firstExistingConfigSourcePath()) { | ||
| mkdirSync(path.dirname(configFilePath), { recursive: true }) | ||
| writeFileSync(configFilePath, defaultRow.config_content) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win Write the restored configuration atomically. A crash or interrupted Use the shared atomic file writer or write a temporary file in the same directory and rename it. Based on learnings: shared JSON state files must use a temporary file and atomic rename. 🤖 Prompt for AI AgentsSource: Learnings |
||
| } | ||
| } catch (error) { | ||
| logger.warn('Failed to restore the default opencode config file', error) | ||
| } | ||
| } | ||
|
|
||
| db.run('DROP INDEX IF EXISTS idx_opencode_default') | ||
| db.run('DROP INDEX IF EXISTS idx_opencode_user_id') | ||
| db.run('DROP TABLE IF EXISTS opencode_configs') | ||
| db.run('ALTER TABLE repos DROP COLUMN opencode_config_name') | ||
| }, | ||
|
|
||
| down(db) { | ||
| db.run(` | ||
| CREATE TABLE IF NOT EXISTS opencode_configs ( | ||
| id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| user_id TEXT NOT NULL DEFAULT 'default', | ||
| config_name TEXT NOT NULL, | ||
| config_content TEXT NOT NULL, | ||
| is_default BOOLEAN DEFAULT FALSE, | ||
| created_at INTEGER NOT NULL, | ||
| updated_at INTEGER NOT NULL, | ||
| UNIQUE(user_id, config_name) | ||
| ) | ||
| `) | ||
| db.run('CREATE INDEX IF NOT EXISTS idx_opencode_user_id ON opencode_configs(user_id)') | ||
| db.run('CREATE INDEX IF NOT EXISTS idx_opencode_default ON opencode_configs(user_id, is_default)') | ||
| db.run('ALTER TABLE repos ADD COLUMN opencode_config_name TEXT') | ||
| }, | ||
| } | ||
|
|
||
| export default migration | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' | ||
| import path from 'node:path' | ||
| import { getOpenCodeModelStatePath } from '@opencode-manager/shared/config/env' | ||
| import type { Migration } from '../migration-runner' | ||
| import { logger } from '../../utils/logger' | ||
|
|
||
| interface ModelStateRow { | ||
| recent: string | ||
| favorite: string | ||
| variant: string | ||
| updated_at: number | ||
| } | ||
|
|
||
| function readDefaultRow(db: Parameters<Migration['up']>[0]): ModelStateRow | undefined { | ||
| try { | ||
| return db.prepare("SELECT recent, favorite, variant, updated_at FROM opencode_model_state WHERE user_id = 'default'").get() as ModelStateRow | undefined | ||
| } catch { | ||
| return undefined | ||
| } | ||
| } | ||
|
|
||
| function parseJson<T>(value: string, fallback: T): T { | ||
| try { | ||
| return JSON.parse(value) as T | ||
| } catch { | ||
| return fallback | ||
| } | ||
| } | ||
|
|
||
| function restoreModelStateFile(row: ModelStateRow): void { | ||
| const filePath = getOpenCodeModelStatePath() | ||
| const fileExists = existsSync(filePath) | ||
|
|
||
| if (fileExists && statSync(filePath).mtimeMs >= row.updated_at) { | ||
| return | ||
| } | ||
|
|
||
| const existing = fileExists | ||
| ? parseJson<Record<string, unknown>>(readFileSync(filePath, 'utf8'), {}) | ||
| : {} | ||
|
|
||
| mkdirSync(path.dirname(filePath), { recursive: true }) | ||
| writeFileSync(filePath, JSON.stringify({ | ||
| ...existing, | ||
| recent: parseJson<unknown[]>(row.recent, []), | ||
| favorite: parseJson<unknown[]>(row.favorite, []), | ||
| variant: parseJson<Record<string, unknown>>(row.variant, {}), | ||
| }, null, 2)) | ||
| } | ||
|
|
||
| const migration: Migration = { | ||
| version: 20, | ||
| name: 'drop-opencode-model-state', | ||
|
|
||
| up(db) { | ||
| const row = readDefaultRow(db) | ||
| if (row) { | ||
| try { | ||
| restoreModelStateFile(row) | ||
| } catch (error) { | ||
| logger.warn('Failed to restore the OpenCode model state file', error) | ||
| } | ||
| } | ||
|
|
||
| db.run('DROP INDEX IF EXISTS idx_opencode_model_state_user') | ||
| db.run('DROP TABLE IF EXISTS opencode_model_state') | ||
| }, | ||
|
|
||
| down(db) { | ||
| db.run(` | ||
| CREATE TABLE IF NOT EXISTS opencode_model_state ( | ||
| id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| user_id TEXT NOT NULL DEFAULT 'default', | ||
| recent TEXT NOT NULL DEFAULT '[]', | ||
| favorite TEXT NOT NULL DEFAULT '[]', | ||
| variant TEXT NOT NULL DEFAULT '{}', | ||
| updated_at INTEGER NOT NULL, | ||
| UNIQUE(user_id) | ||
| ) | ||
| `) | ||
| db.run('CREATE INDEX IF NOT EXISTS idx_opencode_model_state_user ON opencode_model_state(user_id)') | ||
| }, | ||
| } | ||
|
|
||
| export default migration |
This file was deleted.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🔴 Critical | 🏗️ Heavy lift
Abort the migration when configuration preservation fails.
These catch blocks suppress archive and restoration failures. The migration then drops
opencode_configs, which can permanently delete rows that were not archived or leave the installation without an active configuration.Throw the error so the migration transaction can stop before the destructive statements.
Also applies to: 45-47, 57-59
🤖 Prompt for AI Agents