mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat(schedules): add workspace modes and worktree management
This commit is contained in:
1 parent
c06075651d
commit
6ec3f3bd91
90 files changed
+2084
-801
No files matched your search
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<{
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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,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
|
||||
@@ -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,
|
||||
]
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user