feat: add explicit OpenCode host import and repo relink (#176)

* feat: add explicit OpenCode host import and repo relink

* fix: tighten OpenCode import and relink reporting

* Add OpenCode config schema and JSONC parser imports

* Fix repo relinking and state availability detection for config-only imports

* Remove unused exports and internalize row-shape types

* Remove unused reserveScheduleJobNextRun function

---------

Co-authored-by: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
This commit is contained in:
itz4blitzandChris Scott authored and GitHub committed 2026-04-12 10:50:37 -04:00
1 parent 173dbf578e
commit 6b1a1e2005
15 files changed
+1031 -245

No files matched your search

-58
View File
@@ -40,62 +40,4 @@ export function createAuthMiddleware(auth: AuthInstance) {
})
}
export function createOptionalAuthMiddleware(auth: AuthInstance) {
return createMiddleware<{
Variables: {
session: Session['session'] | null
user: Session['user'] | null
}
}>(async (c, next) => {
try {
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (session) {
c.set('session', session.session as Session['session'])
c.set('user', session.user as Session['user'])
} else {
c.set('session', null)
c.set('user', null)
}
} catch {
c.set('session', null)
c.set('user', null)
}
await next()
})
}
export function createAdminMiddleware(auth: AuthInstance) {
return createMiddleware<{
Variables: {
session: Session['session']
user: Session['user']
}
}>(async (c, next) => {
let session
try {
session = await auth.api.getSession({
headers: c.req.raw.headers,
})
} catch (error) {
logger.error('Session lookup failed', { error })
return c.json({ error: 'Internal Server Error' }, 500)
}
if (!session) {
return c.json({ error: 'Unauthorized' }, 401)
}
const user = session.user as Session['user']
if (user.role !== 'admin') {
return c.json({ error: 'Forbidden: Admin access required' }, 403)
}
c.set('session', session.session as Session['session'])
c.set('user', user)
await next()
})
}
-49
View File
@@ -34,10 +34,6 @@ function markApplied(db: Database, migration: Migration): void {
.run(migration.version, migration.name, Date.now())
}
function markReverted(db: Database, version: number): void {
db.prepare('DELETE FROM schema_migrations WHERE version = ?').run(version)
}
export function migrate(db: Database, migrations: Migration[]): void {
ensureMigrationsTable(db)
@@ -70,49 +66,4 @@ export function migrate(db: Database, migrations: Migration[]): void {
logger.info('All migrations applied successfully')
}
export function rollback(db: Database, migrations: Migration[], targetVersion?: number): void {
ensureMigrationsTable(db)
const applied = getAppliedVersions(db)
const sorted = [...migrations]
.filter(m => applied.has(m.version))
.sort((a, b) => b.version - a.version)
if (sorted.length === 0) {
logger.info('No migrations to rollback')
return
}
const latest = sorted[0]
if (!latest) {
logger.info('No migrations to rollback')
return
}
const target = targetVersion ?? latest.version - 1
const toRevert = sorted.filter(m => m.version > target)
if (toRevert.length === 0) {
logger.info('No migrations to rollback')
return
}
logger.info(`Rolling back ${toRevert.length} migration(s) to version ${target}`)
for (const migration of toRevert) {
logger.info(`Reverting migration ${migration.version}: ${migration.name}`)
db.run('BEGIN TRANSACTION')
try {
migration.down(db)
markReverted(db, migration.version)
db.run('COMMIT')
logger.info(`Migration ${migration.version} reverted successfully`)
} catch (error) {
db.run('ROLLBACK')
logger.error(`Rollback of migration ${migration.version} failed:`, error)
throw error
}
}
logger.info('Rollback completed successfully')
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { getReposPath } from '@opencode-manager/shared/config/env'
import { getErrorMessage } from '../utils/error-utils'
import path from 'path'
export interface RepoRow {
interface RepoRow {
id: number
repo_url?: string
local_path: string
-5
View File
@@ -204,11 +204,6 @@ export function deleteScheduleJob(db: Database, repoId: number, jobId: number):
return result.changes > 0
}
export function reserveScheduleJobNextRun(db: Database, repoId: number, jobId: number, nextRunAt: number): void {
const stmt = db.prepare('UPDATE schedule_jobs SET next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
stmt.run(nextRunAt, Date.now(), repoId, jobId)
}
export function updateScheduleJobRunState(db: Database, repoId: number, jobId: number, values: { lastRunAt: number; nextRunAt?: number | null }): void {
const stmt = db.prepare('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
stmt.run(values.lastRunAt, values.nextRunAt ?? null, Date.now(), repoId, jobId)
+16 -115
View File
@@ -2,10 +2,7 @@ import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { serveStatic } from '@hono/node-server/serve-static'
import os from 'os'
import path from 'path'
import { cp, readdir, readFile, rm } from 'fs/promises'
import { Database as SQLiteDatabase } from 'bun:sqlite'
import { readFile } from 'fs/promises'
import { initializeDatabase } from './db/schema'
import { createRepoRoutes } from './routes/repos'
import { createIPCServer, type IPCServer } from './ipc/ipcServer'
@@ -47,6 +44,9 @@ import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './ser
import { NotificationService } from './services/notification'
import { ScheduleRunner, ScheduleService } from './services/schedules'
import { migrateGlobalSkills } from './services/skills'
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
import { parse as parseJsonc } from 'jsonc-parser'
import { logger } from './utils/logger'
import {
@@ -58,8 +58,7 @@ import {
getDatabasePath,
ENV
} from '@opencode-manager/shared/config/env'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
import { parse as parseJsonc } from 'jsonc-parser'
const { PORT, HOST } = ENV.SERVER
const DB_PATH = getDatabasePath()
@@ -86,72 +85,6 @@ import { DEFAULT_AGENTS_MD } from './constants'
let ipcServer: IPCServer | undefined
const gitAuthService = new GitAuthService()
const OPENCODE_STATE_DB_FILENAMES = new Set(['opencode.db', 'opencode.db-shm', 'opencode.db-wal'])
function getImportPathCandidates(envKey: string, fallbackPath: string): string[] {
const candidates = [process.env[envKey], fallbackPath]
.filter((value): value is string => Boolean(value))
.map((value) => path.resolve(value))
return Array.from(new Set(candidates))
}
async function getFirstExistingPath(paths: string[]): Promise<string | undefined> {
for (const candidate of paths) {
if (await fileExists(candidate)) {
return candidate
}
}
return undefined
}
function escapeSqliteValue(value: string): string {
return value.replace(/'/g, "''")
}
async function copyOpenCodeStateFiles(sourcePath: string, targetPath: string): Promise<void> {
const entries = await readdir(sourcePath, { withFileTypes: true })
for (const entry of entries) {
if (OPENCODE_STATE_DB_FILENAMES.has(entry.name)) {
continue
}
await cp(path.join(sourcePath, entry.name), path.join(targetPath, entry.name), {
recursive: true,
force: false,
errorOnExist: false,
})
}
}
async function snapshotOpenCodeDatabase(sourcePath: string, targetPath: string): Promise<void> {
await rm(targetPath, { force: true })
const database = new SQLiteDatabase(sourcePath)
try {
database.exec(`VACUUM INTO '${escapeSqliteValue(targetPath)}'`)
} finally {
database.close()
}
}
async function importOpenCodeStateDirectory(sourcePath: string, targetPath: string): Promise<void> {
await ensureDirectoryExists(targetPath)
await copyOpenCodeStateFiles(sourcePath, targetPath)
const sourceDbPath = path.join(sourcePath, 'opencode.db')
if (!await fileExists(sourceDbPath)) {
return
}
await rm(path.join(targetPath, 'opencode.db-shm'), { force: true })
await rm(path.join(targetPath, 'opencode.db-wal'), { force: true })
await snapshotOpenCodeDatabase(sourceDbPath, path.join(targetPath, 'opencode.db'))
}
async function ensureDefaultConfigExists(): Promise<void> {
const settingsService = new SettingsService(db)
const workspaceConfigPath = getOpenCodeConfigFilePath()
@@ -188,36 +121,13 @@ async function ensureDefaultConfigExists(): Promise<void> {
}
}
const importConfigPath = await getFirstExistingPath(
getImportPathCandidates(
'OPENCODE_IMPORT_CONFIG_PATH',
path.join(os.homedir(), '.config/opencode/opencode.json')
)
)
const { configSourcePath: importConfigPath } = await getOpenCodeImportStatus()
if (importConfigPath) {
logger.info(`Found importable OpenCode config at ${importConfigPath}, importing...`)
try {
const rawContent = await readFileContent(importConfigPath)
const parsed = parseJsonc(rawContent)
const validation = OpenCodeConfigSchema.safeParse(parsed)
if (validation.success) {
const existingDefault = settingsService.getOpenCodeConfigByName('default')
if (existingDefault) {
settingsService.updateOpenCodeConfig('default', {
content: rawContent,
isDefault: true,
})
} else {
settingsService.createOpenCodeConfig({
name: 'default',
content: rawContent,
isDefault: true,
})
}
await writeFileContent(workspaceConfigPath, rawContent)
const result = await syncOpenCodeImport({ db, overwriteState: false })
if (result.configImported) {
logger.info(`Imported OpenCode config from ${importConfigPath} to workspace`)
return
}
@@ -249,28 +159,19 @@ async function ensureDefaultConfigExists(): Promise<void> {
async function ensureHomeStateImported(): Promise<void> {
try {
const workspaceStateRoot = path.join(getWorkspacePath(), '.opencode', 'state')
const workspaceStatePath = path.join(workspaceStateRoot, 'opencode')
const workspaceStateDbPath = path.join(workspaceStatePath, 'opencode.db')
if (await fileExists(workspaceStateDbPath)) {
const status = await getOpenCodeImportStatus()
if (status.workspaceStateExists) {
return
}
const importStatePath = await getFirstExistingPath(
getImportPathCandidates(
'OPENCODE_IMPORT_STATE_PATH',
path.join(os.homedir(), '.local', 'share', 'opencode')
)
)
if (!importStatePath) {
if (!status.stateSourcePath) {
return
}
await ensureDirectoryExists(workspaceStateRoot)
await importOpenCodeStateDirectory(importStatePath, workspaceStatePath)
logger.info(`Imported OpenCode state from ${importStatePath}`)
const result = await syncOpenCodeImport({ db, overwriteState: false })
if (result.stateImported) {
logger.info(`Imported OpenCode state from ${status.stateSourcePath}`)
}
} catch (error) {
logger.warn('Failed to import OpenCode state, continuing without imported state', error)
}
@@ -359,7 +260,7 @@ const protectedApi = new Hono()
protectedApi.use('/*', requireAuth)
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService))
protectedApi.route('/settings', createSettingsRoutes(db))
protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService))
protectedApi.route('/files', createFileRoutes())
protectedApi.route('/providers', createProvidersRoutes())
protectedApi.route('/oauth', createOAuthRoutes())
+75 -1
View File
@@ -20,10 +20,13 @@ import {
} from '@opencode-manager/shared'
import { logger } from '../utils/logger'
import { opencodeServerManager } from '../services/opencode-single-server'
import type { GitAuthService } from '../services/git-auth'
import { DEFAULT_AGENTS_MD } from '../constants'
import { validateSSHPrivateKey } from '../utils/ssh-validation'
import { encryptSecret } from '../utils/crypto'
import { compareVersions, isValidVersion } from '../utils/version-utils'
import { getImportedSessionDirectories, getOpenCodeImportStatus, syncOpenCodeImport } from '../services/opencode-import'
import { relinkReposFromSessionDirectories } from '../services/repo'
import {
listManagedSkills,
getSkill,
@@ -153,6 +156,10 @@ const TestSSHConnectionSchema = z.object({
passphrase: z.string().optional(),
})
const SyncOpenCodeImportSchema = z.object({
overwriteState: z.boolean().optional(),
})
async function extractOpenCodeError(response: Response, defaultError: string): Promise<string> {
const errorObj = await response.json().catch(() => null)
@@ -161,7 +168,7 @@ async function extractOpenCodeError(response: Response, defaultError: string): P
: defaultError
}
export function createSettingsRoutes(db: Database) {
export function createSettingsRoutes(db: Database, gitAuthService: GitAuthService) {
const app = new Hono()
const settingsService = new SettingsService(db)
@@ -432,6 +439,73 @@ export function createSettingsRoutes(db: Database) {
}
})
app.get('/opencode-import/status', async (c) => {
try {
return c.json(await getOpenCodeImportStatus())
} catch (error) {
logger.error('Failed to get OpenCode import status:', error)
return c.json({
error: 'Failed to get OpenCode import status',
details: error instanceof Error ? error.message : 'Unknown error'
}, 500)
}
})
app.post('/opencode-import', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const rawBody = c.req.header('content-type')?.includes('application/json') ? await c.req.json() : {}
const body = SyncOpenCodeImportSchema.parse(rawBody)
const result = await syncOpenCodeImport({
db,
userId,
overwriteState: body.overwriteState ?? true,
})
if (!result.configImported && !result.stateImported) {
return c.json({
error: 'No importable OpenCode host data found',
...result,
}, 404)
}
let relinkedRepos
if (result.stateImported) {
const importedSessions = await getImportedSessionDirectories(result.workspaceStatePath)
relinkedRepos = await relinkReposFromSessionDirectories(db, gitAuthService, importedSessions.directories)
} else {
relinkedRepos = {
repos: [],
relinkedCount: 0,
existingCount: 0,
nonRepoPathCount: 0,
duplicatePathCount: 0,
errors: [],
}
}
opencodeServerManager.clearStartupError()
await opencodeServerManager.restart()
return c.json({
success: true,
message: 'Imported existing OpenCode host data and restarted the server',
serverRestarted: true,
relinkedRepos,
...result,
})
} catch (error) {
logger.error('Failed to import existing OpenCode host data:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid OpenCode import request', details: error.issues }, 400)
}
return c.json({
error: 'Failed to import existing OpenCode host data',
details: error instanceof Error ? error.message : 'Unknown error'
}, 500)
}
})
app.post('/opencode-reload', async (c) => {
try {
logger.info('OpenCode configuration reload requested')
+221
View File
@@ -0,0 +1,221 @@
import os from 'os'
import path from 'path'
import { cp, readdir, rm } from 'fs/promises'
import { Database as SQLiteDatabase, type Database } from 'bun:sqlite'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
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'
const OPENCODE_STATE_DB_FILENAMES = new Set(['opencode.db', 'opencode.db-shm', 'opencode.db-wal'])
export interface OpenCodeImportStatus {
configSourcePath: string | null
stateSourcePath: string | null
workspaceConfigPath: string
workspaceStatePath: string
workspaceStateExists: boolean
}
export interface SyncOpenCodeImportOptions {
db: Database
userId?: string
overwriteState?: boolean
}
export interface SyncOpenCodeImportResult extends OpenCodeImportStatus {
configImported: boolean
stateImported: boolean
}
export interface ImportedSessionDirectorySummary {
directories: string[]
}
export function getImportPathCandidates(envKey: string, fallbackPath: string): string[] {
const candidates = [process.env[envKey], fallbackPath]
.filter((value): value is string => Boolean(value))
.map((value) => path.resolve(value))
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
}
async function getFirstExistingPathWithDatabase(paths: string[]): Promise<string | null> {
for (const candidate of paths) {
if (await fileExists(candidate) && await fileExists(path.join(candidate, 'opencode.db'))) {
return candidate
}
}
return null
}
function escapeSqliteValue(value: string): string {
return value.replace(/'/g, "''")
}
async function copyOpenCodeStateFiles(sourcePath: string, targetPath: string): Promise<void> {
const entries = await readdir(sourcePath, { withFileTypes: true })
for (const entry of entries) {
if (OPENCODE_STATE_DB_FILENAMES.has(entry.name)) {
continue
}
await cp(path.join(sourcePath, entry.name), path.join(targetPath, entry.name), {
recursive: true,
force: true,
errorOnExist: false,
})
}
}
function snapshotOpenCodeDatabase(sourcePath: string, targetPath: string): void {
const database = new SQLiteDatabase(sourcePath)
try {
database.exec(`VACUUM INTO '${escapeSqliteValue(targetPath)}'`)
} finally {
database.close()
}
}
export async function importOpenCodeStateDirectory(sourcePath: string, targetPath: string): Promise<boolean> {
const resolvedSourcePath = path.resolve(sourcePath)
const resolvedTargetPath = path.resolve(targetPath)
const sourceDbPath = path.join(resolvedSourcePath, 'opencode.db')
if (!await fileExists(sourceDbPath)) {
return false
}
if (resolvedSourcePath === resolvedTargetPath) {
return false
}
await ensureDirectoryExists(resolvedTargetPath)
const existingEntries = await readdir(resolvedTargetPath, { withFileTypes: true })
for (const entry of existingEntries) {
if (!OPENCODE_STATE_DB_FILENAMES.has(entry.name)) {
await rm(path.join(resolvedTargetPath, entry.name), { recursive: true, force: true })
}
}
await rm(path.join(resolvedTargetPath, 'opencode.db'), { force: true })
await rm(path.join(resolvedTargetPath, 'opencode.db-shm'), { force: true })
await rm(path.join(resolvedTargetPath, 'opencode.db-wal'), { force: true })
await copyOpenCodeStateFiles(resolvedSourcePath, resolvedTargetPath)
snapshotOpenCodeDatabase(sourceDbPath, path.join(resolvedTargetPath, 'opencode.db'))
return true
}
export async function getOpenCodeImportStatus(): Promise<OpenCodeImportStatus> {
const workspaceConfigPath = getOpenCodeConfigFilePath()
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 stateSourcePath = await getFirstExistingPathWithDatabase(
getImportPathCandidates('OPENCODE_IMPORT_STATE_PATH', path.join(os.homedir(), '.local', 'share', 'opencode'))
)
return {
configSourcePath,
stateSourcePath,
workspaceConfigPath,
workspaceStatePath,
workspaceStateExists,
}
}
async function importOpenCodeConfigFromSource(db: Database, userId: string, sourcePath: string, workspaceConfigPath: string): Promise<boolean> {
const rawContent = await readFileContent(sourcePath)
const parsed = parseJsonc(rawContent)
const validation = OpenCodeConfigSchema.safeParse(parsed)
if (!validation.success) {
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)
return true
}
export async function syncOpenCodeImport(options: SyncOpenCodeImportOptions): Promise<SyncOpenCodeImportResult> {
const initialStatus = await getOpenCodeImportStatus()
const userId = options.userId || 'default'
let configImported = false
let stateImported = false
if (initialStatus.configSourcePath) {
configImported = await importOpenCodeConfigFromSource(options.db, userId, initialStatus.configSourcePath, initialStatus.workspaceConfigPath)
}
if (initialStatus.stateSourcePath && ((options.overwriteState ?? true) || !initialStatus.workspaceStateExists)) {
stateImported = await importOpenCodeStateDirectory(initialStatus.stateSourcePath, initialStatus.workspaceStatePath)
}
const finalStatus = await getOpenCodeImportStatus()
return {
...finalStatus,
configImported,
stateImported,
}
}
export async function getImportedSessionDirectories(workspaceStatePath?: string): Promise<ImportedSessionDirectorySummary> {
const statePath = workspaceStatePath || path.join(getWorkspacePath(), '.opencode', 'state', 'opencode')
const stateDbPath = path.join(statePath, 'opencode.db')
if (!await fileExists(stateDbPath)) {
return { directories: [] }
}
const database = new SQLiteDatabase(stateDbPath, { readonly: true })
try {
const rows = database
.query("SELECT DISTINCT directory FROM session WHERE directory IS NOT NULL AND TRIM(directory) != '' ORDER BY directory")
.all() as Array<{ directory: string }>
return {
directories: rows
.map((row) => row.directory.trim())
.filter(Boolean),
}
} finally {
database.close()
}
}
+80
View File
@@ -230,6 +230,16 @@ async function safeGetCurrentBranch(repoPath: string, env: Record<string, string
}
}
async function findGitRepoRoot(targetPath: string, env: Record<string, string>): Promise<string | null> {
try {
const resolvedPath = normalizeAbsolutePath(targetPath)
const repoRoot = await executeCommand(['git', '-C', resolvedPath, 'rev-parse', '--show-toplevel'], { env, silent: true })
return normalizeAbsolutePath(repoRoot.trim())
} catch {
return null
}
}
async function registerExistingLocalRepo(
database: Database,
gitAuthService: GitAuthService,
@@ -375,6 +385,76 @@ export async function discoverLocalRepos(
}
}
export async function relinkReposFromSessionDirectories(
database: Database,
gitAuthService: GitAuthService,
directories: string[]
): Promise<{
repos: Repo[]
relinkedCount: number
existingCount: number
nonRepoPathCount: number
duplicatePathCount: number
errors: Array<{ path: string; error: string }>
}> {
const env = gitAuthService.getGitEnvironment()
const errors: Array<{ path: string; error: string }> = []
const uniqueRepoRoots = new Set<string>()
let nonRepoPathCount = 0
let duplicatePathCount = 0
for (const directory of directories) {
const normalizedDirectory = normalizeInputPath(directory)
if (!normalizedDirectory) {
nonRepoPathCount += 1
continue
}
const repoRoot = await findGitRepoRoot(normalizedDirectory, env)
if (!repoRoot) {
nonRepoPathCount += 1
continue
}
if (uniqueRepoRoots.has(repoRoot)) {
duplicatePathCount += 1
continue
}
uniqueRepoRoots.add(repoRoot)
}
const repos: Repo[] = []
let relinkedCount = 0
let existingCount = 0
for (const repoRoot of Array.from(uniqueRepoRoots).sort((left, right) => left.localeCompare(right))) {
try {
const result = await registerExistingLocalRepo(database, gitAuthService, repoRoot)
repos.push(result.repo)
if (result.existed) {
existingCount += 1
} else {
relinkedCount += 1
}
} catch (error: unknown) {
errors.push({
path: repoRoot,
error: getErrorMessage(error),
})
}
}
return {
repos,
relinkedCount,
existingCount,
nonRepoPathCount,
duplicatePathCount,
errors,
}
}
async function checkoutBranchSafely(repoPath: string, branch: string, env: Record<string, string>): Promise<void> {
const sanitizedBranch = branch
.replace(/^refs\/heads\//, '')