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

+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)