feat(schedules): add workspace modes and worktree management

This commit is contained in:
Chris Scott committed 2026-10-06 10:16:34 -04:00
1 parent c06075651d
commit 6ec3f3bd91
90 files changed
+2084 -801

No files matched your search

+67 -51
View File
@@ -1,65 +1,38 @@
import { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
/**
* A schema change applied once per database. Migrations run in the order they appear in
* `allMigrations`, and each is recorded by its `id`, which must never change once released.
*
* New migrations use a UTC timestamp id, `YYYYMMDDHHmm-short-name` (for example
* `202610061345-schedule-workspace-mode`), in a file of the same name, so migrations written on
* different branches cannot claim the same identity. Make `up` safe to run on a database that
* already has the change, because merged branches may apply migrations in a different order.
*
* `legacy` only exists on the numbered migrations written before ids; it lets databases that
* recorded them by version number in `schema_migrations` recognise them as applied.
*/
export interface Migration {
version: number
name: string
id: string
legacy?: { version: number; name: string }
up(db: Database): void
down(db: Database): void
}
interface MigrationRecord {
interface LegacyMigrationRecord {
version: number
name: string
applied_at: number
}
function ensureMigrationsTable(db: Database): void {
db.run(`
CREATE TABLE IF NOT EXISTS schema_migrations (
version INTEGER PRIMARY KEY,
name TEXT NOT NULL,
applied_at INTEGER NOT NULL
)
`)
}
function getAppliedMigrations(db: Database): Map<number, string> {
const rows = db.prepare('SELECT version, name FROM schema_migrations ORDER BY version').all() as MigrationRecord[]
return new Map(rows.map(r => [r.version, r.name]))
}
/**
* Surfaces version-number collisions where a recorded migration's name differs
* from the code migration registered under the same version. The runner keys on
* version number alone, so a reused version silently skips the real migration
* (e.g. an ADD COLUMN), producing later runtime errors that are hard to trace.
* This converts that silent skip into a loud, actionable warning.
*/
function warnOnVersionNameMismatch(applied: Map<number, string>, migrations: Migration[]): void {
for (const migration of migrations) {
const recordedName = applied.get(migration.version)
if (recordedName !== undefined && recordedName !== migration.name) {
logger.warn(
`Migration version ${migration.version} is recorded as "${recordedName}" but the code defines "${migration.name}". ` +
`This migration was skipped; its schema changes may be missing. Verify the database schema and apply the changes manually if needed.`,
)
}
}
}
function markApplied(db: Database, migration: Migration): void {
db.prepare('INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)')
.run(migration.version, migration.name, Date.now())
}
export function migrate(db: Database, migrations: Migration[]): void {
ensureMigrationsTable(db)
assertUniqueIds(migrations)
db.run('CREATE TABLE IF NOT EXISTS applied_migrations (id TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)')
adoptLegacyMigrations(db, migrations)
const applied = getAppliedMigrations(db)
warnOnVersionNameMismatch(applied, migrations)
const sorted = [...migrations].sort((a, b) => a.version - b.version)
const pending = sorted.filter(m => !applied.has(m.version))
const applied = new Set((db.prepare('SELECT id FROM applied_migrations').all() as Array<{ id: string }>).map((row) => row.id))
const pending = migrations.filter((migration) => !applied.has(migration.id))
if (pending.length === 0) {
logger.info('Database schema is up to date')
@@ -69,16 +42,16 @@ export function migrate(db: Database, migrations: Migration[]): void {
logger.info(`Running ${pending.length} pending migration(s)`)
for (const migration of pending) {
logger.info(`Applying migration ${migration.version}: ${migration.name}`)
logger.info(`Applying migration ${migration.id}`)
db.run('BEGIN TRANSACTION')
try {
migration.up(db)
markApplied(db, migration)
db.prepare('INSERT INTO applied_migrations (id, applied_at) VALUES (?, ?)').run(migration.id, Date.now())
db.run('COMMIT')
logger.info(`Migration ${migration.version} applied successfully`)
logger.info(`Migration ${migration.id} applied successfully`)
} catch (error) {
db.run('ROLLBACK')
logger.error(`Migration ${migration.version} failed:`, error)
logger.error(`Migration ${migration.id} failed:`, error)
throw error
}
}
@@ -86,4 +59,47 @@ export function migrate(db: Database, migrations: Migration[]): void {
logger.info('All migrations applied successfully')
}
function assertUniqueIds(migrations: Migration[]): void {
const seen = new Set<string>()
for (const migration of migrations) {
if (seen.has(migration.id)) throw new Error(`Duplicate migration id "${migration.id}"`)
seen.add(migration.id)
}
}
/**
* Records numbered migrations that a database applied under the old version-keyed table.
* A version recorded under a different name is still treated as applied, as before, but warned
* about because its schema change may be missing.
*/
function adoptLegacyMigrations(db: Database, migrations: Migration[]): void {
const hasLegacyTable = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'").get()
if (!hasLegacyTable) return
const records = new Map(
(db.prepare('SELECT version, name, applied_at FROM schema_migrations').all() as LegacyMigrationRecord[])
.map((record) => [record.version, record] as const),
)
const adopted = migrations.flatMap((migration) => {
const record = migration.legacy ? records.get(migration.legacy.version) : undefined
if (!migration.legacy || !record) return []
if (record.name !== migration.legacy.name) {
logger.warn(
`Migration version ${migration.legacy.version} is recorded as "${record.name}" but the code defines "${migration.legacy.name}". ` +
`This migration was skipped; its schema changes may be missing. Verify the database schema and apply the changes manually if needed.`,
)
}
return [{ id: migration.id, appliedAt: record.applied_at }]
})
if (adopted.length === 0) return
const insert = db.prepare('INSERT OR IGNORE INTO applied_migrations (id, applied_at) VALUES (?, ?)')
db.run('BEGIN TRANSACTION')
try {
adopted.forEach((entry) => insert.run(entry.id, entry.appliedAt))
db.run('COMMIT')
} catch (error) {
db.run('ROLLBACK')
throw error
}
}
+2 -2
View File
@@ -1,8 +1,8 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 1,
name: 'base-schema',
id: '001-base-schema',
legacy: { version: 1, name: 'base-schema' },
up(db) {
db.run(`
@@ -6,8 +6,8 @@ interface ColumnInfo {
}
const migration: Migration = {
version: 2,
name: 'repos-nullable-url',
id: '002-repos-nullable-url',
legacy: { version: 2, name: 'repos-nullable-url' },
up(db) {
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
@@ -16,8 +16,8 @@ const COLUMNS = [
]
const migration: Migration = {
version: 3,
name: 'repos-add-columns',
id: '003-repos-add-columns',
legacy: { version: 3, name: 'repos-add-columns' },
up(db) {
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
@@ -1,8 +1,8 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 4,
name: 'repos-indexes',
id: '004-repos-indexes',
legacy: { version: 4, name: 'repos-indexes' },
up(db) {
db.run(`
@@ -2,8 +2,8 @@ import type { Migration } from '../migration-runner'
import { logger } from '../../utils/logger'
const migration: Migration = {
version: 5,
name: 'repos-local-path-prefix',
id: '005-repos-local-path-prefix',
legacy: { version: 5, name: 'repos-local-path-prefix' },
up(db) {
const repos = db.prepare("SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'").all() as Array<{
@@ -2,8 +2,8 @@ import type { Migration } from '../migration-runner'
import { logger } from '../../utils/logger'
const migration: Migration = {
version: 6,
name: 'git-token-to-credentials',
id: '006-git-token-to-credentials',
legacy: { version: 6, name: 'git-token-to-credentials' },
up(db) {
const rows = db.prepare('SELECT user_id, preferences FROM user_preferences').all() as Array<{
+2 -2
View File
@@ -1,8 +1,8 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 7,
name: 'schedules',
id: '007-schedules',
legacy: { version: 7, name: 'schedules' },
up(db) {
db.run(`
@@ -7,8 +7,8 @@ interface ColumnInfo {
}
const migration: Migration = {
version: 8,
name: 'schedule-cron-support',
id: '008-schedule-cron-support',
legacy: { version: 8, name: 'schedule-cron-support' },
up(db) {
const tableExists = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='schedule_jobs'").get()
@@ -1,8 +1,8 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 10,
name: '010-prompt-templates',
id: '009-prompt-templates',
legacy: { version: 10, name: '010-prompt-templates' },
up(db) {
db.run(`
@@ -5,8 +5,8 @@ interface ColumnInfo {
}
const migration: Migration = {
version: 9,
name: 'repo-source-path',
id: '009-repo-source-path',
legacy: { version: 9, name: 'repo-source-path' },
up(db) {
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
@@ -5,8 +5,8 @@ interface ColumnInfo {
}
const migration: Migration = {
version: 11,
name: 'repo-last-accessed',
id: '011-repo-last-accessed',
legacy: { version: 11, name: 'repo-last-accessed' },
up(db) {
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
@@ -1,8 +1,8 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 12,
name: 'opencode-model-state',
id: '012-opencode-model-state',
legacy: { version: 12, name: 'opencode-model-state' },
up(db) {
db.run(`
CREATE TABLE IF NOT EXISTS opencode_model_state (
+2 -2
View File
@@ -1,8 +1,8 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 13,
name: 'app-secrets',
id: '013-app-secrets',
legacy: { version: 13, name: 'app-secrets' },
up(db) {
db.run(`
CREATE TABLE IF NOT EXISTS app_secrets (
@@ -5,8 +5,8 @@ interface ColumnInfo {
}
const migration: Migration = {
version: 14,
name: 'repos-add-name',
id: '014-repos-add-name',
legacy: { version: 14, name: 'repos-add-name' },
up(db) {
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
@@ -7,8 +7,8 @@ interface ColumnInfo {
}
const migration: Migration = {
version: 15,
name: 'schedule-worktree-isolation',
id: '015-schedule-worktree-isolation',
legacy: { version: 15, name: 'schedule-worktree-isolation' },
up(db) {
const jobColumns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
@@ -7,8 +7,8 @@ interface ColumnInfo {
}
const migration: Migration = {
version: 16,
name: 'schedule-permission-config',
id: '016-schedule-permission-config',
legacy: { version: 16, name: 'schedule-permission-config' },
up(db) {
const cols = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
@@ -7,8 +7,8 @@ interface ColumnInfo {
}
const migration: Migration = {
version: 17,
name: 'schedule-run-workspace-id',
id: '017-schedule-run-workspace-id',
legacy: { version: 17, name: 'schedule-run-workspace-id' },
up(db) {
const cols = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
@@ -2,8 +2,8 @@ import type { Migration } from '../migration-runner'
import { ensureSessionPinsTable } from '../session-pins'
const migration: Migration = {
version: 18,
name: 'session-pins',
id: '018-session-pins',
legacy: { version: 18, name: 'session-pins' },
up(db) {
ensureSessionPinsTable(db)
},
@@ -45,8 +45,8 @@ function archiveConfigs(rows: Array<{ config_name: string; config_content: strin
}
const migration: Migration = {
version: 19,
name: 'drop-opencode-configs',
id: '019-drop-opencode-configs',
legacy: { 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 }>
@@ -49,8 +49,8 @@ function restoreModelStateFile(row: ModelStateRow): void {
}
const migration: Migration = {
version: 20,
name: 'drop-opencode-model-state',
id: '020-drop-opencode-model-state',
legacy: { version: 20, name: 'drop-opencode-model-state' },
up(db) {
const row = readDefaultRow(db)
@@ -5,8 +5,8 @@ interface ColumnInfo {
}
const migration: Migration = {
version: 21,
name: 'drop-schedule-run-workspace-id',
id: '021-drop-schedule-run-workspace-id',
legacy: { version: 21, name: 'drop-schedule-run-workspace-id' },
up(db) {
const cols = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
@@ -1,8 +1,8 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 22,
name: 'schedule-runs-session-index',
id: '022-schedule-runs-session-index',
legacy: { version: 22, name: 'schedule-runs-session-index' },
up(db) {
db.run(`
@@ -5,8 +5,8 @@ interface ColumnInfo {
}
const migration: Migration = {
version: 23,
name: 'schedule-mcp-servers',
id: '023-schedule-mcp-servers',
legacy: { version: 23, name: 'schedule-mcp-servers' },
up(db) {
const columns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
@@ -5,8 +5,8 @@ interface ColumnInfo {
}
const migration: Migration = {
version: 24,
name: 'schedule-runs-viewed-at',
id: '024-schedule-runs-viewed-at',
legacy: { version: 24, name: 'schedule-runs-viewed-at' },
up(db) {
const columns = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
@@ -2,8 +2,8 @@ import type { Migration } from '../migration-runner'
import { ensureSessionPermissionModesTable } from '../session-permission-modes'
const migration: Migration = {
version: 25,
name: 'session-permission-modes',
id: '025-session-permission-modes',
legacy: { version: 25, name: 'session-permission-modes' },
up(db) {
ensureSessionPermissionModesTable(db)
},
@@ -2,8 +2,8 @@ import type { Migration } from '../migration-runner'
import { ensureSessionGoalsTable } from '../session-goals'
const migration: Migration = {
version: 26,
name: 'session-goals',
id: '026-session-goals',
legacy: { version: 26, name: 'session-goals' },
up(db) {
ensureSessionGoalsTable(db)
},
+2 -2
View File
@@ -2,8 +2,8 @@ import type { Migration } from '../migration-runner'
import { ensureMultiRunTables } from '../multi-runs'
const migration: Migration = {
version: 27,
name: 'multi-runs',
id: '027-multi-runs',
legacy: { version: 27, name: 'multi-runs' },
up(db) {
ensureMultiRunTables(db)
},
@@ -0,0 +1,22 @@
import type { Migration } from '../migration-runner'
interface ColumnInfo {
name: string
}
const migration: Migration = {
id: '202610061345-schedule-workspace-mode',
up(db) {
const columns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
if (!columns.some((column) => column.name === 'workspace_mode')) {
db.run("ALTER TABLE schedule_jobs ADD COLUMN workspace_mode TEXT NOT NULL DEFAULT 'worktree'")
}
},
down(db) {
db.run('ALTER TABLE schedule_jobs DROP COLUMN workspace_mode')
},
}
export default migration
+2
View File
@@ -26,6 +26,7 @@ import migration024 from './024-schedule-runs-viewed-at'
import migration025 from './025-session-permission-modes'
import migration026 from './026-session-goals'
import migration027 from './027-multi-runs'
import migration202610061345 from './202610061345-schedule-workspace-mode'
export const allMigrations: Migration[] = [
migration001,
@@ -55,4 +56,5 @@ export const allMigrations: Migration[] = [
migration025,
migration026,
migration027,
migration202610061345,
]
+17 -7
View File
@@ -12,6 +12,7 @@ import {
type ScheduleRun,
type ScheduleRunStatus,
type ScheduleRunTriggerSource,
type ScheduleWorkspaceMode,
} from '@opencode-manager/shared/schemas'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME, ASSISTANT_REPO_PATH, getRepoDisplayName } from '@opencode-manager/shared/utils'
import type { ScheduleJobPersistenceInput } from '../services/schedule-config'
@@ -33,6 +34,7 @@ interface ScheduleJobRow {
permission_config: string | null
mcp_servers: string | null
branch: string | null
workspace_mode: ScheduleWorkspaceMode | null
created_at: number
updated_at: number
last_run_at: number | null
@@ -118,6 +120,7 @@ function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob {
permissionConfig: parsePermissionConfig(row.permission_config),
mcpServers: parseMcpServers(row.mcp_servers),
branch: row.branch,
workspaceMode: row.workspace_mode ?? 'worktree',
createdAt: row.created_at,
updatedAt: row.updated_at,
lastRunAt: row.last_run_at,
@@ -199,9 +202,10 @@ export function createScheduleJob(db: Database, repoId: number, input: ScheduleJ
permission_config,
mcp_servers,
branch,
workspace_mode,
created_at, updated_at, last_run_at, next_run_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`)
const result = stmt.run(
@@ -220,6 +224,7 @@ export function createScheduleJob(db: Database, repoId: number, input: ScheduleJ
serializePermissionConfig(input.permissionConfig),
serializeMcpServers(input.mcpServers),
input.branch,
input.workspaceMode,
now,
now,
null,
@@ -244,7 +249,7 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
const stmt = db.prepare(`
UPDATE schedule_jobs
SET name = ?, description = ?, enabled = ?, schedule_mode = ?, interval_minutes = ?, cron_expression = ?, timezone = ?,
agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, mcp_servers = ?, branch = ?, updated_at = ?, next_run_at = ?
agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, mcp_servers = ?, branch = ?, workspace_mode = ?, updated_at = ?, next_run_at = ?
WHERE repo_id = ? AND id = ?
`)
@@ -263,6 +268,7 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
serializePermissionConfig(input.permissionConfig),
serializeMcpServers(input.mcpServers),
input.branch,
input.workspaceMode,
now,
input.nextRunAt,
repoId,
@@ -298,11 +304,15 @@ export function listScheduleRunArtifactsByJob(db: Database, repoId: number, jobI
}))
}
export function listActiveScheduleRunWorktreePaths(db: Database): string[] {
const rows = db
.prepare('SELECT worktree_path FROM schedule_runs WHERE worktree_path IS NOT NULL')
.all() as { worktree_path: string }[]
return rows.map((row) => row.worktree_path)
export function getScheduleJobRepoId(db: Database, jobId: number): number | null {
const row = db.prepare('SELECT repo_id FROM schedule_jobs WHERE id = ?').get(jobId) as { repo_id: number } | undefined
return row?.repo_id ?? null
}
export function clearScheduleRunWorktreePath(db: Database, repoId: number, jobId: number, worktreePath: string): number {
return db
.prepare('UPDATE schedule_runs SET worktree_path = NULL WHERE repo_id = ? AND job_id = ? AND worktree_path = ?')
.run(repoId, jobId, worktreePath).changes
}
export function deleteScheduleRunById(db: Database, repoId: number, jobId: number, runId: number): boolean {
+1 -1
View File
@@ -243,9 +243,9 @@ const terminalService = new TerminalService(
() => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()),
)
const projectConfigService = new ProjectConfigService(db, createGitService(gitAuthService), gitAuthService)
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, gitAuthService, projectConfigService, terminalService)
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db)
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager)
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, gitAuthService, projectConfigService, terminalService, scheduleService)
const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
const notificationService = new NotificationService(db)
+1 -1
View File
@@ -53,7 +53,7 @@ function createTestApp(
prepareRepoDelete: () => {},
} as any
const projectConfigService = new ProjectConfigService(db, createGitService(stubGitAuthService), stubGitAuthService)
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, stubGitAuthService, projectConfigService, terminalService)
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, stubGitAuthService, projectConfigService, terminalService, scheduleService)
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces))
return app
}
+7 -2
View File
@@ -3,7 +3,7 @@ import { z } from 'zod'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import type { Database } from 'bun:sqlite'
import type { DeleteRepoResult, Repo } from '@opencode-manager/shared/types'
import { DiscoverReposRequestSchema, AssistantModeInitRequestSchema, UpdateRepoRequestSchema, DeleteRepoRequestSchema } from '@opencode-manager/shared/schemas'
import { DiscoverReposRequestSchema, AssistantModeInitRequestSchema, UpdateRepoRequestSchema, CreateRepoWorkspaceRequestSchema, DeleteRepoRequestSchema } from '@opencode-manager/shared/schemas'
import { listRepos, getRepoById, updateLastAccessed, getRepoGitCredentialId, setRepoGitCredentialId, updateRepoName } from '../db/queries'
import * as repoService from '../services/repo'
import * as archiveService from '../services/archive'
@@ -358,8 +358,13 @@ app.get('/', async (c) => {
const repo = getRepoById(database, id)
if (!repo || repo.cloneStatus !== 'ready') return c.json({ error: 'Repo not found' }, 404)
const parsed = CreateRepoWorkspaceRequestSchema.safeParse(await c.req.json().catch(() => ({})))
if (!parsed.success) {
return c.json({ error: parsed.error.issues[0]?.message ?? 'Invalid request' }, 400)
}
try {
return c.json(await repoWorkspaces.create(repo))
return c.json(await repoWorkspaces.create(repo, { name: parsed.data.name || undefined }))
} catch (error: unknown) {
if (isWorktreeError(error)) {
return c.json({ error: error.data.message }, 409)
+26 -2
View File
@@ -1,6 +1,7 @@
import { Hono } from 'hono'
import {
CreateScheduleJobRequestSchema,
RemoveScheduleWorktreesRequestSchema,
UpdateScheduleJobRequestSchema,
} from '@opencode-manager/shared/schemas'
import { ScheduleService, ScheduleServiceError } from '../services/schedules'
@@ -152,17 +153,40 @@ export function createScheduleRoutes(scheduleService: ScheduleService) {
}
})
app.delete('/:jobId', (c) => {
app.delete('/:jobId', async (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError)
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
scheduleService.deleteJob(repoId, jobId)
await scheduleService.deleteJob(repoId, jobId)
return c.json({ success: true })
} catch (error) {
return handleServiceError(c, error, 'Failed to delete schedule', ScheduleServiceError)
}
})
app.get('/:jobId/worktrees', (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError)
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
return c.json({ worktrees: scheduleService.listWorktrees(repoId, jobId) })
} catch (error) {
return handleServiceError(c, error, 'Failed to list schedule worktrees', ScheduleServiceError)
}
})
app.delete('/:jobId/worktrees', async (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError)
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
const body = await c.req.json().catch(() => ({}))
const input = RemoveScheduleWorktreesRequestSchema.parse(body)
const result = await scheduleService.removeWorktrees(repoId, jobId, input.worktreePath)
return c.json(result)
} catch (error) {
return handleServiceError(c, error, 'Failed to remove schedule worktrees', ScheduleServiceError)
}
})
app.post('/:jobId/run', async (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError)
+2
View File
@@ -400,6 +400,8 @@ Create a new schedule job.
Body matches \`CreateScheduleJobRequest\` schema (discriminated union with \`scheduleMode: 'interval' | 'cron'\`).
Optional \`workspaceMode\` sets where runs execute: \`worktree\` (default, a fresh worktree removed after each run), \`kept-worktree\` (a fresh worktree kept after each run), \`shared-worktree\` (one worktree and branch reused by every run), or \`repo\` (the repository checkout itself). Kept and shared worktrees are listed with \`GET /repos/:repoId/schedules/:jobId/worktrees\` and removed with \`DELETE /repos/:repoId/schedules/:jobId/worktrees\` (optional body \`{ "worktreePath": "..." }\`; omit it to remove every idle worktree). Pending changes are committed to the worktree's branch before removal.
\`\`\`json
{
"action": "request",
+2 -24
View File
@@ -6,7 +6,7 @@ import { getRepoById, getRepoByDirectory, updateRepoBranch, listRepos } from '..
import { updateScheduleJobsBranch } from '../../db/schedules'
import { isSSHUrl, getBranchNameError } from '@opencode-manager/shared/utils'
import { GitOperationError, isNoUpstreamError, parseGitError } from '../../utils/git-errors'
import { resolveMainCheckoutPath } from '../repo'
import { listGitWorktrees, resolveMainCheckoutPath } from '../repo'
import { MAX_COMMIT_PROMPT_DIFF_CHARS, type CommitMessageContext } from './commit-message-prompt'
import type { Database } from 'bun:sqlite'
import type { DeleteBranchResult, GitOperationKind, GitOperationState, GitStashEntry, IntegrateBranchRequest, IntegrateBranchResult, StashPushRequest } from '@opencode-manager/shared'
@@ -1058,30 +1058,8 @@ export class GitService {
)
}
private async listWorktreeCheckouts(repoPath: string, env: Record<string, string> | undefined): Promise<Array<{ path: string; branch: string | null }>> {
try {
const output = await executeCommand(['git', '-C', repoPath, 'worktree', 'list', '--porcelain'], { env, silent: true })
const checkouts: Array<{ path: string; branch: string | null }> = []
let current: { path: string; branch: string | null } | null = null
for (const line of output.split('\n')) {
if (line.startsWith('worktree ')) {
if (current) checkouts.push(current)
current = { path: line.slice('worktree '.length).trim(), branch: null }
} else if (line.startsWith('branch refs/heads/') && current) {
current.branch = line.slice('branch refs/heads/'.length).trim()
}
}
if (current) checkouts.push(current)
return checkouts
} catch {
return []
}
}
private async findCheckoutPath(repoPath: string, branch: string, env: Record<string, string> | undefined): Promise<string | null> {
const checkouts = await this.listWorktreeCheckouts(repoPath, env)
const checkouts = await listGitWorktrees(repoPath, env)
return checkouts.find((checkout) => checkout.branch === branch)?.path ?? null
}
+25 -1
View File
@@ -6,9 +6,12 @@ import type { GitAuthService } from './git-auth'
import type { OpenCodeClient } from './opencode/client'
import type { ProjectConfigService } from './project-config'
import type { TerminalService } from './terminal'
import type { ScheduleService } from './schedules'
import { findSiblingByDirectory, getSiblingRepos, RepoWorkspaceError, resolveRepoProjectId } from './repo'
import { executeCommand } from '../utils/process'
import { getErrorMessage } from '../utils/error-utils'
/** Single owner of OpenCode workspace lifecycle side effects: worktree setup on create and terminal cleanup on remove. */
/** Single owner of repo worktree lifecycle side effects: worktree setup on create, and terminal cleanup plus owner-specific removal on remove. */
export class RepoWorkspaceService {
constructor(
private readonly database: Database,
@@ -16,6 +19,7 @@ export class RepoWorkspaceService {
private readonly gitAuthService: GitAuthService,
private readonly projectConfigService: ProjectConfigService,
private readonly terminalService: TerminalService,
private readonly scheduleWorktrees: Pick<ScheduleService, 'removeWorktrees'>,
) {}
async create(repo: Repo, options: { name?: string; ref?: string } = {}) {
@@ -29,11 +33,31 @@ export class RepoWorkspaceService {
return { ...worktree, worktreeSetup }
}
/**
* Removes a worktree of the repo the way its owner expects: OpenCode worktrees through
* OpenCode, schedule worktrees through the schedule (committing pending changes first),
* and plain git worktrees with `git worktree remove`, which refuses uncommitted changes.
*/
async remove(repo: Repo, directory: string): Promise<void> {
const worktree = findSiblingByDirectory(await this.listWorktreeSiblings(repo.id), directory)
if (!worktree) throw new RepoWorkspaceError('Not a deletable worktree of this repo', 400)
if (worktree.schedule?.inUse) throw new RepoWorkspaceError('This worktree is in use by a running scheduled run. Cancel the run first.', 400)
await this.removeTerminals(worktree.fullPath)
if (worktree.schedule) {
await this.scheduleWorktrees.removeWorktrees(worktree.schedule.repoId, worktree.schedule.jobId, worktree.fullPath)
return
}
if (worktree.worktreeSource === 'git') {
await executeCommand(['git', '-C', repo.fullPath, 'worktree', 'remove', worktree.fullPath], { env: this.gitAuthService.getGitEnvironment(true) })
.catch((error: unknown) => {
throw new RepoWorkspaceError(`Could not remove worktree: ${getErrorMessage(error)}`, 400)
})
return
}
const projectID = await resolveRepoProjectId(this.openCodeClient, repo.fullPath)
await this.openCodeClient.api.worktree.remove({ projectID, directory: worktree.fullPath, force: true })
}
+126 -53
View File
@@ -7,7 +7,7 @@ import type { Database } from 'bun:sqlite'
import type { Repo, CreateRepoInput } from '../types/repo'
import { logger } from '../utils/logger'
import { getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, getRepoBaseDirectoryName, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, SCP_STYLE_URL_PATTERN, ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, getRepoBaseDirectoryName, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, SCP_STYLE_URL_PATTERN, ASSISTANT_REPO_ID, type RepoWorktreeSchedule, type RepoWorktreeSource } from '@opencode-manager/shared/utils'
import type { GitAuthService } from './git-auth'
import { isGitHubHttpsUrl } from '../utils/git-auth'
import path from 'path'
@@ -16,7 +16,8 @@ import { getErrorMessage } from '../utils/error-utils'
import { sseAggregator } from './sse-aggregator'
import { resolveProjectId, isGitMainCheckout } from './project-id-resolver'
import { listRepos } from '../db/queries'
import { listActiveScheduleRunWorktreePaths } from '../db/schedules'
import { getScheduleJobRepoId, listRunningScheduleRuns } from '../db/schedules'
import { parseScheduleWorktreeName } from './schedule-worktree-paths'
import { SettingsService } from './settings'
import { buildAssistantRepo } from './assistant-mode'
import type { OpenCodeClient } from './opencode/client'
@@ -1228,13 +1229,20 @@ export async function resolveRepoWorkingDirectory(
return findSiblingByDirectory(await loadSiblings(), directory)?.fullPath ?? null
}
export type RepoSibling = Repo & {
currentBranch: string | undefined
worktreeSource?: RepoWorktreeSource
worktreeStrategy?: string
schedule?: RepoWorktreeSchedule
}
export async function getSiblingRepos(
database: Database,
repoId: number,
gitEnv: Record<string, string>,
openCodeClient?: OpenCodeClient,
options: { includeBranch?: boolean } = {},
): Promise<Array<Repo & { currentBranch: string | undefined; worktreeStrategy?: string }>> {
): Promise<RepoSibling[]> {
const settingsService = new SettingsService(database)
const settings = settingsService.getSettings()
const allRepos = listRepos(database, settings.preferences.repoOrder)
@@ -1265,64 +1273,129 @@ export async function getSiblingRepos(
})),
)
if (!openCodeClient) return repoSiblings
const [openCodeWorktrees, gitWorktrees] = await Promise.all([
listOpenCodeWorktrees(openCodeClient, target.fullPath),
listGitWorktrees(target.fullPath, gitEnv),
])
try {
const projectID = await resolveRepoProjectId(openCodeClient, target.fullPath)
const worktrees = await openCodeClient.api.worktree.list({ projectID })
const excludedDirectories = new Set([
...repoSiblings.map((repo) => canonicalPathSync(path.resolve(repo.fullPath))),
canonicalPathSync(path.resolve(getReposPath())),
])
const candidates = new Map<string, { directory: string; strategy?: string; branch?: string; inGit: boolean }>()
openCodeWorktrees.forEach((worktree) => {
const key = canonicalPathSync(path.resolve(worktree.directory))
if (!excludedDirectories.has(key) && !candidates.has(key) && existsSync(worktree.directory)) {
candidates.set(key, { directory: worktree.directory, strategy: worktree.strategy, inGit: false })
}
})
gitWorktrees.slice(1).forEach((worktree) => {
const key = canonicalPathSync(path.resolve(worktree.path))
if (excludedDirectories.has(key)) return
const existing = candidates.get(key)
if (existing) {
existing.branch = worktree.branch ?? undefined
existing.inGit = true
return
}
if (existsSync(worktree.path)) {
candidates.set(key, { directory: worktree.path, branch: worktree.branch ?? undefined, inGit: true })
}
})
const knownDirectories = new Set(repoSiblings.map((repo) => canonicalPathSync(path.resolve(repo.fullPath))))
const targetDirectory = canonicalPathSync(path.resolve(target.fullPath))
const reposRoot = canonicalPathSync(path.resolve(getReposPath()))
const scheduleWorktreeRoot = canonicalPathSync(path.resolve(getScheduleWorktreesPath()))
const activeRunDirectories = new Set(
listActiveScheduleRunWorktreePaths(database).map((p) => canonicalPathSync(path.resolve(p))),
)
const entries = Array.from(candidates.entries())
const mainChecks = await Promise.all(
entries.map(([, candidate]) => isGitMainCheckout(candidate.directory).catch(() => false)),
)
const describeSchedule = createScheduleWorktreeDescriber(database)
const candidates = worktrees.filter((worktree) => {
const directory = canonicalPathSync(path.resolve(worktree.directory))
if (directory === targetDirectory) return false
if (directory === reposRoot) return false
if (directory.startsWith(`${scheduleWorktreeRoot}${path.sep}`)) return false
if (activeRunDirectories.has(directory)) return false
if (knownDirectories.has(directory)) return false
return true
const worktreeSiblings = entries
.filter((_, index) => !mainChecks[index])
.map(([key, candidate]) => {
const schedule = describeSchedule(key)
const worktreeSource: RepoWorktreeSource | undefined = schedule
? 'schedule'
: candidate.strategy ? 'opencode' : candidate.inGit ? 'git' : undefined
return {
id: -1,
repoUrl: target.repoUrl,
localPath: path.basename(candidate.directory),
fullPath: candidate.directory,
sourcePath: candidate.directory,
branch: candidate.branch,
defaultBranch: target.defaultBranch,
cloneStatus: 'ready' as const,
clonedAt: Date.now(),
isWorktree: true,
isLocal: true,
currentBranch: candidate.branch,
worktreeSource,
worktreeStrategy: candidate.strategy,
...(schedule ? { schedule } : {}),
}
})
const mainChecks = await Promise.all(
candidates.map((worktree) => isGitMainCheckout(worktree.directory).catch(() => false)),
)
return [...repoSiblings, ...worktreeSiblings]
}
const uniqueWorktrees = new Map<string, typeof candidates[number]>()
candidates
.filter((_, index) => !mainChecks[index])
.forEach((worktree) => {
const directory = canonicalPathSync(path.resolve(worktree.directory))
if (!uniqueWorktrees.has(directory)) {
uniqueWorktrees.set(directory, worktree)
}
})
const worktreeSiblings = Array.from(uniqueWorktrees.values()).map((worktree) => ({
id: -1,
repoUrl: target.repoUrl,
localPath: path.basename(worktree.directory),
fullPath: worktree.directory,
sourcePath: worktree.directory,
branch: undefined,
defaultBranch: target.defaultBranch,
cloneStatus: 'ready' as const,
clonedAt: Date.now(),
isWorktree: true,
isLocal: true,
currentBranch: undefined,
worktreeStrategy: worktree.strategy,
}))
return [...repoSiblings, ...worktreeSiblings]
async function listOpenCodeWorktrees(openCodeClient: OpenCodeClient | undefined, directory: string) {
if (!openCodeClient) return []
try {
const projectID = await resolveRepoProjectId(openCodeClient, directory)
return await openCodeClient.api.worktree.list({ projectID })
} catch (error) {
logger.warn('Failed to list OpenCode worktrees:', error)
return repoSiblings
return []
}
}
/**
* Lists a repository's git worktrees with their checked-out branch; the main worktree comes first.
*/
export async function listGitWorktrees(repoPath: string, env: Record<string, string> | undefined): Promise<Array<{ path: string; branch: string | null }>> {
try {
const output = await executeCommand(['git', '-C', repoPath, 'worktree', 'list', '--porcelain'], { env, silent: true })
const checkouts: Array<{ path: string; branch: string | null }> = []
let current: { path: string; branch: string | null } | null = null
for (const line of output.split('\n')) {
if (line.startsWith('worktree ')) {
current = { path: line.slice('worktree '.length).trim(), branch: null }
checkouts.push(current)
} else if (line.startsWith('branch refs/heads/') && current) {
current.branch = line.slice('branch refs/heads/'.length).trim()
}
}
return checkouts
} catch {
return []
}
}
/**
* Builds a lookup that says which schedule, if any, owns a canonical worktree directory:
* either a directory named for a schedule under the schedule worktree root, or the
* worktree a running run works in. Directories of deleted schedules are not owned.
*/
function createScheduleWorktreeDescriber(database: Database): (directory: string) => RepoWorktreeSchedule | undefined {
const scheduleRoot = canonicalPathSync(path.resolve(getScheduleWorktreesPath()))
const runningRuns = listRunningScheduleRuns(database)
const runningByDirectory = new Map(runningRuns.flatMap((run) => (
run.worktreePath ? [[canonicalPathSync(path.resolve(run.worktreePath)), run] as const] : []
)))
return (directory) => {
const running = runningByDirectory.get(directory)
const parsed = path.dirname(directory) === scheduleRoot ? parseScheduleWorktreeName(path.basename(directory)) : null
const jobId = parsed?.jobId ?? running?.jobId
if (jobId === undefined) return undefined
const repoId = running?.repoId ?? getScheduleJobRepoId(database, jobId)
if (repoId === null) return undefined
return {
repoId,
jobId,
runId: parsed ? parsed.runId : running?.id ?? null,
inUse: running !== undefined || (parsed?.runId === null && runningRuns.some((run) => run.jobId === jobId)),
}
}
}
+4
View File
@@ -6,6 +6,7 @@ import type {
ScheduleMode,
SchedulePermissionConfig,
ScheduleSkillMetadata,
ScheduleWorkspaceMode,
UpdateScheduleJobRequest,
} from '@opencode-manager/shared/types'
@@ -26,6 +27,7 @@ export interface ScheduleJobPersistenceInput {
permissionConfig: SchedulePermissionConfig | null
mcpServers: ScheduleMcpServer[]
branch: string | null
workspaceMode: ScheduleWorkspaceMode
nextRunAt: number | null
}
@@ -101,6 +103,7 @@ export function buildCreateSchedulePersistenceInput(input: CreateScheduleJobRequ
model: input.model?.trim() || null,
skillMetadata: input.skillMetadata,
branch: input.branch?.trim() || null,
workspaceMode: input.workspaceMode ?? 'worktree',
}
const scheduleConfig = input.scheduleMode === 'cron'
@@ -162,6 +165,7 @@ export function buildUpdatedSchedulePersistenceInput(
permissionConfig: input.permissionConfig === undefined ? existing.permissionConfig : (input.permissionConfig ?? null),
mcpServers: input.mcpServers ?? existing.mcpServers,
branch: input.branch === undefined ? existing.branch : (input.branch?.trim() || null),
workspaceMode: input.workspaceMode ?? existing.workspaceMode,
nextRunAt,
}
}
@@ -0,0 +1,30 @@
import path from 'path'
import { getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
const SCHEDULE_WORKTREE_DIRECTORY = /^job-(\d+)-(?:run-(\d+)|shared)$/
export function getSharedScheduleWorktreePath(jobId: number): string {
return path.join(getScheduleWorktreesPath(), `job-${jobId}-shared`)
}
export function getRunScheduleWorktreePath(jobId: number, runId: number): string {
return path.join(getScheduleWorktreesPath(), `job-${jobId}-run-${runId}`)
}
export function getSharedScheduleBranch(jobId: number): string {
return `schedule/${jobId}/shared`
}
export function getRunScheduleBranch(jobId: number, runId: number): string {
return `schedule/${jobId}/run-${runId}`
}
/**
* Reads the job and run a schedule worktree directory name belongs to. `runId` is null
* for a schedule's shared worktree; non-schedule names return null.
*/
export function parseScheduleWorktreeName(name: string): { jobId: number; runId: number | null } | null {
const match = SCHEDULE_WORKTREE_DIRECTORY.exec(name)
if (!match) return null
return { jobId: Number(match[1]), runId: match[2] ? Number(match[2]) : null }
}
+142 -33
View File
@@ -1,8 +1,9 @@
import { existsSync } from 'node:fs'
import { existsSync, readdirSync } from 'node:fs'
import path from 'path'
import type { Database } from 'bun:sqlite'
import { getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import type { ScheduleWorkspaceMode } from '@opencode-manager/shared/types'
import type { Repo } from '../types/repo'
import type { GitAuthService } from './git-auth'
import { isSSHUrl } from '@opencode-manager/shared/utils'
@@ -10,6 +11,13 @@ import { executeCommand } from '../utils/process'
import { resolveDefaultBranch, createWorktreeSafely, removeWorktree } from './repo'
import { logger } from '../utils/logger'
import { mkdirSyncSafe } from '../utils/fs-safe'
import {
getRunScheduleBranch,
getRunScheduleWorktreePath,
getSharedScheduleBranch,
getSharedScheduleWorktreePath,
parseScheduleWorktreeName,
} from './schedule-worktree-paths'
export interface ScheduleWorktreeContext {
directory: string
@@ -17,6 +25,20 @@ export interface ScheduleWorktreeContext {
runBranch: string
}
/**
* A schedule worktree directory found on disk. `runId` is null for a schedule's shared worktree.
*/
export interface ScheduleWorktreeEntry {
jobId: number
runId: number | null
worktreePath: string
branch: string
}
function isSharedWorktreePath(worktreePath: string): boolean {
return path.basename(worktreePath).endsWith('-shared')
}
/**
* Build repo-context environment variables used by the GIT_ASKPASS handler
* to resolve repo-specific credentials. Mirrors GitService.getEnvironmentForRepo.
@@ -34,12 +56,17 @@ export class ScheduleWorktreeManager {
private readonly db: Database,
) {}
/**
* Prepares the directory a run works in. Returns null when the run works in the
* repository checkout itself. A shared worktree that already exists is reused as-is;
* otherwise a worktree is created, continuing the shared branch when it already exists.
*/
async prepare(
repo: Repo,
job: { id: number; branch: string | null },
job: { id: number; branch: string | null; workspaceMode: ScheduleWorkspaceMode },
runId: number,
): Promise<ScheduleWorktreeContext | null> {
if (repo.id === ASSISTANT_REPO_ID) return null
if (repo.id === ASSISTANT_REPO_ID || job.workspaceMode === 'repo') return null
try {
await executeCommand(['git', '-C', repo.fullPath, 'rev-parse', '--is-inside-work-tree'], { silent: true })
@@ -47,6 +74,10 @@ export class ScheduleWorktreeManager {
return null
}
const shared = job.workspaceMode === 'shared-worktree'
const runBranch = shared ? getSharedScheduleBranch(job.id) : getRunScheduleBranch(job.id, runId)
const worktreePath = shared ? getSharedScheduleWorktreePath(job.id) : getRunScheduleWorktreePath(job.id, runId)
let sshSetup = false
if (repo.repoUrl && isSSHUrl(repo.repoUrl)) {
await this.gitAuthService.setupSSHForRepoUrl(repo.repoUrl, this.db)
@@ -56,6 +87,10 @@ export class ScheduleWorktreeManager {
try {
const env = await this.buildGitEnv(repo, sshSetup, true)
if (shared && await this.isUsableWorktree(worktreePath, env)) {
return { directory: worktreePath, worktreePath, runBranch }
}
await executeCommand(['git', '-C', repo.fullPath, 'fetch', '--prune', 'origin'], { env }).catch(() => {})
const base = job.branch?.trim() || (await resolveDefaultBranch(repo.fullPath, env))
@@ -64,9 +99,10 @@ export class ScheduleWorktreeManager {
throw new Error(`Base branch "${base}" was not found in this repository. Choose an existing branch in the schedule settings.`)
}
const runBranch = `schedule/${job.id}/run-${runId}`
if (existsSync(worktreePath)) {
await removeWorktree(repo.fullPath, worktreePath, env)
}
const worktreePath = path.join(getScheduleWorktreesPath(), `job-${job.id}-run-${runId}`)
mkdirSyncSafe(path.dirname(worktreePath))
await createWorktreeSafely(repo.fullPath, worktreePath, runBranch, env, baseRef)
@@ -82,15 +118,21 @@ export class ScheduleWorktreeManager {
}
}
/**
* Commits a finished run's changes to its branch. A `worktree` run's worktree is then
* removed, along with its branch when nothing was committed. Kept and shared worktrees
* stay on disk on their branch so the work can be continued.
*/
async finalize(
repo: Repo,
job: { id: number; name: string; prompt: string },
job: { id: number; name: string; prompt: string; workspaceMode: ScheduleWorkspaceMode },
run: { id: number; worktreePath: string | null; runBranch: string | null; triggerSource: string },
): Promise<{ commitHash: string | null }> {
if (!run.worktreePath) {
return { commitHash: null }
}
const retain = isSharedWorktreePath(run.worktreePath) || job.workspaceMode === 'kept-worktree'
let sshSetup = false
let env: Record<string, string> | undefined
let commitHash: string | null = null
@@ -103,33 +145,31 @@ export class ScheduleWorktreeManager {
env = await this.buildGitEnv(repo, sshSetup, false)
const status = await executeCommand(['git', '-C', run.worktreePath, 'status', '--porcelain'], { env }).catch(() => '')
const promptSummary = job.prompt.length > 200 ? `${job.prompt.slice(0, 200)}...` : job.prompt
commitHash = await this.commitPendingChanges(
run.worktreePath,
env,
`Scheduled run: ${job.name} (run #${run.id})`,
`Trigger: ${run.triggerSource}\nPrompt: ${promptSummary}`,
)
if (status.trim()) {
await executeCommand(['git', '-C', run.worktreePath, 'add', '-A'], { env })
const title = `Scheduled run: ${job.name} (run #${run.id})`
const promptSummary = job.prompt.length > 200 ? `${job.prompt.slice(0, 200)}...` : job.prompt
const body = `Trigger: ${run.triggerSource}\nPrompt: ${promptSummary}`
await executeCommand(['git', '-C', run.worktreePath, 'commit', '-m', title, '-m', body], { env })
commitHash = (await executeCommand(['git', '-C', run.worktreePath, 'rev-parse', 'HEAD'], { env })).trim()
if (!retain) {
await executeCommand(['git', '-C', run.worktreePath, 'checkout', '--detach'], { env }).catch(() => {})
}
// Detach HEAD to protect the run branch from accidental pushes
await executeCommand(['git', '-C', run.worktreePath, 'checkout', '--detach'], { env }).catch(() => {})
return { commitHash }
} catch (error) {
logger.error(`Failed to finalize schedule run ${run.id} in worktree ${run.worktreePath}:`, error)
throw error
} finally {
await removeWorktree(repo.fullPath, run.worktreePath, env).catch((error) => {
logger.error(`Failed to remove worktree ${run.worktreePath}:`, error)
})
if (!retain) {
await removeWorktree(repo.fullPath, run.worktreePath, env).catch((error) => {
logger.error(`Failed to remove worktree ${run.worktreePath}:`, error)
})
if (run.runBranch && !commitHash) {
await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', run.runBranch], env ? { env } : undefined).catch(() => undefined)
if (run.runBranch && !commitHash) {
await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', run.runBranch], env ? { env } : undefined).catch(() => undefined)
}
}
if (sshSetup) {
@@ -138,33 +178,102 @@ export class ScheduleWorktreeManager {
}
}
/**
* Removes a kept or shared worktree. Uncommitted changes are committed to its branch
* first and the branch is kept, so no work is lost; if that commit fails the worktree
* is left in place.
*/
async releaseWorktree(repo: Repo, job: { name: string }, worktreePath: string): Promise<void> {
const env = await this.buildGitEnv(repo, false, true)
if (existsSync(worktreePath)) {
await this.commitPendingChanges(worktreePath, env, `Schedule worktree removed: ${job.name}`, 'Uncommitted changes saved before the worktree was removed.')
}
await removeWorktree(repo.fullPath, worktreePath, env)
}
/**
* Lists the schedule worktree directories on disk, optionally for a single job.
*/
listWorktrees(jobId?: number): ScheduleWorktreeEntry[] {
let names: string[]
try {
names = readdirSync(getScheduleWorktreesPath())
} catch {
return []
}
return names.flatMap((name) => {
const parsed = parseScheduleWorktreeName(name)
if (!parsed || (jobId !== undefined && parsed.jobId !== jobId)) return []
return [{
jobId: parsed.jobId,
runId: parsed.runId,
worktreePath: path.join(getScheduleWorktreesPath(), name),
branch: parsed.runId === null ? getSharedScheduleBranch(parsed.jobId) : getRunScheduleBranch(parsed.jobId, parsed.runId),
}]
})
}
/**
* Removes leftover worktrees and deletes the run branches for a set of
* finished runs. Used when clearing run history. Branch and worktree removal
* are local git operations, so no SSH setup is needed; failures are swallowed
* per artifact so one bad entry does not block the rest.
* finished runs. Used when clearing run history. The job's shared worktree and
* branch are never touched, since they belong to the schedule rather than a run.
* Branch and worktree removal are local git operations, so no SSH setup is needed;
* failures are swallowed per artifact so one bad entry does not block the rest.
*/
async pruneRunArtifacts(
repo: Repo,
jobId: number,
artifacts: { runBranch: string | null; worktreePath: string | null }[],
): Promise<void> {
if (artifacts.length === 0) return
const sharedPath = getSharedScheduleWorktreePath(jobId)
const sharedBranch = getSharedScheduleBranch(jobId)
const worktreePaths = artifacts
.map((a) => a.worktreePath)
.filter((p): p is string => p !== null && p !== sharedPath)
const branches = artifacts
.map((a) => a.runBranch)
.filter((b): b is string => b !== null && b.length > 0 && b !== sharedBranch)
if (worktreePaths.length === 0 && branches.length === 0) return
const env = await this.buildGitEnv(repo, false, true)
await Promise.all(
artifacts.map(async (artifact) => {
if (!artifact.worktreePath) return
await removeWorktree(repo.fullPath, artifact.worktreePath, env).catch(() => undefined)
}),
worktreePaths.map((worktreePath) => removeWorktree(repo.fullPath, worktreePath, env).catch(() => undefined)),
)
const branches = artifacts.map((a) => a.runBranch).filter((b): b is string => b !== null && b.length > 0)
if (branches.length > 0) {
await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', ...branches], { env }).catch(() => {})
}
}
private async commitPendingChanges(
worktreePath: string,
env: Record<string, string>,
title: string,
body: string,
): Promise<string | null> {
const status = await executeCommand(['git', '-C', worktreePath, 'status', '--porcelain'], { env }).catch(() => '')
if (!status.trim()) return null
await executeCommand(['git', '-C', worktreePath, 'add', '-A'], { env })
await executeCommand(['git', '-C', worktreePath, 'commit', '-m', title, '-m', body], { env })
return (await executeCommand(['git', '-C', worktreePath, 'rev-parse', 'HEAD'], { env })).trim()
}
private async isUsableWorktree(worktreePath: string, env: Record<string, string>): Promise<boolean> {
if (!existsSync(path.join(worktreePath, '.git'))) return false
try {
await executeCommand(['git', '-C', worktreePath, 'rev-parse', '--is-inside-work-tree'], { env, silent: true })
return true
} catch {
return false
}
}
/**
* Resolves a user-supplied base branch name to a verified git ref, preferring
* the remote-tracking branch for freshness. Returns null when neither the
+81 -8
View File
@@ -1,3 +1,5 @@
import { existsSync } from 'node:fs'
import path from 'path'
import type { Database } from 'bun:sqlite'
import { Cron } from 'croner'
import {
@@ -5,6 +7,7 @@ import {
type ScheduleJob,
type ScheduleRun,
type ScheduleRunTriggerSource,
type ScheduleWorktree,
type UpdateScheduleJobRequest,
} from '@opencode-manager/shared/types'
import { mcpStatusByName, openCodeLocation } from '@opencode-manager/shared/opencode'
@@ -13,6 +16,7 @@ import { getRepoById } from '../db/queries'
import type { ScheduleJobWithRepo } from '../db/schedules'
import {
cleanupOrphanedSchedules,
clearScheduleRunWorktreePath,
createScheduleJob,
createScheduleRun,
deleteScheduleJob,
@@ -53,6 +57,7 @@ import type { Repo } from '../types/repo'
import { sseAggregator, type ScheduledSessionRef } from './sse-aggregator'
import { getErrorMessage } from '../utils/error-utils'
import { logger } from '../utils/logger'
import { canonicalPathSync } from '../utils/fs-safe'
import { buildAssistantRepo } from './assistant-mode'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
@@ -319,8 +324,72 @@ export class ScheduleService {
return listEnabledScheduleJobs(this.db)
}
listAllJobsWithRepos(): ScheduleJobWithRepo[] {
return listAllScheduleJobsWithRepos(this.db)
listAllJobsWithRepos(): Array<ScheduleJobWithRepo & { retainedWorktreeCount: number }> {
const runningPaths = this.listRunningWorktreePaths()
const counts = new Map<number, number>()
for (const entry of this.worktreeManager.listWorktrees()) {
if (runningPaths.has(entry.worktreePath)) continue
counts.set(entry.jobId, (counts.get(entry.jobId) ?? 0) + 1)
}
return listAllScheduleJobsWithRepos(this.db).map((job) => ({ ...job, retainedWorktreeCount: counts.get(job.id) ?? 0 }))
}
/**
* Lists the worktrees of a schedule that still exist on disk: kept run worktrees,
* the shared worktree, and the worktree of a run in progress.
*/
listWorktrees(repoId: number, jobId: number): ScheduleWorktree[] {
this.assertJob(repoId, jobId)
const runningPaths = this.listRunningWorktreePaths()
const jobRunning = ScheduleService.activeRuns.has(jobId) || getRunningScheduleRunByJob(this.db, repoId, jobId) !== null
return this.worktreeManager.listWorktrees(jobId)
.map((entry) => ({
worktreePath: entry.worktreePath,
branch: entry.branch,
runId: entry.runId,
inUse: runningPaths.has(entry.worktreePath) || (entry.runId === null && jobRunning),
}))
.sort((left, right) => (right.runId ?? Number.MAX_SAFE_INTEGER) - (left.runId ?? Number.MAX_SAFE_INTEGER))
}
/**
* Removes one of a schedule's worktrees, or every worktree not in use when no path is
* given. Pending changes are committed to each worktree's branch first and branches are
* kept, so a shared schedule continues from its branch on the next run.
*/
async removeWorktrees(repoId: number, jobId: number, worktreePath?: string): Promise<{ removed: number }> {
const repo = this.assertRepo(repoId)
const job = this.assertJob(repoId, jobId)
const worktrees = this.listWorktrees(repoId, jobId)
let targets = worktrees.filter((worktree) => !worktree.inUse)
if (worktreePath !== undefined) {
const requestedPath = canonicalPathSync(path.resolve(worktreePath))
const target = worktrees.find((worktree) => canonicalPathSync(worktree.worktreePath) === requestedPath)
if (!target) {
throw new ScheduleServiceError('Worktree not found for this schedule', 404)
}
if (target.inUse) {
throw new ScheduleServiceError('This worktree is in use by a running run. Cancel the run first.', 409)
}
targets = [target]
}
for (const target of targets) {
try {
await this.worktreeManager.releaseWorktree(repo, job, target.worktreePath)
} catch (error) {
throw new ScheduleServiceError(`Failed to remove worktree ${target.worktreePath}: ${getErrorMessage(error)}`, 500)
}
clearScheduleRunWorktreePath(this.db, repoId, jobId, target.worktreePath)
}
return { removed: targets.length }
}
private listRunningWorktreePaths(): Set<string> {
return new Set(listRunningScheduleRuns(this.db).flatMap((run) => (run.worktreePath ? [run.worktreePath] : [])))
}
listAllRuns(options: ListAllRunsOptions = {}): ScheduleRunWithContext[] {
@@ -406,7 +475,7 @@ export class ScheduleService {
return job
}
deleteJob(repoId: number, jobId: number): void {
async deleteJob(repoId: number, jobId: number): Promise<void> {
this.assertRepo(repoId)
this.assertJob(repoId, jobId)
@@ -419,6 +488,8 @@ export class ScheduleService {
throw new ScheduleServiceError('Cannot delete a schedule while it is running. Cancel the run first.', 409)
}
await this.removeWorktrees(repoId, jobId)
const deleted = deleteScheduleJob(this.db, repoId, jobId)
if (!deleted) {
throw new ScheduleServiceError('Schedule not found', 404)
@@ -483,7 +554,7 @@ export class ScheduleService {
return { cleared: 0 }
}
await this.worktreeManager.pruneRunArtifacts(repo, removable)
await this.worktreeManager.pruneRunArtifacts(repo, jobId, removable)
const cleared = deleteScheduleRunsByIds(this.db, repoId, jobId, removable.map((run) => run.id))
return { cleared }
}
@@ -501,7 +572,7 @@ export class ScheduleService {
throw new ScheduleServiceError('Cannot delete a run while it is in progress. Cancel it first.', 409)
}
await this.worktreeManager.pruneRunArtifacts(repo, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }])
await this.worktreeManager.pruneRunArtifacts(repo, jobId, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }])
const deleted = deleteScheduleRunById(this.db, repoId, jobId, runId)
if (!deleted) {
throw new ScheduleServiceError('Run not found', 404)
@@ -1109,17 +1180,19 @@ export class ScheduleService {
try {
const fresh = getScheduleRunById(this.db, repoId, jobId, runId)
if (!fresh?.worktreePath) return
const worktreePath = fresh.worktreePath
const remainingWorktreePath = () => (existsSync(worktreePath) ? worktreePath : null)
try {
const { commitHash } = await this.worktreeManager.finalize(repo, job, {
id: runId,
worktreePath: fresh.worktreePath,
worktreePath,
runBranch: fresh.runBranch,
triggerSource: fresh.triggerSource,
})
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null, commitHash })
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: remainingWorktreePath(), commitHash })
} catch (error) {
logger.error(`Failed to finalize worktree for run ${runId}:`, error)
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null })
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: remainingWorktreePath() })
}
} finally {
ScheduleService.activeTeardowns.delete(key)
+94 -24
View File
@@ -1,26 +1,82 @@
import { Database } from 'bun:sqlite'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { migrate, type Migration } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { logger } from '../../src/utils/logger'
function makeMigration(version: number, name: string, up: () => void): Migration {
return { version, name, up, down: () => {} }
function makeMigration(id: string, up: () => void = vi.fn(), legacy?: Migration['legacy']): Migration {
return { id, legacy, up, down: () => {} }
}
describe('migrate - version/name mismatch guard', () => {
function createLegacyTable(db: Database, rows: Array<[number, string]>): void {
db.run('CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL)')
rows.forEach(([version, name]) => {
db.prepare('INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, 0)').run(version, name)
})
}
function appliedIds(db: Database): string[] {
return (db.prepare('SELECT id FROM applied_migrations ORDER BY id').all() as Array<{ id: string }>).map((row) => row.id)
}
describe('migrate', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('warns and skips when an applied version was recorded under a different name', () => {
it('applies pending migrations in list order and records them by id', () => {
const db = new Database(':memory:')
db.run('CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL)')
db.run("INSERT INTO schema_migrations (version, name, applied_at) VALUES (15, 'repos-add-name', 0)")
const order: string[] = []
migrate(db, [
makeMigration('202610061345-second', () => order.push('second')),
makeMigration('202610051200-first', () => order.push('first')),
])
expect(order).toEqual(['second', 'first'])
expect(appliedIds(db)).toEqual(['202610051200-first', '202610061345-second'])
})
it('does not run a migration twice', () => {
const db = new Database(':memory:')
const up = vi.fn()
migrate(db, [makeMigration('202610061345-once', up)])
migrate(db, [makeMigration('202610061345-once', up)])
expect(up).toHaveBeenCalledTimes(1)
})
it('runs a migration whose old version number another branch already used', () => {
const db = new Database(':memory:')
createLegacyTable(db, [[28, 'remote-devices']])
const up = vi.fn()
migrate(db, [makeMigration('202610061345-schedule-workspace-mode', up)])
expect(up).toHaveBeenCalledTimes(1)
})
it('adopts numbered migrations recorded in the old version-keyed table', () => {
const db = new Database(':memory:')
createLegacyTable(db, [[15, 'schedule-worktree-isolation']])
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
const up = vi.fn()
migrate(db, [makeMigration(15, 'schedule-worktree-isolation', up)])
migrate(db, [makeMigration('015-schedule-worktree-isolation', up, { version: 15, name: 'schedule-worktree-isolation' })])
expect(up).not.toHaveBeenCalled()
expect(appliedIds(db)).toEqual(['015-schedule-worktree-isolation'])
expect(warnSpy).not.toHaveBeenCalled()
})
it('warns and skips when a legacy version was recorded under a different name', () => {
const db = new Database(':memory:')
createLegacyTable(db, [[15, 'repos-add-name']])
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
const up = vi.fn()
migrate(db, [makeMigration('015-schedule-worktree-isolation', up, { version: 15, name: 'schedule-worktree-isolation' })])
expect(up).not.toHaveBeenCalled()
expect(warnSpy).toHaveBeenCalledWith(
@@ -28,26 +84,40 @@ describe('migrate - version/name mismatch guard', () => {
)
})
it('does not warn when recorded names match', () => {
const db = new Database(':memory:')
db.run('CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL)')
db.run("INSERT INTO schema_migrations (version, name, applied_at) VALUES (15, 'schedule-worktree-isolation', 0)")
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
migrate(db, [makeMigration(15, 'schedule-worktree-isolation', vi.fn())])
expect(warnSpy).not.toHaveBeenCalled()
})
it('applies pending migrations and records them', () => {
it('rejects duplicate ids before touching the database', () => {
const db = new Database(':memory:')
const up = vi.fn()
migrate(db, [makeMigration(1, 'base', up)])
expect(() => migrate(db, [makeMigration('202610061345-a', up), makeMigration('202610061345-a', up)])).toThrow('Duplicate migration id')
expect(up).not.toHaveBeenCalled()
})
expect(up).toHaveBeenCalledTimes(1)
const row = db.prepare('SELECT version, name FROM schema_migrations WHERE version = 1').get() as { version: number; name: string }
expect(row).toEqual({ version: 1, name: 'base' })
it('rolls back and stops when a migration fails', () => {
const db = new Database(':memory:')
vi.spyOn(logger, 'error').mockImplementation(() => {})
const later = vi.fn()
expect(() => migrate(db, [
makeMigration('202610061345-broken', () => {
db.run('CREATE TABLE partial (id INTEGER)')
throw new Error('boom')
}),
makeMigration('202610061346-later', later),
])).toThrow('boom')
expect(later).not.toHaveBeenCalled()
expect(appliedIds(db)).toEqual([])
expect(db.prepare("SELECT name FROM sqlite_master WHERE name = 'partial'").get()).toBeFalsy()
})
})
describe('allMigrations', () => {
it('uses timestamp ids for every migration added after the numbered ones', () => {
const unnumbered = allMigrations.filter((migration) => !migration.legacy)
expect(unnumbered.length).toBeGreaterThan(0)
unnumbered.forEach((migration) => {
expect(migration.id).toMatch(/^\d{12}-[a-z0-9]+(?:-[a-z0-9]+)*$/)
})
})
})
@@ -22,7 +22,7 @@ const originalHome = process.env.HOME
const originalImportConfigPath = process.env.OPENCODE_IMPORT_CONFIG_PATH
function migrateToV18(db: Database): void {
migrate(db, allMigrations.filter(migration => migration.version < 19))
migrate(db, allMigrations.filter(migration => (migration.legacy?.version ?? Infinity) < 19))
}
function insertConfig(db: Database, name: string, content: string, isDefault: boolean): void {
@@ -23,7 +23,7 @@ interface ModelStateRow {
}
function migrateToV19(db: Database): void {
migrate(db, allMigrations.filter(migration => migration.version < 20))
migrate(db, allMigrations.filter(migration => (migration.legacy?.version ?? Infinity) < 20))
}
function insertRow(db: Database, state: ModelStateRow, updatedAt: number): void {
@@ -35,6 +35,7 @@ describe('schedule permission config persistence', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: Date.now() + 3600000,
...overrides,
})
+8 -11
View File
@@ -116,6 +116,7 @@ describe('schedule database queries', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
})
@@ -135,6 +136,7 @@ describe('schedule database queries', () => {
null,
null,
null,
'worktree',
expect.any(Number),
expect.any(Number),
null,
@@ -174,6 +176,7 @@ describe('schedule database queries', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: null,
})
@@ -192,6 +195,7 @@ describe('schedule database queries', () => {
null,
null,
null,
'worktree',
expect.any(Number),
null,
42,
@@ -668,19 +672,12 @@ describe('schedule database queries', () => {
])
})
it('listActiveScheduleRunWorktreePaths returns only non-null worktree paths', () => {
const stmt = {
all: vi.fn().mockReturnValue([
{ worktree_path: '/wt/2' },
{ worktree_path: '/wt/9' },
]),
}
it('getScheduleJobRepoId returns the owning repo or null for an unknown job', () => {
const stmt = { get: vi.fn().mockReturnValueOnce({ repo_id: 42 }).mockReturnValueOnce(undefined) }
mockDb.prepare.mockReturnValue(stmt)
const paths = schedulesDb.listActiveScheduleRunWorktreePaths(mockDb)
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT worktree_path FROM schedule_runs WHERE worktree_path IS NOT NULL')
expect(paths).toEqual(['/wt/2', '/wt/9'])
expect(schedulesDb.getScheduleJobRepoId(mockDb, 7)).toBe(42)
expect(schedulesDb.getScheduleJobRepoId(mockDb, 8)).toBeNull()
})
it('deleteScheduleRunById deletes a single run row', () => {
+3 -3
View File
@@ -21,9 +21,9 @@ describe('initializeDatabase', () => {
it('creates the database file, applies migrations, and seeds defaults', async () => {
const db = initializeDatabase(dbPath)
const migrations = db.prepare('SELECT name FROM schema_migrations ORDER BY version ASC').all() as Array<{ name: string }>
expect(migrations.map(migration => migration.name)).toContain('base-schema')
expect(migrations.map(migration => migration.name)).toContain('drop-opencode-configs')
const migrations = db.prepare('SELECT id AS name FROM applied_migrations').all() as Array<{ name: string }>
expect(migrations.map(migration => migration.name)).toContain('001-base-schema')
expect(migrations.map(migration => migration.name)).toContain('019-drop-opencode-configs')
const preferences = db.prepare('SELECT preferences FROM user_preferences WHERE user_id = ?').get('default') as { preferences: string }
expect(preferences.preferences).toBe('{}')
@@ -26,7 +26,7 @@ describe('internal-schedules routes', () => {
db = new Database(':memory:')
migrate(db, allMigrations)
const openCodeClient = createOpenCodeClient()
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }) } as unknown as ScheduleWorktreeManager
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }), listWorktrees: () => [] } as unknown as ScheduleWorktreeManager
scheduleService = new ScheduleService(db, openCodeClient, stubWorktreeManager)
notificationService = new NotificationService(db)
settingsService = new SettingsService(db)
+35 -2
View File
@@ -110,7 +110,7 @@ const mockTerminalService = {
function createTestRoutes(openCodeClient: ReturnType<typeof createStubOpenCodeClient> = createStubOpenCodeClient()): ReturnType<typeof createRepoRoutes> {
const projectConfigService = new ProjectConfigService(mockDb, createGitService(mockGitAuthService), mockGitAuthService)
const repoWorkspaces = new RepoWorkspaceService(mockDb, openCodeClient, mockGitAuthService, projectConfigService, mockTerminalService)
const repoWorkspaces = new RepoWorkspaceService(mockDb, openCodeClient, mockGitAuthService, projectConfigService, mockTerminalService, mockScheduleService)
return createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, openCodeClient, mockTerminalService, projectConfigService, repoWorkspaces)
}
@@ -505,6 +505,39 @@ describe('Repo Routes', () => {
expect(await res.json()).toEqual({ directory: '/tmp/wrk-test', worktreeSetup: { status: 'none' } })
})
it('passes a requested worktree name to OpenCode', async () => {
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' }))
const client = createStubOpenCodeClient()
const create = vi.fn(async () => ({ directory: '/tmp/feature-login' }))
client.api.worktree.create = create as never
const res = await createTestRoutes(client).request('/1/workspaces', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: ' feature-login ' }),
})
expect(res.status).toBe(200)
expect(create).toHaveBeenCalledWith(expect.objectContaining({ name: 'feature-login' }))
})
it('rejects a worktree name that is not a single folder name', async () => {
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' }))
const client = createStubOpenCodeClient()
const create = vi.fn(async () => ({ directory: '/tmp/x' }))
client.api.worktree.create = create as never
const res = await createTestRoutes(client).request('/1/workspaces', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: '../escape' }),
})
expect(res.status).toBe(400)
expect(await res.json()).toEqual({ error: 'Directory name cannot contain dot-dot path segments' })
expect(create).not.toHaveBeenCalled()
})
it('returns 200 with a failed worktree setup when the setup terminal cannot start', async () => {
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' }))
vi.mocked(db.getRepoSetting).mockImplementation((_database, _repoId, key) =>
@@ -880,7 +913,7 @@ describe('Repo Routes', () => {
vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined)
vi.mocked(repoService.getSiblingRepos).mockResolvedValue([
{ ...createMockRepo({ id: 2, fullPath: '/tmp/repos/manager-worktree', isWorktree: true }), currentBranch: undefined },
{ ...createMockRepo({ id: -1, fullPath: '/tmp/plugin-workspace' }), currentBranch: undefined, worktreeStrategy: 'git' },
{ ...createMockRepo({ id: -1, fullPath: '/tmp/plugin-workspace' }), currentBranch: undefined, worktreeStrategy: 'git', worktreeSource: 'opencode' },
])
const app = createTestRoutes()
+1 -1
View File
@@ -683,7 +683,7 @@ describe('assistant-mode end-to-end', () => {
const token = getOrCreateInternalToken(db)
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }) } as unknown as ScheduleWorktreeManager
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }), listWorktrees: () => [] } as unknown as ScheduleWorktreeManager
const scheduleService = new ScheduleService(db, createOpenCodeClient(), stubWorktreeManager)
const notificationService = new NotificationService(db)
const settingsService = new SettingsService(db)
@@ -43,6 +43,7 @@ function scheduleJobInput(name: string, branch: string): ScheduleJobPersistenceI
skillMetadata: null,
permissionConfig: null,
mcpServers: [],
workspaceMode: 'worktree',
branch,
nextRunAt: null,
}
+34 -20
View File
@@ -1,5 +1,5 @@
import { execFileSync } from 'node:child_process'
import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { createServer } from 'node:https'
import { tmpdir } from 'node:os'
import path from 'node:path'
@@ -16,7 +16,6 @@ import type { GitAuthService } from '../../src/services/git-auth'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import type { Repo } from '../../src/types/repo'
type SiblingRepo = Repo & { currentBranch: string | undefined; worktreeStrategy?: string }
const workspaceRoot = mkdtempSync(path.join(tmpdir(), 'repo-git-'))
process.env.WORKSPACE_PATH = workspaceRoot
@@ -923,7 +922,7 @@ describe('repo service real git', () => {
expect(siblings.every((repo) => repo.currentBranch === 'main')).toBe(true)
})
it('adds filtered workspace siblings from the OpenCode client', async () => {
it('lists OpenCode, schedule, and plain git worktrees as worktree siblings', async () => {
const { getSiblingRepos } = await import('../../src/services/repo')
const origin = path.join(workspaceRoot, uniqueName('sibling-ws-origin.git'))
const work = path.join(workspaceRoot, uniqueName('sibling-ws-work'))
@@ -953,15 +952,27 @@ describe('repo service real git', () => {
const projectId = (await resolveOpenCodeProjectId(repoA))!
const extraDir = path.join(workspaceRoot, uniqueName('sibling-ws-extra'))
const duplicateDir = path.join(workspaceRoot, uniqueName('sibling-ws-duplicate'))
const activeWorktree = path.join(workspaceRoot, uniqueName('sibling-ws-active'))
const activeWorkspace = path.join(workspaceRoot, uniqueName('sibling-ws-active-dir'))
const unownedDir = path.join(workspaceRoot, uniqueName('sibling-ws-unowned'))
mkdirSync(extraDir, { recursive: true })
mkdirSync(duplicateDir, { recursive: true })
mkdirSync(activeWorktree, { recursive: true })
mkdirSync(activeWorkspace, { recursive: true })
const scheduleDir = path.join(getScheduleWorktreesPath(), uniqueName('sibling-ws-schedule'))
db.prepare('INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at, worktree_path) VALUES (?, ?, ?, ?, ?, ?, ?)').run(1, a.id, 'manual', 'running', Date.now(), Date.now(), activeWorktree)
db.prepare('INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at, worktree_path) VALUES (?, ?, ?, ?, ?, ?, ?)').run(1, a.id, 'manual', 'running', Date.now(), Date.now(), activeWorkspace)
mkdirSync(unownedDir, { recursive: true })
const jobId = Number(db.prepare('INSERT INTO schedule_jobs (repo_id, name, prompt, created_at, updated_at) VALUES (?, ?, ?, ?, ?)').run(a.id, 'nightly', 'check', Date.now(), Date.now()).lastInsertRowid)
const keptDir = path.join(getScheduleWorktreesPath(), `job-${jobId}-run-3`)
const sharedDir = path.join(getScheduleWorktreesPath(), `job-${jobId}-shared`)
const orphanDir = path.join(getScheduleWorktreesPath(), 'job-999999-run-1')
const manualDir = path.join(workspaceRoot, uniqueName('sibling-ws-manual'))
mkdirSync(getScheduleWorktreesPath(), { recursive: true })
git(['worktree', 'add', '-b', `schedule/${jobId}/run-3`, keptDir], repoA)
git(['worktree', 'add', '-b', `schedule/${jobId}/shared`, sharedDir], repoA)
git(['worktree', 'add', '-b', 'schedule/999999/run-1', orphanDir], repoA)
git(['worktree', 'add', '-b', 'manual-work', manualDir], repoA)
db.prepare('INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at, worktree_path) VALUES (?, ?, ?, ?, ?, ?, ?)').run(jobId, a.id, 'manual', 'running', Date.now(), Date.now(), sharedDir)
const keptPath = realpathSync(keptDir)
const sharedPath = realpathSync(sharedDir)
const orphanPath = realpathSync(orphanDir)
const manualPath = realpathSync(manualDir)
const client = {
api: {
location: {
@@ -974,22 +985,25 @@ describe('repo service real git', () => {
{ directory: duplicateDir, strategy: 'git' },
{ directory: repoA, strategy: 'git' },
{ directory: getReposPath(), strategy: 'git' },
{ directory: scheduleDir, strategy: 'git' },
{ directory: activeWorktree, strategy: 'git' },
{ directory: activeWorkspace, strategy: 'git' },
{ directory: unownedDir },
],
},
},
} as unknown as OpenCodeClient
const siblings = await getSiblingRepos(db, a.id, {}, client) as SiblingRepo[]
const siblings = await getSiblingRepos(db, a.id, {}, client)
const worktreeSiblings = siblings.filter((repo) => isWorktreeSibling(repo))
const findSibling = (directory: string) => worktreeSiblings.find((repo) => repo.fullPath === directory)
expect(worktreeSiblings.map((repo) => repo.fullPath)).toEqual([extraDir, duplicateDir])
expect(worktreeSiblings.every((repo) => repo.id === -1)).toBe(true)
expect(worktreeSiblings.every((repo) => repo.localPath === path.basename(repo.fullPath))).toBe(true)
expect(worktreeSiblings.every((repo) => repo.worktreeStrategy === 'git')).toBe(true)
expect(worktreeSiblings.every((repo) => repo.branch === undefined && repo.currentBranch === undefined)).toBe(true)
expect(worktreeSiblings.map((repo) => repo.fullPath).sort()).toEqual([extraDir, duplicateDir, keptPath, sharedPath, orphanPath, manualPath].sort())
expect(siblings.some((repo) => repo.fullPath === unownedDir && repo.worktreeSource === undefined)).toBe(true)
expect(worktreeSiblings.every((repo) => repo.id === -1 && repo.localPath === path.basename(repo.fullPath))).toBe(true)
expect(findSibling(extraDir)).toMatchObject({ worktreeSource: 'opencode', worktreeStrategy: 'git', branch: undefined })
expect(findSibling(keptPath)).toMatchObject({ worktreeSource: 'schedule', branch: `schedule/${jobId}/run-3`, schedule: { repoId: a.id, jobId, runId: 3, inUse: false } })
expect(findSibling(sharedPath)).toMatchObject({ worktreeSource: 'schedule', schedule: { repoId: a.id, jobId, runId: null, inUse: true } })
expect(findSibling(orphanPath)).toMatchObject({ worktreeSource: 'git', branch: 'schedule/999999/run-1' })
expect(findSibling(orphanPath)?.schedule).toBeUndefined()
expect(findSibling(manualPath)).toMatchObject({ worktreeSource: 'git', currentBranch: 'manual-work' })
})
it('returns repo siblings when the OpenCode client fails', async () => {
@@ -1021,7 +1035,7 @@ describe('repo service real git', () => {
},
} as unknown as OpenCodeClient
const siblings = await getSiblingRepos(db, a.id, {}, client) as SiblingRepo[]
const siblings = await getSiblingRepos(db, a.id, {}, client)
expect(siblings.some((repo) => repo.id === a.id)).toBe(true)
expect(siblings.some((repo) => isWorktreeSibling(repo))).toBe(false)
@@ -145,7 +145,7 @@ describe('getSiblingRepos branch resolution', () => {
expect(siblings).toHaveLength(1)
expect(siblings[0]?.currentBranch).toBeUndefined()
expect(executeCommand).not.toHaveBeenCalled()
expect(executeCommand.mock.calls.map(([args]) => args)).toEqual([['git', '-C', repo.fullPath, 'worktree', 'list', '--porcelain']])
})
it('resolves the branch when includeBranch is true', async () => {
+48 -5
View File
@@ -69,6 +69,7 @@ function createService(overrides: {
} as unknown as OpenCodeClient
const projectConfigService = { runWorktreeSetupForRepo } as unknown as ProjectConfigService
const terminalService = { removeAll } as unknown as TerminalService
const removeScheduleWorktrees = vi.fn(async () => ({ removed: 1 }))
return {
service: new RepoWorkspaceService(
@@ -77,7 +78,9 @@ function createService(overrides: {
gitAuthService,
projectConfigService,
terminalService,
{ removeWorktrees: removeScheduleWorktrees },
),
removeScheduleWorktrees,
worktreeCreate,
worktreeRemove,
runWorktreeSetupForRepo,
@@ -128,7 +131,7 @@ describe('RepoWorkspaceService', () => {
it('throws a 400 when the directory is not a worktree sibling and touches nothing', async () => {
const worktreeRemove = vi.fn(async () => undefined)
const removeAll = vi.fn(async () => undefined)
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/other', worktreeStrategy: 'git' }])
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/other', worktreeStrategy: 'git', worktreeSource: 'opencode' }])
const { service } = createService({ worktreeRemove, removeAll })
const error = await service.remove(REPO, '/worktrees/unknown').catch((caught: unknown) => caught)
@@ -142,7 +145,7 @@ describe('RepoWorkspaceService', () => {
it('removes terminals for the matched sibling before removing the worktree', async () => {
const worktreeRemove = vi.fn(async () => undefined)
const removeAll = vi.fn(async () => undefined)
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/feature-x', worktreeStrategy: 'git' }])
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/feature-x', worktreeStrategy: 'git', worktreeSource: 'opencode' }])
const { service } = createService({ worktreeRemove, removeAll })
await service.remove(REPO, '/worktrees/feature-x')
@@ -161,7 +164,7 @@ describe('RepoWorkspaceService', () => {
const removeAll = vi.fn(async () => {
throw new Error('pty cleanup failed')
})
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/feature-x', worktreeStrategy: 'git' }])
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/feature-x', worktreeStrategy: 'git', worktreeSource: 'opencode' }])
const { service } = createService({ worktreeRemove, removeAll })
await expect(service.remove(REPO, '/worktrees/feature-x')).resolves.toBeUndefined()
@@ -173,14 +176,54 @@ describe('RepoWorkspaceService', () => {
force: true,
})
})
it('removes a schedule worktree through its schedule instead of OpenCode', async () => {
const worktreeRemove = vi.fn(async () => undefined)
mocks.getSiblingRepos.mockResolvedValue([{
fullPath: '/schedule-worktrees/job-7-shared',
worktreeSource: 'schedule',
schedule: { repoId: 3, jobId: 7, runId: null, inUse: false },
}])
const { service, removeScheduleWorktrees } = createService({ worktreeRemove })
await service.remove(REPO, '/schedule-worktrees/job-7-shared')
expect(removeScheduleWorktrees).toHaveBeenCalledWith(3, 7, '/schedule-worktrees/job-7-shared')
expect(worktreeRemove).not.toHaveBeenCalled()
})
it('refuses to remove a schedule worktree a running run is using', async () => {
const removeAll = vi.fn(async () => undefined)
mocks.getSiblingRepos.mockResolvedValue([{
fullPath: '/schedule-worktrees/job-7-run-2',
worktreeSource: 'schedule',
schedule: { repoId: 1, jobId: 7, runId: 2, inUse: true },
}])
const { service, removeScheduleWorktrees } = createService({ removeAll })
await expect(service.remove(REPO, '/schedule-worktrees/job-7-run-2')).rejects.toThrow('in use by a running scheduled run')
expect(removeAll).not.toHaveBeenCalled()
expect(removeScheduleWorktrees).not.toHaveBeenCalled()
})
it('reports a plain git worktree that git refuses to remove', async () => {
const worktreeRemove = vi.fn(async () => undefined)
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/manual', worktreeSource: 'git' }])
const { service } = createService({ worktreeRemove })
const error = await service.remove(REPO, '/worktrees/manual').catch((caught: unknown) => caught)
expect(error).toBeInstanceOf(RepoWorkspaceError)
expect((error as Error).message).toMatch(/^Could not remove worktree/)
expect(worktreeRemove).not.toHaveBeenCalled()
})
})
describe('removeRepoTerminals', () => {
it('removes terminals for the repo directory and each worktree sibling', async () => {
const removeAll = vi.fn(async () => undefined)
mocks.getSiblingRepos.mockResolvedValue([
{ fullPath: '/worktrees/a', worktreeStrategy: 'git' },
{ fullPath: '/worktrees/b', worktreeStrategy: 'git' },
{ fullPath: '/worktrees/a', worktreeStrategy: 'git', worktreeSource: 'opencode' },
{ fullPath: '/worktrees/b', worktreeStrategy: 'git', worktreeSource: 'opencode' },
{ fullPath: '/repos/manager-worktree', isWorktree: true },
])
const { service } = createService({ removeAll })
+34 -8
View File
@@ -1,10 +1,11 @@
import path from 'path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Database } from 'bun:sqlite'
import { getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
import { getReposPath } from '@opencode-manager/shared/config/env'
import type { GitAuthService } from '../../src/services/git-auth'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import type { Repo } from '../../src/types/repo'
import type { RepoSibling } from '../../src/services/repo'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
@@ -30,6 +31,18 @@ const symlink = vi.fn()
const readlink = vi.fn()
const mkdirSafe = vi.fn()
const missingDirectories = new Set<string>()
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>()
return {
...actual,
existsSync: (target: string) => (
target.startsWith('/worktrees/') ? !missingDirectories.has(target) : actual.existsSync(target)
),
}
})
vi.mock('fs/promises', () => ({
default: {
lstat,
@@ -447,7 +460,7 @@ describe('repo service', () => {
})
describe('getSiblingRepos worktree API', () => {
type SiblingRepo = Repo & { currentBranch: string | undefined; worktreeStrategy?: string }
type SiblingRepo = RepoSibling
let db: Database
@@ -496,6 +509,20 @@ describe('getSiblingRepos worktree API', () => {
afterEach(() => {
db.close()
missingDirectories.clear()
})
it('skips worktrees OpenCode still records but that no longer exist on disk', async () => {
const { getSiblingRepos } = await import('../../src/services/repo')
missingDirectories.add('/worktrees/removed-run')
const client = createClient([
{ directory: '/worktrees/removed-run', strategy: 'git' },
{ directory: '/worktrees/feature-x', strategy: 'git' },
])
const siblings = await getSiblingRepos(db, 1, {}, client)
expect(siblings.filter((sibling) => sibling.id === -1).map((sibling) => sibling.fullPath)).toEqual(['/worktrees/feature-x'])
})
it('maps worktree entries to worktree siblings', async () => {
@@ -515,17 +542,15 @@ describe('getSiblingRepos worktree API', () => {
expect(siblings[1]?.currentBranch).toBeUndefined()
})
it('excludes the target repo, repos root, schedule root, known siblings, and main checkouts', async () => {
it('excludes the target repo, repos root, known siblings, and main checkouts', async () => {
const { getSiblingRepos } = await import('../../src/services/repo')
const repoA = path.join(getReposPath(), 'repo-a')
const repoB = path.join(getReposPath(), 'repo-b')
const scheduleDir = path.join(getScheduleWorktreesPath(), 'run-1')
listRepos.mockReturnValue([createRepoRow(1, 'repo-a'), createRepoRow(2, 'repo-b')])
isGitMainCheckout.mockImplementation(async (directory: string) => directory === '/worktrees/main-checkout')
const client = createClient([
{ directory: repoA, strategy: 'git' },
{ directory: getReposPath(), strategy: 'git' },
{ directory: scheduleDir, strategy: 'git' },
{ directory: repoB, strategy: 'git' },
{ directory: '/worktrees/main-checkout', strategy: 'git' },
{ directory: '/worktrees/feature-x', strategy: 'git' },
@@ -537,7 +562,7 @@ describe('getSiblingRepos worktree API', () => {
expect(siblings.filter((sibling) => sibling.id === -1).map((sibling) => sibling.fullPath)).toEqual(['/worktrees/feature-x'])
})
it('excludes an active schedule run worktree path', async () => {
it('marks an active schedule run worktree as an in-use schedule worktree', async () => {
const { getSiblingRepos } = await import('../../src/services/repo')
const activePath = '/worktrees/active-run'
db.prepare('INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at, worktree_path) VALUES (?, ?, ?, ?, ?, ?, ?)').run(1, 1, 'manual', 'running', Date.now(), Date.now(), activePath)
@@ -548,8 +573,9 @@ describe('getSiblingRepos worktree API', () => {
const siblings = await getSiblingRepos(db, 1, {}, client) as SiblingRepo[]
expect(siblings).toHaveLength(2)
expect(siblings[1]?.fullPath).toBe('/worktrees/feature-x')
expect(siblings).toHaveLength(3)
expect(siblings[1]).toMatchObject({ fullPath: activePath, worktreeSource: 'schedule', schedule: { repoId: 1, jobId: 1, runId: 1, inUse: true } })
expect(siblings[2]).toMatchObject({ fullPath: '/worktrees/feature-x', worktreeSource: 'opencode' })
})
it('returns only repo siblings when the location lookup rejects', async () => {
@@ -36,6 +36,7 @@ describe('schedule-config', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: currentDate + 60 * 60_000,
})
})
@@ -76,6 +77,7 @@ describe('schedule-config', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
@@ -108,6 +110,7 @@ describe('schedule-config', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
@@ -143,6 +146,7 @@ describe('schedule-config', () => {
permissionConfig: null,
mcpServers: [],
branch: 'feature/foo',
workspaceMode: 'worktree',
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: null,
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
@@ -174,6 +178,7 @@ describe('schedule-config', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: null,
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
@@ -205,6 +210,7 @@ describe('schedule-config', () => {
permissionConfig: null,
mcpServers: [],
branch: 'feature/foo',
workspaceMode: 'worktree',
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: null,
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
@@ -236,6 +242,7 @@ describe('schedule-config', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: null,
lastRunAt: null,
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
@@ -280,6 +287,7 @@ describe('schedule-config', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: null,
lastRunAt: null,
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
+71 -12
View File
@@ -118,7 +118,7 @@ describe('ScheduleWorktreeManager', () => {
it('prepare creates a worktree with the correct branch name and returns context', async () => {
const manager = await createManager()
const repo = testRepo()
const job = { id: 10, branch: null }
const job = { id: 10, branch: null, workspaceMode: 'worktree' as const }
const runId = 1
const ctx = await manager.prepare(repo, job, runId)
@@ -144,7 +144,7 @@ describe('ScheduleWorktreeManager', () => {
it('prepare returns null for a non-git directory', async () => {
const manager = await createManager()
const repo = testRepo({ fullPath: nonGitDir })
const job = { id: 12, branch: null }
const job = { id: 12, branch: null, workspaceMode: 'worktree' as const }
const ctx = await manager.prepare(repo, job, 1)
expect(ctx).toBeNull()
@@ -153,7 +153,7 @@ describe('ScheduleWorktreeManager', () => {
it('prepare returns null for the assistant repo', async () => {
const manager = await createManager()
const repo = testRepo({ id: 0 })
const job = { id: 13, branch: null }
const job = { id: 13, branch: null, workspaceMode: 'worktree' as const }
const ctx = await manager.prepare(repo, job, 1)
expect(ctx).toBeNull()
@@ -162,7 +162,7 @@ describe('ScheduleWorktreeManager', () => {
it('finalize returns null commit when no changes exist and removes the worktree', async () => {
const manager = await createManager()
const repo = testRepo()
const job = { id: 10, branch: null, name: 'No-change job' }
const job = { id: 10, branch: null, name: 'No-change job', workspaceMode: 'worktree' as const }
const runId = 100
// Prepare a worktree first
@@ -174,7 +174,7 @@ describe('ScheduleWorktreeManager', () => {
// Finalize without making any changes
const result = await manager.finalize(
repo,
{ id: 10, name: 'No-change job', prompt: '' },
{ id: 10, name: 'No-change job', prompt: '', workspaceMode: 'worktree' as const },
{ id: runId, worktreePath, runBranch: ctx!.runBranch, triggerSource: 'manual' },
)
@@ -186,7 +186,7 @@ describe('ScheduleWorktreeManager', () => {
it('finalize commits changes and returns the commit hash, then removes the worktree', async () => {
const manager = await createManager()
const repo = testRepo()
const job = { id: 10, branch: null, name: 'Change job' }
const job = { id: 10, branch: null, name: 'Change job', workspaceMode: 'worktree' as const }
const runId = 200
// Prepare a worktree
@@ -201,7 +201,7 @@ describe('ScheduleWorktreeManager', () => {
// Finalize - should commit and clean up
const result = await manager.finalize(
repo,
{ id: 10, name: 'Change job', prompt: 'Generate a changelog' },
{ id: 10, name: 'Change job', prompt: 'Generate a changelog', workspaceMode: 'worktree' as const },
{ id: runId, worktreePath, runBranch: ctx!.runBranch, triggerSource: 'schedule' },
)
@@ -226,7 +226,7 @@ describe('ScheduleWorktreeManager', () => {
const result = await manager.finalize(
repo,
{ id: 10, name: 'Job', prompt: '' },
{ id: 10, name: 'Job', prompt: '', workspaceMode: 'worktree' as const },
{ id: 1, worktreePath: null, runBranch: null, triggerSource: 'manual' },
)
@@ -238,7 +238,7 @@ describe('ScheduleWorktreeManager', () => {
const repo = testRepo()
// A clearly nonexistent ref (avoids case-insensitive filesystem false matches
// that would let a typo like "Main" resolve to "main" locally).
const job = { id: 21, branch: 'does-not-exist-branch' }
const job = { id: 21, branch: 'does-not-exist-branch', workspaceMode: 'worktree' as const }
await expect(manager.prepare(repo, job, 1)).rejects.toThrow(
/Base branch "does-not-exist-branch" was not found/,
@@ -251,7 +251,7 @@ describe('ScheduleWorktreeManager', () => {
it('prepare respects the branch override', async () => {
const manager = await createManager()
const repo = testRepo()
const job = { id: 20, branch: 'dev' }
const job = { id: 20, branch: 'dev', workspaceMode: 'worktree' as const }
const runId = 1
const ctx = await manager.prepare(repo, job, runId)
@@ -277,7 +277,7 @@ describe('ScheduleWorktreeManager', () => {
it('pruneRunArtifacts removes the worktree directory and deletes the run branch', async () => {
const manager = await createManager()
const repo = testRepo()
const job = { id: 90, branch: null }
const job = { id: 90, branch: null, workspaceMode: 'worktree' as const }
const runId = 900
const ctx = await manager.prepare(repo, job, runId)
@@ -287,7 +287,7 @@ describe('ScheduleWorktreeManager', () => {
const runBranch = ctx!.runBranch
expect(existsSync(worktreePath)).toBe(true)
await manager.pruneRunArtifacts(repo, [{ runBranch, worktreePath }])
await manager.pruneRunArtifacts(repo, 90, [{ runBranch, worktreePath }])
expect(existsSync(worktreePath)).toBe(false)
const branchList = execSync(`git -C "${baseRepoPath}" branch --list "${runBranch}"`, {
@@ -295,4 +295,63 @@ describe('ScheduleWorktreeManager', () => {
}).trim()
expect(branchList).toBe('')
})
it('prepare returns null in repo mode so the run works in the checkout', async () => {
const manager = await createManager()
const ctx = await manager.prepare(testRepo(), { id: 30, branch: null, workspaceMode: 'repo' }, 1)
expect(ctx).toBeNull()
expect(manager.listWorktrees(30)).toEqual([])
})
it('finalize commits but keeps the worktree on its branch in kept-worktree mode', async () => {
const manager = await createManager()
const repo = testRepo()
const job = { id: 31, branch: null, name: 'Kept job', prompt: 'keep', workspaceMode: 'kept-worktree' as const }
const ctx = await manager.prepare(repo, job, 1)
writeFileSync(path.join(ctx!.worktreePath, 'kept.md'), 'kept')
const result = await manager.finalize(repo, job, { id: 1, worktreePath: ctx!.worktreePath, runBranch: ctx!.runBranch, triggerSource: 'manual' })
expect(result.commitHash).toMatch(/^[0-9a-f]{40}$/)
expect(existsSync(ctx!.worktreePath)).toBe(true)
expect(execSync(`git -C "${ctx!.worktreePath}" rev-parse --abbrev-ref HEAD`, { encoding: 'utf-8' }).trim()).toBe('schedule/31/run-1')
expect(manager.listWorktrees(31)).toEqual([
{ jobId: 31, runId: 1, worktreePath: ctx!.worktreePath, branch: 'schedule/31/run-1' },
])
await manager.releaseWorktree(repo, job, ctx!.worktreePath)
})
it('reuses one shared worktree across runs and continues its branch after release', async () => {
const manager = await createManager()
const repo = testRepo()
const job = { id: 32, branch: null, name: 'Shared job', prompt: 'share', workspaceMode: 'shared-worktree' as const }
const sharedPath = path.join(scheduleWorktreesRoot, 'job-32-shared')
const first = await manager.prepare(repo, job, 1)
expect(first).toEqual({ directory: sharedPath, worktreePath: sharedPath, runBranch: 'schedule/32/shared' })
writeFileSync(path.join(sharedPath, 'first.md'), 'first')
await manager.finalize(repo, job, { id: 1, worktreePath: sharedPath, runBranch: 'schedule/32/shared', triggerSource: 'manual' })
expect(existsSync(sharedPath)).toBe(true)
writeFileSync(path.join(sharedPath, 'uncommitted.md'), 'pending')
const second = await manager.prepare(repo, job, 2)
expect(second!.worktreePath).toBe(sharedPath)
expect(existsSync(path.join(sharedPath, 'uncommitted.md'))).toBe(true)
await manager.releaseWorktree(repo, job, sharedPath)
expect(existsSync(sharedPath)).toBe(false)
const third = await manager.prepare(repo, job, 3)
expect(existsSync(path.join(third!.worktreePath, 'first.md'))).toBe(true)
expect(existsSync(path.join(third!.worktreePath, 'uncommitted.md'))).toBe(true)
await manager.pruneRunArtifacts(repo, 32, [{ runBranch: 'schedule/32/shared', worktreePath: sharedPath }])
expect(existsSync(sharedPath)).toBe(true)
expect(execSync(`git -C "${baseRepoPath}" branch --list schedule/32/shared`, { encoding: 'utf-8' }).trim()).not.toBe('')
await manager.releaseWorktree(repo, job, sharedPath)
})
})
@@ -123,6 +123,7 @@ const baseJob: ScheduleJob = {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
+53 -10
View File
@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({
getScheduleRunById: vi.fn(),
listEnabledScheduleJobs: vi.fn(),
listRunningScheduleRuns: vi.fn(),
clearScheduleRunWorktreePath: vi.fn(),
listScheduleJobIdsByRepo: vi.fn(),
listScheduleJobsByRepo: vi.fn(),
listScheduleRunsByJob: vi.fn(),
@@ -35,6 +36,8 @@ const mocks = vi.hoisted(() => ({
prepare: vi.fn().mockResolvedValue(null),
finalize: vi.fn().mockResolvedValue({ commitHash: null }),
pruneRunArtifacts: vi.fn().mockResolvedValue(undefined),
listWorktrees: vi.fn().mockReturnValue([]),
releaseWorktree: vi.fn().mockResolvedValue(undefined),
},
}))
@@ -55,6 +58,7 @@ vi.mock('../../src/db/schedules', () => ({
getScheduleRunById: mocks.getScheduleRunById,
listEnabledScheduleJobs: mocks.listEnabledScheduleJobs,
listRunningScheduleRuns: mocks.listRunningScheduleRuns,
clearScheduleRunWorktreePath: mocks.clearScheduleRunWorktreePath,
listScheduleJobIdsByRepo: mocks.listScheduleJobIdsByRepo,
listScheduleJobsByRepo: mocks.listScheduleJobsByRepo,
listScheduleRunsByJob: mocks.listScheduleRunsByJob,
@@ -146,6 +150,7 @@ const job: ScheduleJob = {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
@@ -910,31 +915,31 @@ describe('ScheduleService', () => {
expect(stub.api.agent.list).toHaveBeenCalledTimes(1)
})
it('throws when deleting or loading missing records', () => {
it('throws when deleting or loading missing records', async () => {
const stub = createStubScheduleApi()
const service = makeService(stub.api)
mocks.deleteScheduleJob.mockReturnValue(false)
mocks.getScheduleRunById.mockReturnValue(null)
expect(() => service.deleteJob(42, 7)).toThrow('Schedule not found')
await expect(service.deleteJob(42, 7)).rejects.toThrow('Schedule not found')
expect(() => service.getRun(42, 7, 5)).toThrow('Run not found')
})
it('blocks deleteJob when a running run exists in activeRuns', () => {
it('blocks deleteJob when a running run exists in activeRuns', async () => {
const stub = createStubScheduleApi()
const service = makeService(stub.api)
Reflect.get(ScheduleService, 'activeRuns').set(7, { runId: 5, abort: new AbortController() })
expect(() => service.deleteJob(42, 7)).toThrow('Cannot delete a schedule while it is running. Cancel the run first.')
await expect(service.deleteJob(42, 7)).rejects.toThrow('Cannot delete a schedule while it is running. Cancel the run first.')
})
it('blocks deleteJob when a running run exists in the database', () => {
it('blocks deleteJob when a running run exists in the database', async () => {
const stub = createStubScheduleApi()
const service = makeService(stub.api)
mocks.getRunningScheduleRunByJob.mockReturnValue({ ...baseRun, status: 'running' })
expect(() => service.deleteJob(42, 7)).toThrow('Cannot delete a schedule while it is running. Cancel the run first.')
await expect(service.deleteJob(42, 7)).rejects.toThrow('Cannot delete a schedule while it is running. Cancel the run first.')
})
it('blocks prepareRepoDelete when a running run exists in activeRuns', () => {
@@ -961,14 +966,14 @@ describe('ScheduleService', () => {
expect(onJobChange).not.toHaveBeenCalled()
})
it('deleteJob succeeds when no runs are active', () => {
it('deleteJob succeeds when no runs are active', async () => {
const stub = createStubScheduleApi()
const service = makeService(stub.api)
mocks.deleteScheduleJob.mockReturnValue(true)
const onJobChange = vi.fn()
service.setJobChangeHandler(onJobChange)
service.deleteJob(42, 7)
await service.deleteJob(42, 7)
expect(mocks.deleteScheduleJob).toHaveBeenCalledWith(expect.anything(), 42, 7)
expect(onJobChange).toHaveBeenCalledWith(null, 7)
@@ -2153,6 +2158,7 @@ describe('ScheduleRunner', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: Date.now(),
lastRunAt: null,
createdAt: Date.now(),
@@ -2191,6 +2197,7 @@ describe('ScheduleRunner', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: Date.now(),
lastRunAt: null,
createdAt: Date.now(),
@@ -2227,6 +2234,7 @@ describe('ScheduleRunner', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: Date.now(),
lastRunAt: null,
createdAt: Date.now(),
@@ -2262,6 +2270,7 @@ describe('ScheduleRunner', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: Date.now(),
lastRunAt: null,
createdAt: Date.now(),
@@ -2297,6 +2306,7 @@ describe('ScheduleRunner', () => {
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
nextRunAt: Date.now(),
lastRunAt: null,
createdAt: Date.now(),
@@ -2346,7 +2356,7 @@ describe('ScheduleService run history cleanup', () => {
const result = await makeService().clearRunHistory(42, 7)
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, [
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, 7, [
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null },
{ id: 1, status: 'failed', runBranch: null, worktreePath: null },
])
@@ -2372,12 +2382,45 @@ describe('ScheduleService run history cleanup', () => {
await makeService().deleteRun(42, 7, 5)
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, [
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, 7, [
{ runBranch: 'schedule/7/run-5', worktreePath: '/wt/5' },
])
expect(mocks.deleteScheduleRunById).toHaveBeenCalledWith({}, 42, 7, 5)
})
it('listWorktrees marks the shared worktree and running run worktrees as in use', () => {
mocks.listRunningScheduleRuns.mockReturnValue([{ ...baseRun, status: 'running', worktreePath: '/wt/job-7-run-9' }])
mocks.getRunningScheduleRunByJob.mockReturnValue({ ...baseRun, status: 'running' })
mocks.stubWorktreeManager.listWorktrees.mockReturnValue([
{ jobId: 7, runId: 3, worktreePath: '/wt/job-7-run-3', branch: 'schedule/7/run-3' },
{ jobId: 7, runId: null, worktreePath: '/wt/job-7-shared', branch: 'schedule/7/shared' },
{ jobId: 7, runId: 9, worktreePath: '/wt/job-7-run-9', branch: 'schedule/7/run-9' },
])
expect(makeService().listWorktrees(42, 7)).toEqual([
{ worktreePath: '/wt/job-7-shared', branch: 'schedule/7/shared', runId: null, inUse: true },
{ worktreePath: '/wt/job-7-run-9', branch: 'schedule/7/run-9', runId: 9, inUse: true },
{ worktreePath: '/wt/job-7-run-3', branch: 'schedule/7/run-3', runId: 3, inUse: false },
])
})
it('removeWorktrees releases idle worktrees and clears run references', async () => {
mocks.listRunningScheduleRuns.mockReturnValue([{ ...baseRun, status: 'running', worktreePath: '/wt/job-7-run-9' }])
mocks.getRunningScheduleRunByJob.mockReturnValue(null)
mocks.stubWorktreeManager.listWorktrees.mockReturnValue([
{ jobId: 7, runId: 3, worktreePath: '/wt/job-7-run-3', branch: 'schedule/7/run-3' },
{ jobId: 7, runId: 9, worktreePath: '/wt/job-7-run-9', branch: 'schedule/7/run-9' },
])
await expect(makeService().removeWorktrees(42, 7)).resolves.toEqual({ removed: 1 })
expect(mocks.stubWorktreeManager.releaseWorktree).toHaveBeenCalledTimes(1)
expect(mocks.stubWorktreeManager.releaseWorktree).toHaveBeenCalledWith(repo, job, '/wt/job-7-run-3')
expect(mocks.clearScheduleRunWorktreePath).toHaveBeenCalledWith({}, 42, 7, '/wt/job-7-run-3')
await expect(makeService().removeWorktrees(42, 7, '/wt/job-7-run-9')).rejects.toThrow('in use by a running run')
await expect(makeService().removeWorktrees(42, 7, '/etc')).rejects.toThrow('Worktree not found')
})
it('deleteRun refuses to delete a run in progress', async () => {
mocks.getScheduleRunById.mockReturnValue({ ...baseRun, id: 5, status: 'running' })