fix(servers): address CodeRabbit review on linked-server automation

Scope session permission modes and schedule locks by server, keep remote schedule cleanup working when a server is disabled or removed, harden the session server-scope migration and rollback, reject local server multi-run targets, widen schedule query invalidation, and update CLI fixtures for server-scoped schemas.
This commit is contained in:
Chris Scott committed 2026-10-18 21:01:53 -04:00
1 parent 780d31087b
commit 9ec2ed5903
13 files changed
+426 -49

No files matched your search

@@ -3,6 +3,13 @@ import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import type { Migration } from '../migration-runner'
const SERVER_ID_COLUMN = 'server_id'
const PERMISSION_MODES_TABLE = 'session_permission_modes'
const PERMISSION_MODES_REBUILD_TABLE = 'session_permission_modes_rebuild'
interface ColumnInfo {
name: string
pk: number
}
function tableExists(db: Database, table: string): boolean {
return Boolean(
@@ -10,9 +17,19 @@ function tableExists(db: Database, table: string): boolean {
)
}
function tableColumns(db: Database, table: string): ColumnInfo[] {
return db.prepare(`PRAGMA table_info(${table})`).all() as ColumnInfo[]
}
function hasColumn(db: Database, table: string, column: string): boolean {
const columns = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>
return columns.some((entry) => entry.name === column)
return tableColumns(db, table).some((entry) => entry.name === column)
}
function primaryKeyColumns(db: Database, table: string): string[] {
return tableColumns(db, table)
.filter((column) => column.pk > 0)
.sort((left, right) => left.pk - right.pk)
.map((column) => column.name)
}
function addServerIdColumn(db: Database, table: string): void {
@@ -29,22 +46,88 @@ function dropServerIdColumn(db: Database, table: string): void {
db.run(`ALTER TABLE ${table} DROP COLUMN ${SERVER_ID_COLUMN}`)
}
function deleteRemoteRows(db: Database, table: string): void {
if (!tableExists(db, table) || !hasColumn(db, table, SERVER_ID_COLUMN)) {
return
}
db.run(`DELETE FROM ${table} WHERE ${SERVER_ID_COLUMN} <> '${LOCAL_OPENCODE_SERVER_ID}'`)
}
function rebuildPermissionModesForServers(db: Database): void {
if (!tableExists(db, PERMISSION_MODES_TABLE) || !hasColumn(db, PERMISSION_MODES_TABLE, SERVER_ID_COLUMN)) {
return
}
const primaryKey = primaryKeyColumns(db, PERMISSION_MODES_TABLE)
if (primaryKey.length === 2 && primaryKey[0] === SERVER_ID_COLUMN && primaryKey[1] === 'session_id') {
return
}
db.run(`DROP TABLE IF EXISTS ${PERMISSION_MODES_REBUILD_TABLE}`)
db.run(`
CREATE TABLE ${PERMISSION_MODES_REBUILD_TABLE} (
session_id TEXT NOT NULL,
server_id TEXT NOT NULL DEFAULT '${LOCAL_OPENCODE_SERVER_ID}',
mode TEXT NOT NULL CHECK(mode IN ('ask','auto')),
updated_at INTEGER NOT NULL,
PRIMARY KEY (server_id, session_id)
)
`)
db.run(`
INSERT INTO ${PERMISSION_MODES_REBUILD_TABLE}(session_id, server_id, mode, updated_at)
SELECT session_id, ${SERVER_ID_COLUMN}, mode, updated_at FROM ${PERMISSION_MODES_TABLE}
`)
db.run(`DROP TABLE ${PERMISSION_MODES_TABLE}`)
db.run(`ALTER TABLE ${PERMISSION_MODES_REBUILD_TABLE} RENAME TO ${PERMISSION_MODES_TABLE}`)
}
function rebuildPermissionModesForLocalSessions(db: Database): void {
if (!tableExists(db, PERMISSION_MODES_TABLE) || !hasColumn(db, PERMISSION_MODES_TABLE, SERVER_ID_COLUMN)) {
return
}
const primaryKey = primaryKeyColumns(db, PERMISSION_MODES_TABLE)
if (primaryKey.length === 1 && primaryKey[0] === 'session_id') {
return
}
db.run(`DROP TABLE IF EXISTS ${PERMISSION_MODES_REBUILD_TABLE}`)
db.run(`
CREATE TABLE ${PERMISSION_MODES_REBUILD_TABLE} (
session_id TEXT PRIMARY KEY,
mode TEXT NOT NULL CHECK(mode IN ('ask','auto')),
updated_at INTEGER NOT NULL
)
`)
db.run(`
INSERT INTO ${PERMISSION_MODES_REBUILD_TABLE}(session_id, mode, updated_at)
SELECT session_id, mode, updated_at FROM ${PERMISSION_MODES_TABLE}
WHERE ${SERVER_ID_COLUMN} = '${LOCAL_OPENCODE_SERVER_ID}'
`)
db.run(`DROP TABLE ${PERMISSION_MODES_TABLE}`)
db.run(`ALTER TABLE ${PERMISSION_MODES_REBUILD_TABLE} RENAME TO ${PERMISSION_MODES_TABLE}`)
}
const migration: Migration = {
id: '202610181300-session-server-scope',
up(db) {
addServerIdColumn(db, 'session_permission_modes')
addServerIdColumn(db, PERMISSION_MODES_TABLE)
addServerIdColumn(db, 'session_goals')
rebuildPermissionModesForServers(db)
db.run('DROP INDEX IF EXISTS idx_session_goals_open')
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_goals_open
ON session_goals(server_id, session_id)
WHERE status IN ('active','paused')
`)
if (tableExists(db, 'session_goals')) {
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_goals_open
ON session_goals(server_id, session_id)
WHERE status IN ('active','paused')
`)
}
},
down(db) {
deleteRemoteRows(db, 'session_goals')
deleteRemoteRows(db, PERMISSION_MODES_TABLE)
db.run('DROP INDEX IF EXISTS idx_session_goals_open')
if (tableExists(db, 'session_goals')) {
db.run(`
@@ -53,8 +136,8 @@ const migration: Migration = {
WHERE status IN ('active','paused')
`)
}
rebuildPermissionModesForLocalSessions(db)
dropServerIdColumn(db, 'session_goals')
dropServerIdColumn(db, 'session_permission_modes')
},
}
+7 -3
View File
@@ -536,9 +536,13 @@ export function getScheduleRunById(db: Database, repoId: number | null, jobId: n
return row ? rowToScheduleRun(row) : null
}
export function getScheduleRunBySessionId(db: Database, sessionId: string): ScheduleRun | null {
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE session_id = ? ORDER BY started_at DESC LIMIT 1')
const row = stmt.get(sessionId) as ScheduleRunRow | undefined
export function getScheduleRunBySessionId(
db: Database,
sessionId: string,
serverId: string = LOCAL_OPENCODE_SERVER_ID,
): ScheduleRun | null {
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE server_id = ? AND session_id = ? ORDER BY started_at DESC LIMIT 1')
const row = stmt.get(serverId, sessionId) as ScheduleRunRow | undefined
return row ? rowToScheduleRun(row) : null
}
+4 -4
View File
@@ -4,10 +4,11 @@ import { LOCAL_OPENCODE_SERVER_ID, type SessionPermissionMode } from '@opencode-
export function ensureSessionPermissionModesTable(db: Database): void {
db.run(`
CREATE TABLE IF NOT EXISTS session_permission_modes (
session_id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
server_id TEXT NOT NULL DEFAULT 'local',
mode TEXT NOT NULL CHECK(mode IN ('ask','auto')),
updated_at INTEGER NOT NULL
updated_at INTEGER NOT NULL,
PRIMARY KEY (server_id, session_id)
)
`)
}
@@ -32,8 +33,7 @@ export function setSessionPermissionMode(
db.prepare(`
INSERT INTO session_permission_modes(server_id, session_id, mode, updated_at)
VALUES(?,?,?,?)
ON CONFLICT(session_id) DO UPDATE SET
server_id=excluded.server_id,
ON CONFLICT(server_id, session_id) DO UPDATE SET
mode=excluded.mode,
updated_at=excluded.updated_at
`).run(serverId, sessionId, mode, Date.now())
+3
View File
@@ -88,6 +88,9 @@ function multiRunTargetFromRequest(
request: Pick<LaunchMultiRunRequest, 'repoId' | 'serverId' | 'directory'>,
): MultiRunTarget {
if (request.serverId !== undefined) {
if (request.serverId === LOCAL_OPENCODE_SERVER_ID) {
throw new MultiRunError('Local multi-runs must target a repository', 400)
}
if (request.directory === undefined) {
throw new MultiRunError('A server multi-run needs a directory', 400)
}
+20 -14
View File
@@ -415,6 +415,13 @@ export class ScheduleService {
}
}
private resolveTargetPersistence(target: ScheduleJobTarget): { repo: Repo | null; repoId: number | null } {
if (target.kind === 'repo') {
return { repo: this.assertRepo(target.repoId), repoId: target.repoId }
}
return { repo: null, repoId: null }
}
private targetForJob(job: ScheduleJob): ScheduleJobTarget {
if (job.repoId !== null) {
return { kind: 'repo', repoId: job.repoId }
@@ -570,7 +577,6 @@ export class ScheduleService {
}
listServerJobs(serverId: string): ScheduleJob[] {
this.assertServer(serverId)
return listScheduleJobsByServer(this.db, serverId)
}
@@ -672,13 +678,13 @@ export class ScheduleService {
private async deleteJobForTarget(target: ScheduleJobTarget, jobId: number): Promise<void> {
const job = this.loadJobForTarget(target, jobId)
const context = this.resolveTargetContext(target, job.directory)
const { repoId } = this.resolveTargetPersistence(target)
if (ScheduleService.activeRuns.has(jobId)) {
throw new ScheduleServiceError('Cannot delete a schedule while it is running. Cancel the run first.', 409)
}
const runningRun = getRunningScheduleRunByJob(this.db, context.repoId, jobId)
const runningRun = getRunningScheduleRunByJob(this.db, repoId, jobId)
if (runningRun) {
throw new ScheduleServiceError('Cannot delete a schedule while it is running. Cancel the run first.', 409)
}
@@ -691,7 +697,7 @@ export class ScheduleService {
await this.removeWorktrees(target.repoId, jobId)
}
const deleted = deleteScheduleJob(this.db, context.repoId, jobId)
const deleted = deleteScheduleJob(this.db, repoId, jobId)
if (!deleted) {
throw new ScheduleServiceError('Schedule not found', 404)
}
@@ -781,17 +787,17 @@ export class ScheduleService {
private async clearRunHistoryForTarget(target: ScheduleJobTarget, jobId: number, worktrees: ScheduleRunWorktreesMode = 'commit'): Promise<{ cleared: number }> {
const job = this.loadJobForTarget(target, jobId)
const context = this.resolveTargetContext(target, job.directory)
const { repo, repoId } = this.resolveTargetPersistence(target)
const removable = listScheduleRunArtifactsByJob(this.db, context.repoId, jobId).filter((run) => run.status !== 'running')
const removable = listScheduleRunArtifactsByJob(this.db, repoId, jobId).filter((run) => run.status !== 'running')
if (removable.length === 0) {
return { cleared: 0 }
}
if (context.repo) {
await this.worktreeManager.pruneRunArtifacts(context.repo, job, removable, worktrees)
if (repo) {
await this.worktreeManager.pruneRunArtifacts(repo, job, removable, worktrees)
}
const cleared = deleteScheduleRunsByIds(this.db, context.repoId, jobId, removable.map((run) => run.id))
const cleared = deleteScheduleRunsByIds(this.db, repoId, jobId, removable.map((run) => run.id))
return { cleared }
}
@@ -811,8 +817,8 @@ export class ScheduleService {
private async deleteRunForTarget(target: ScheduleJobTarget, jobId: number, runId: number, worktrees: ScheduleRunWorktreesMode = 'commit'): Promise<void> {
const job = this.loadJobForTarget(target, jobId)
const context = this.resolveTargetContext(target, job.directory)
const run = getScheduleRunById(this.db, context.repoId, jobId, runId)
const { repo, repoId } = this.resolveTargetPersistence(target)
const run = getScheduleRunById(this.db, repoId, jobId, runId)
if (!run) {
throw new ScheduleServiceError('Run not found', 404)
@@ -821,10 +827,10 @@ export class ScheduleService {
throw new ScheduleServiceError('Cannot delete a run while it is in progress. Cancel it first.', 409)
}
if (context.repo) {
await this.worktreeManager.pruneRunArtifacts(context.repo, job, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }], worktrees)
if (repo) {
await this.worktreeManager.pruneRunArtifacts(repo, job, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }], worktrees)
}
const deleted = deleteScheduleRunById(this.db, context.repoId, jobId, runId)
const deleted = deleteScheduleRunById(this.db, repoId, jobId, runId)
if (!deleted) {
throw new ScheduleServiceError('Run not found', 404)
}
@@ -209,7 +209,7 @@ export class SessionPermissionModeService {
rootSessionId: string,
serverId: string,
): SessionLockReason | null {
if (serverId === LOCAL_OPENCODE_SERVER_ID && getScheduleRunBySessionId(this.db, rootSessionId)) {
if (getScheduleRunBySessionId(this.db, rootSessionId, serverId)) {
return 'schedule'
}