Merge branch 'main' into feat/docker-self-upgrade

Resolve conflicts against the restart-coordinator rewrite and renumber
the manager-upgrade-jobs migration from 16 to 19 to avoid colliding
with main's 016-018 migrations. Includes review fixes: background the
docker pull, add a staleness guard for stuck recreating jobs, move
manager-upgrade types to @opencode-manager/shared, wire the
active-session pre-check dialog into the Upgrade Manager button, and
surface upgrade errors via FetchError-aware messaging.
This commit is contained in:
Chris Scott committed 2026-07-04 10:36:01 -04:00
commit 9effe53bdc
125 files changed
+3899 -975

No files matched your search

-9
View File
@@ -1,9 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
const mockFn = vi.hoisted(() => vi.fn().mockReturnValue('mocked'))
describe('bun test vi.hoisted compatibility', () => {
it('supports vi.hoisted', () => {
expect(mockFn()).toBe('mocked')
})
})
+53
View File
@@ -0,0 +1,53 @@
import { Database } from 'bun:sqlite'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { migrate, type Migration } from '../../src/db/migration-runner'
import { logger } from '../../src/utils/logger'
function makeMigration(version: number, name: string, up: () => void): Migration {
return { version, name, up, down: () => {} }
}
describe('migrate - version/name mismatch guard', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('warns and skips when an applied version was recorded under a different name', () => {
const db = new Database(':memory:')
db.run('CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL)')
db.run("INSERT INTO schema_migrations (version, name, applied_at) VALUES (15, 'repos-add-name', 0)")
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
const up = vi.fn()
migrate(db, [makeMigration(15, 'schedule-worktree-isolation', up)])
expect(up).not.toHaveBeenCalled()
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('Migration version 15 is recorded as "repos-add-name" but the code defines "schedule-worktree-isolation"'),
)
})
it('does not warn when recorded names match', () => {
const db = new Database(':memory:')
db.run('CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL)')
db.run("INSERT INTO schema_migrations (version, name, applied_at) VALUES (15, 'schedule-worktree-isolation', 0)")
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
migrate(db, [makeMigration(15, 'schedule-worktree-isolation', vi.fn())])
expect(warnSpy).not.toHaveBeenCalled()
})
it('applies pending migrations and records them', () => {
const db = new Database(':memory:')
const up = vi.fn()
migrate(db, [makeMigration(1, 'base', up)])
expect(up).toHaveBeenCalledTimes(1)
const row = db.prepare('SELECT version, name FROM schema_migrations WHERE version = 1').get() as { version: number; name: string }
expect(row).toEqual({ version: 1, name: 'base' })
})
})
-14
View File
@@ -1,6 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import * as db from '../../src/db/queries'
import * as schema from '../../src/db/schema'
const mockDb = {
prepare: vi.fn(),
@@ -289,17 +288,4 @@ describe('Database Queries', () => {
expect(mockDb.prepare).not.toHaveBeenCalled()
})
})
describe('Database Schema', () => {
it('should have schema module available', () => {
expect(schema.initializeDatabase).toBeDefined()
expect(typeof schema.initializeDatabase).toBe('function')
})
})
describe('Transaction Support', () => {
it('should support transaction existence', () => {
expect(typeof mockDb.transaction).toBe('function')
})
})
})
@@ -0,0 +1,107 @@
import { describe, expect, it, beforeEach } from 'vitest'
import { Database } from 'bun:sqlite'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { createScheduleJob, getScheduleJobById, updateScheduleJob } from '../../src/db/schedules'
import type { ScheduleJobPersistenceInput } from '../../src/services/schedule-config'
describe('schedule permission config persistence', () => {
let db: Database
beforeEach(() => {
db = new Database(':memory:')
db.exec('PRAGMA foreign_keys = OFF')
migrate(db, allMigrations)
const now = Date.now()
db.exec(
`INSERT INTO repos (id, repo_url, local_path, branch, default_branch, clone_status, cloned_at)
VALUES (1, 'https://github.com/test/repo', 'repos/test', 'main', 'main', 'ready', ${now})`,
)
})
const baseInput = (overrides: Partial<ScheduleJobPersistenceInput> = {}): ScheduleJobPersistenceInput => ({
name: 'Permission test job',
description: null,
enabled: true,
scheduleMode: 'interval',
intervalMinutes: 60,
cronExpression: null,
timezone: null,
agentSlug: null,
prompt: 'Run a permission test',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: Date.now() + 3600000,
...overrides,
})
it('round-trips permissionConfig when set on create', () => {
const config = {
allowExternalDirectory: true,
bashDenyPatterns: ['rm -rf /'],
}
const created = createScheduleJob(db, 1, baseInput({ permissionConfig: config }))
expect(created.permissionConfig).toEqual(config)
const fetched = getScheduleJobById(db, 1, created.id)
expect(fetched).not.toBeNull()
expect(fetched!.permissionConfig).toEqual(config)
})
it('returns null permissionConfig when not provided on create', () => {
const created = createScheduleJob(db, 1, baseInput())
expect(created.permissionConfig).toBeNull()
const fetched = getScheduleJobById(db, 1, created.id)
expect(fetched).not.toBeNull()
expect(fetched!.permissionConfig).toBeNull()
})
it('updates permissionConfig independently of other fields', () => {
const created = createScheduleJob(db, 1, baseInput())
expect(created.permissionConfig).toBeNull()
const config = {
allowExternalDirectory: false,
bashDenyPatterns: ['sudo rm -rf *'],
}
const updated = updateScheduleJob(db, 1, created.id, baseInput({ permissionConfig: config }))
expect(updated).not.toBeNull()
expect(updated!.permissionConfig).toEqual(config)
// Verify other fields are unchanged
expect(updated!.name).toBe('Permission test job')
expect(updated!.prompt).toBe('Run a permission test')
})
it('clears permissionConfig when set to null on update', () => {
const config = { allowExternalDirectory: true, bashDenyPatterns: [] }
const created = createScheduleJob(db, 1, baseInput({ permissionConfig: config }))
expect(created.permissionConfig).toEqual(config)
const updated = updateScheduleJob(db, 1, created.id, baseInput({ permissionConfig: null }))
expect(updated).not.toBeNull()
expect(updated!.permissionConfig).toBeNull()
})
it('preserves permissionConfig when updating other fields', () => {
const config = { allowExternalDirectory: false, bashDenyPatterns: ['rm -rf *'] }
const created = createScheduleJob(db, 1, baseInput({ permissionConfig: config }))
expect(created.permissionConfig).toEqual(config)
const updated = updateScheduleJob(db, 1, created.id, {
...baseInput({ permissionConfig: config }),
name: 'Updated name',
prompt: 'Updated prompt',
})
expect(updated).not.toBeNull()
expect(updated!.name).toBe('Updated name')
expect(updated!.prompt).toBe('Updated prompt')
expect(updated!.permissionConfig).toEqual(config)
})
})
+11 -4
View File
@@ -20,6 +20,7 @@ function makeJobRow(overrides: Record<string, unknown> = {}) {
prompt: 'Generate a weekly summary.',
model: 'openai/gpt-5-mini',
skill_metadata: JSON.stringify({ skillSlugs: ['planning'], notes: 'Optional notes' }),
permission_config: null,
branch: null,
created_at: Date.UTC(2026, 2, 8, 12, 0, 0),
updated_at: Date.UTC(2026, 2, 9, 12, 0, 0),
@@ -47,6 +48,7 @@ function makeRunRow(overrides: Record<string, unknown> = {}) {
run_branch: null,
commit_hash: null,
worktree_path: null,
workspace_id: null,
...overrides,
}
}
@@ -111,6 +113,7 @@ describe('schedule database queries', () => {
prompt: 'Generate a weekly summary.',
model: 'openai/gpt-5-mini',
skillMetadata: { skillSlugs: ['planning'], notes: 'Optional notes' },
permissionConfig: null,
branch: null,
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
})
@@ -129,6 +132,7 @@ describe('schedule database queries', () => {
'openai/gpt-5-mini',
JSON.stringify({ skillSlugs: ['planning'], notes: 'Optional notes' }),
null,
null,
expect.any(Number),
expect.any(Number),
null,
@@ -165,6 +169,7 @@ describe('schedule database queries', () => {
prompt: 'Run a new summary.',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: null,
})
@@ -182,6 +187,7 @@ describe('schedule database queries', () => {
null,
null,
null,
null,
expect.any(Number),
null,
42,
@@ -300,6 +306,7 @@ describe('schedule database queries', () => {
'/worktrees/feature-branch',
'feature-x',
null,
null,
42,
7,
5,
@@ -602,8 +609,8 @@ describe('schedule database queries', () => {
it('listScheduleRunArtifactsByJob maps run branch/worktree rows', () => {
const stmt = {
all: vi.fn().mockReturnValue([
{ id: 3, status: 'completed', run_branch: 'schedule/7/run-3', worktree_path: null },
{ id: 2, status: 'running', run_branch: 'schedule/7/run-2', worktree_path: '/wt/2' },
{ id: 3, status: 'completed', run_branch: 'schedule/7/run-3', worktree_path: null, workspace_id: null },
{ id: 2, status: 'running', run_branch: 'schedule/7/run-2', worktree_path: '/wt/2', workspace_id: null },
]),
}
mockDb.prepare.mockReturnValue(stmt)
@@ -612,8 +619,8 @@ describe('schedule database queries', () => {
expect(stmt.all).toHaveBeenCalledWith(42, 7)
expect(artifacts).toEqual([
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null },
{ id: 2, status: 'running', runBranch: 'schedule/7/run-2', worktreePath: '/wt/2' },
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null, workspaceId: null },
{ id: 2, status: 'running', runBranch: 'schedule/7/run-2', worktreePath: '/wt/2', workspaceId: null },
])
})
+6 -2
View File
@@ -11,7 +11,10 @@ export class Database {
prepare(sql: string) {
const stmt = this.db.prepare(sql)
return {
run: (...params: unknown[]) => (stmt.run as (...args: unknown[]) => void)(...params),
run: (...params: unknown[]) => {
const result = (stmt.run as (...args: unknown[]) => { changes: number; lastInsertRowid: number })(...params)
return { changes: result.changes, lastInsertRowid: result.lastInsertRowid }
},
get: (...params: unknown[]) => (stmt.get as (...args: unknown[]) => unknown)(...params),
all: (...params: unknown[]) => (stmt.all as (...args: unknown[]) => unknown[])(...params),
}
@@ -27,7 +30,8 @@ export class Database {
run(sql: string, ...params: unknown[]) {
const stmt = this.db.prepare(sql)
return (stmt.run as (...args: unknown[]) => void)(...params)
const result = (stmt.run as (...args: unknown[]) => { changes: number; lastInsertRowid: number })(...params)
return { changes: result.changes, lastInsertRowid: result.lastInsertRowid }
}
transaction<T extends (...args: unknown[]) => void>(fn: T) {
-48
View File
@@ -1,48 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { DEFAULTS } from '@opencode-manager/shared/config'
const { HEARTBEAT_INTERVAL_MS } = DEFAULTS.SSE
describe('SSE Routes', () => {
describe('HEARTBEAT_INTERVAL_MS', () => {
it('should be 30000ms (30 seconds)', () => {
expect(HEARTBEAT_INTERVAL_MS).toBe(30000)
})
it('should fire heartbeats at correct interval', async () => {
vi.useFakeTimers()
const heartbeatSpy = vi.fn()
const intervalId = setInterval(() => {
heartbeatSpy()
}, HEARTBEAT_INTERVAL_MS)
await vi.advanceTimersByTimeAsync(0)
expect(heartbeatSpy).toHaveBeenCalledTimes(0)
await vi.advanceTimersByTimeAsync(30000)
expect(heartbeatSpy).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(30000)
expect(heartbeatSpy).toHaveBeenCalledTimes(2)
clearInterval(intervalId)
vi.useRealTimers()
})
it('should fire two heartbeats within 70 seconds', async () => {
vi.useFakeTimers()
const heartbeatSpy = vi.fn()
const intervalId = setInterval(() => {
heartbeatSpy()
}, HEARTBEAT_INTERVAL_MS)
await vi.advanceTimersByTimeAsync(70000)
expect(heartbeatSpy).toHaveBeenCalledTimes(2)
clearInterval(intervalId)
vi.useRealTimers()
})
})
})
-7
View File
@@ -72,13 +72,6 @@ describe('STT Routes', () => {
sttApp = createSTTRoutes(mockDb)
})
describe('createSTTRoutes', () => {
it('should create a Hono app with routes', () => {
expect(sttApp).toBeDefined()
expect(typeof sttApp.fetch).toBe('function')
})
})
describe('GET /status', () => {
it('should return status with correct structure', async () => {
const req = new Request('http://localhost/status?userId=test')
+80 -8
View File
@@ -28,7 +28,6 @@ function createRunner(): { runner: DockerRunner; calls: { inspectSelf: SelfConta
const runner: DockerRunner = {
inspectSelf: vi.fn().mockImplementation(async () => {
const info: SelfContainerInfo = {
containerId: 'abc123',
project: 'opencode',
service: 'manager',
workingDir: '/app',
@@ -164,12 +163,16 @@ describe('ManagerUpgradeService', () => {
const job = await service.startUpgrade('0.15.0')
expect(job.status).toBe('recreating')
// startUpgrade returns as soon as the job is created; the pull and
// recreate continue in the background and are reflected via job status.
expect(job.status).toBe('pulling')
expect(job.toVersion).toBe('0.15.0')
expect(job.targetImage).toBe('opencode-manager:0.15.0')
expect(job.fromVersion).toBe('0.14.0')
expect(job.error).toBeNull()
await tick()
// Pull was called with the resolved target image
expect(calls.pulled).toEqual(['opencode-manager:0.15.0'])
expect(calls.inspectSelf).toHaveLength(1)
@@ -198,6 +201,7 @@ describe('ManagerUpgradeService', () => {
})
await service.startUpgrade('0.15.0')
await tick()
expect(calls.pulled).toEqual(['my-registry/opencode-manager:0.15.0'])
})
@@ -210,6 +214,7 @@ describe('ManagerUpgradeService', () => {
})
await service.startUpgrade()
await tick()
expect(calls.pulled).toEqual(['opencode-manager:latest'])
})
})
@@ -279,6 +284,8 @@ describe('ManagerUpgradeService', () => {
message: 'An upgrade is already in progress',
})
await tick()
// Only one pull and one spawn should have occurred
expect(calls.pulled).toHaveLength(1)
expect(calls.spawned).toHaveLength(1)
@@ -286,8 +293,8 @@ describe('ManagerUpgradeService', () => {
})
describe('startUpgrade - pull failure', () => {
// Cycle 4: pull fails → job marked failed, 500 thrown
it('marks job as failed and throws 500 when pull rejects', async () => {
// Cycle 4: pull fails in the background → job marked failed with the error
it('marks job as failed when the background pull rejects', async () => {
const { runner, calls } = createRunner()
runner.pull = vi.fn().mockRejectedValue(new Error('Network error'))
@@ -297,10 +304,10 @@ describe('ManagerUpgradeService', () => {
capability: () => ({ inDocker: true, socket: true, enabled: true }),
})
await expect(service.startUpgrade('0.15.0')).rejects.toMatchObject({
status: 500,
message: 'Network error',
})
const job = await service.startUpgrade('0.15.0')
expect(job.status).toBe('pulling')
await tick()
// spawnRecreate should NOT have been called
expect(calls.spawned).toHaveLength(0)
@@ -314,6 +321,70 @@ describe('ManagerUpgradeService', () => {
})
})
describe('stale recreating jobs', () => {
it('getStatus fails a recreating job older than the staleness bound', async () => {
const { runner } = createRunner()
insertUpgradeJob(db, {
status: 'recreating',
fromVersion: '0.14.0',
toVersion: '0.15.0',
startedAt: Date.now() - 11 * 60 * 1000,
})
const service = new ManagerUpgradeService(db, {
runner,
// Same as fromVersion — the recreate helper never completed
getCurrentVersion: vi.fn().mockResolvedValue('0.14.0'),
capability: () => ({ inDocker: true, socket: true, enabled: true }),
})
const status = await service.getStatus()
expect(status.job).not.toBeNull()
expect(status.job!.status).toBe('failed')
expect(status.job!.error).toMatch(/did not complete/i)
})
it('startUpgrade proceeds after expiring a stale recreating job', async () => {
const { runner, calls } = createRunner()
insertUpgradeJob(db, {
status: 'recreating',
fromVersion: '0.14.0',
toVersion: '0.15.0',
startedAt: Date.now() - 11 * 60 * 1000,
})
const service = new ManagerUpgradeService(db, {
runner,
getCurrentVersion: vi.fn().mockResolvedValue('0.14.0'),
capability: () => ({ inDocker: true, socket: true, enabled: true }),
})
const job = await service.startUpgrade('0.16.0')
expect(job.status).toBe('pulling')
await tick()
expect(calls.pulled).toEqual(['opencode-manager:0.16.0'])
})
it('getStatus leaves a fresh recreating job untouched', async () => {
const { runner } = createRunner()
insertUpgradeJob(db, {
status: 'recreating',
fromVersion: '0.14.0',
toVersion: '0.15.0',
startedAt: Date.now(),
})
const service = new ManagerUpgradeService(db, {
runner,
getCurrentVersion: vi.fn().mockResolvedValue('0.14.0'),
capability: () => ({ inDocker: true, socket: true, enabled: true }),
})
const status = await service.getStatus()
expect(status.job!.status).toBe('recreating')
})
})
describe('reconcile', () => {
// Cycle 5: recreating job + version matches toVersion → completed
it('marks recreating job as completed when current version matches toVersion', async () => {
@@ -492,6 +563,7 @@ describe('ManagerUpgradeService', () => {
})
await service.startUpgrade('0.15.0')
await tick()
// Should NOT produce 'localhost:0.15.0'
expect(calls.pulled).toEqual(['localhost:5000/opencode-manager:0.15.0'])
expect(calls.spawned[0]!.targetImage).toBe('localhost:5000/opencode-manager:0.15.0')
@@ -33,6 +33,7 @@ describe('schedule-config', () => {
prompt: 'Review the repository and summarize risks.',
model: 'openai/gpt-5',
skillMetadata: undefined,
permissionConfig: null,
branch: null,
nextRunAt: currentDate + 60 * 60_000,
})
@@ -71,6 +72,7 @@ describe('schedule-config', () => {
prompt: 'Old prompt',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
@@ -101,6 +103,7 @@ describe('schedule-config', () => {
prompt: 'Old prompt',
model: 'openai/gpt-5-mini',
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
@@ -134,6 +137,7 @@ describe('schedule-config', () => {
prompt: 'Prompt',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: 'feature/foo',
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: null,
@@ -163,6 +167,7 @@ describe('schedule-config', () => {
prompt: 'Prompt',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: null,
@@ -192,6 +197,7 @@ describe('schedule-config', () => {
prompt: 'Prompt',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: 'feature/foo',
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: null,
@@ -221,6 +227,7 @@ describe('schedule-config', () => {
prompt: 'Run a report',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: null,
lastRunAt: null,
@@ -263,6 +270,7 @@ describe('schedule-config', () => {
prompt: 'Prompt',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: null,
lastRunAt: null,
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest'
import { DEFAULT_DESTRUCTIVE_BASH_PATTERNS, buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
describe('buildSchedulePermissionRuleset', () => {
it('returns the allow-all baseline with default deny rules when given null', () => {
const result = buildSchedulePermissionRuleset(null)
expect(result['*']).toBe('allow')
expect(result.external_directory).toBe('deny')
for (const pattern of DEFAULT_DESTRUCTIVE_BASH_PATTERNS) {
expect(result.bash?.[pattern]).toBe('deny')
}
})
it('returns only the allow-all baseline when all permissions are granted', () => {
const result = buildSchedulePermissionRuleset({ allowExternalDirectory: true, bashDenyPatterns: [] })
expect(result).toEqual({ '*': 'allow' })
})
it('includes a single custom bash deny pattern alongside external_directory deny', () => {
const result = buildSchedulePermissionRuleset({ allowExternalDirectory: false, bashDenyPatterns: ['rm -rf *'] })
expect(result).toEqual({
'*': 'allow',
external_directory: 'deny',
bash: { 'rm -rf *': 'deny' },
})
})
})
+266 -3
View File
@@ -72,6 +72,19 @@ describe('ScheduleWorktreeManager', () => {
}
const mockDb = {} as any
// Default mock OpenCodeClient: postJson rejects (triggers fallback), forward
// returns an ok response for teardown safety.
const mockOpenCodeClient = {
postJson: vi.fn().mockRejectedValue(new Error('API unavailable')),
forward: vi.fn().mockResolvedValue(new Response(null, { status: 200 })),
getJson: vi.fn(),
forwardRaw: vi.fn(),
setProviderAuth: vi.fn(),
deleteProviderAuth: vi.fn(),
startMcpAuth: vi.fn(),
authenticateMcp: vi.fn(),
}
beforeAll(() => {
tmpDir = mkdtempSync(path.join(tmpdir(), 'schedule-worktree-test-'))
tmpRoot = tmpDir
@@ -113,6 +126,7 @@ describe('ScheduleWorktreeManager', () => {
mockSettingsService as any,
mockCredentialProvider as any,
mockDb,
mockOpenCodeClient as any,
)
}
@@ -126,9 +140,9 @@ describe('ScheduleWorktreeManager', () => {
} as any
}
// ---- Tests ----
// ---- Fallback (raw git) tests ----
it('prepare creates a worktree with the correct branch name and returns context', async () => {
it('prepare creates a worktree with the correct branch name and returns context (raw git fallback)', async () => {
const manager = await createManager()
const repo = testRepo()
const job = { id: 10, branch: null }
@@ -140,6 +154,7 @@ describe('ScheduleWorktreeManager', () => {
expect(ctx!.directory).toBeDefined()
expect(ctx!.worktreePath).toBe(ctx!.directory)
expect(ctx!.runBranch).toBe(`schedule/10/run-1`)
expect(ctx!.workspaceId).toBeNull()
expect(existsSync(ctx!.worktreePath)).toBe(true)
// The checked-out branch in the worktree must match the run branch
@@ -260,7 +275,7 @@ describe('ScheduleWorktreeManager', () => {
expect(existsSync(path.join(scheduleWorktreesRoot, 'job-21-run-1'))).toBe(false)
})
it('prepare respects the branch override', async () => {
it('prepare respects the branch override (raw git fallback)', async () => {
const manager = await createManager()
const repo = testRepo()
const job = { id: 20, branch: 'dev' }
@@ -285,4 +300,252 @@ describe('ScheduleWorktreeManager', () => {
const { removeWorktree } = await import('../../src/services/repo')
await removeWorktree(baseRepoPath, ctx!.worktreePath)
})
// ---- OpenCode API path tests ----
/**
* Helper: creates a linked git worktree directory (rather than a clone) so
* that refs and objects are shared with the base repo. The worktree is
* created with a temp branch that prepare() will later overwrite via
* `checkout -B`.
*/
async function createWorktreeWorkspace(dirName: string): Promise<{ directory: string; cleanup: () => Promise<void> }> {
const directory = path.join(tmpDir, dirName)
const tempBranch = `_temp_${dirName}`
// Create a detached worktree on the current HEAD without creating a branch
execSync(`git -C "${baseRepoPath}" worktree add --detach "${directory}" origin/main`, { env })
execSync(`git -C "${directory}" config user.email test@test.com`, { env })
execSync(`git -C "${directory}" config user.name Test`, { env })
const cleanup = async () => {
const { removeWorktree } = await import('../../src/services/repo')
await removeWorktree(baseRepoPath, directory)
// Also remove any leftover branch the test might have created
execSync(`git -C "${baseRepoPath}" branch -D "${tempBranch}" 2>/dev/null || true`, { env })
}
return { directory, cleanup }
}
it('prepare calls POST /experimental/workspace and returns workspaceId on success', async () => {
const { directory: workspaceDirectory, cleanup } = await createWorktreeWorkspace('oc-workspace')
const workspaceId = 'ws-test-123'
const mockPost = vi.fn().mockResolvedValue({
id: workspaceId,
directory: workspaceDirectory,
branch: null,
})
mockOpenCodeClient.postJson = mockPost
const manager = await createManager()
const repo = testRepo()
const job = { id: 30, branch: null }
const runId = 5
const ctx = await manager.prepare(repo, job, runId)
expect(ctx).not.toBeNull()
expect(ctx!.workspaceId).toBe(workspaceId)
expect(ctx!.runBranch).toBe('schedule/30/run-5')
expect(existsSync(ctx!.worktreePath)).toBe(true)
expect(ctx!.worktreePath).toBe(workspaceDirectory)
// Verify the API was called correctly
expect(mockPost).toHaveBeenCalledWith(
'/experimental/workspace',
{ type: 'worktree', branch: null },
{ directory: repo.fullPath },
)
// Verify the branch was re-pointed
const branch = execSync(`git -C "${workspaceDirectory}" rev-parse --abbrev-ref HEAD`, {
encoding: 'utf-8',
}).trim()
expect(branch).toBe('schedule/30/run-5')
// Cleanup
await cleanup()
})
it('prepare falls back to raw git when postJson rejects', async () => {
mockOpenCodeClient.postJson = vi.fn().mockRejectedValue(new Error('API unavailable'))
const manager = await createManager()
const repo = testRepo()
const job = { id: 40, branch: null }
const runId = 10
const ctx = await manager.prepare(repo, job, runId)
expect(ctx).not.toBeNull()
expect(ctx!.workspaceId).toBeNull()
expect(ctx!.runBranch).toBe('schedule/40/run-10')
expect(existsSync(ctx!.worktreePath)).toBe(true)
// The worktree path should be under scheduleWorktreesRoot (raw git path)
expect(ctx!.worktreePath).toContain(scheduleWorktreesRoot)
// Cleanup
const { removeWorktree } = await import('../../src/services/repo')
await removeWorktree(baseRepoPath, ctx!.worktreePath)
})
it('finalize deletes workspace via API when workspaceId is set', async () => {
const { directory: workspaceDirectory, cleanup } = await createWorktreeWorkspace('oc-finalize-test')
const workspaceId = 'ws-finalize-456'
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
id: workspaceId,
directory: workspaceDirectory,
branch: null,
})
const deleteMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
mockOpenCodeClient.forward = deleteMock
const manager = await createManager()
const repo = testRepo()
const job = { id: 50, branch: null, name: 'Finalize API' }
const runId = 300
const ctx = await manager.prepare(repo, job, runId)
expect(ctx).not.toBeNull()
expect(ctx!.workspaceId).toBe(workspaceId)
// Write a file so there are changes to commit
writeFileSync(path.join(workspaceDirectory, 'output.md'), '# API Finalize Test')
const result = await manager.finalize(
repo,
{ id: 50, name: 'Finalize API', prompt: 'test' },
{ id: runId, worktreePath: workspaceDirectory, runBranch: ctx!.runBranch, triggerSource: 'manual', workspaceId: ctx!.workspaceId },
)
expect(result.commitHash).toMatch(/^[0-9a-f]{40}$/)
// Verify DELETE was called with the correct workspaceId
expect(deleteMock).toHaveBeenCalledWith({
method: 'DELETE',
path: `/experimental/workspace/${encodeURIComponent(workspaceId)}`,
directory: repo.fullPath,
})
// The commit must still be reachable on the runBranch in the base repo
const log = execSync(`git -C "${baseRepoPath}" log "${ctx!.runBranch}" --oneline`, {
encoding: 'utf-8',
}).trim()
expect(log).toBeTruthy()
// Clean up in case the API mock didn't actually remove the worktree
await cleanup()
})
it('finalize falls back to raw removeWorktree when workspace DELETE fails', async () => {
const { directory: workspaceDirectory, cleanup } = await createWorktreeWorkspace('oc-delete-fail')
const workspaceId = 'ws-delete-fail-789'
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
id: workspaceId,
directory: workspaceDirectory,
branch: null,
})
// DELETE returns non-ok response → triggers fallback removeWorktree
mockOpenCodeClient.forward = vi.fn().mockResolvedValue(new Response('Not Found', { status: 404 }))
const manager = await createManager()
const repo = testRepo()
const job = { id: 60, branch: null, name: 'Delete Fail' }
const runId = 400
const ctx = await manager.prepare(repo, job, runId)
expect(ctx).not.toBeNull()
expect(ctx!.workspaceId).toBe(workspaceId)
writeFileSync(path.join(workspaceDirectory, 'data.txt'), 'test data')
const result = await manager.finalize(
repo,
{ id: 60, name: 'Delete Fail', prompt: 'test' },
{ id: runId, worktreePath: workspaceDirectory, runBranch: ctx!.runBranch, triggerSource: 'manual', workspaceId: ctx!.workspaceId },
)
expect(result.commitHash).toMatch(/^[0-9a-f]{40}$/)
// Directory should be cleaned up (via fallback removeWorktree)
expect(existsSync(workspaceDirectory)).toBe(false)
// Clean up in case the directory somehow still exists
await cleanup()
})
it('finalize restores run branch if OpenCode delete removed it', async () => {
const { directory: workspaceDirectory, cleanup } = await createWorktreeWorkspace('oc-branch-restore')
const workspaceId = 'ws-branch-restore-101'
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
id: workspaceId,
directory: workspaceDirectory,
branch: null,
})
mockOpenCodeClient.forward = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
const manager = await createManager()
const repo = testRepo()
const job = { id: 70, branch: null, name: 'Branch Restore' }
const runId = 500
const ctx = await manager.prepare(repo, job, runId)
expect(ctx).not.toBeNull()
expect(ctx!.workspaceId).toBe(workspaceId)
writeFileSync(path.join(workspaceDirectory, 'important.md'), '# Branch Restore Test')
// Simulate: API delete removes the branch. First detach the worktree
// HEAD so git allows the deletion (OpenCode's workspace DELETE handles
// the worktree-level cleanup first, then the branch goes away).
const runBranch = ctx!.runBranch!
execSync(`git -C "${workspaceDirectory}" checkout --detach`, { env })
execSync(`git -C "${baseRepoPath}" branch -D "${runBranch}"`, { env })
const result = await manager.finalize(
repo,
{ id: 70, name: 'Branch Restore', prompt: 'test' },
{ id: runId, worktreePath: workspaceDirectory, runBranch, triggerSource: 'manual', workspaceId: ctx!.workspaceId },
)
expect(result.commitHash).toMatch(/^[0-9a-f]{40}$/)
// Branch should have been restored by finalize
const branchExists = execSync(`git -C "${baseRepoPath}" rev-parse --verify "refs/heads/${runBranch}"`, {
encoding: 'utf-8',
}).trim()
expect(branchExists).toBeTruthy()
// And the commit hash should match
const branchCommit = execSync(`git -C "${baseRepoPath}" rev-parse "${runBranch}"`, {
encoding: 'utf-8',
}).trim()
expect(branchCommit).toBe(result.commitHash)
await cleanup()
})
it('prepare returns workspaceId null on postJson failure (fallback path)', async () => {
mockOpenCodeClient.postJson = vi.fn().mockRejectedValue(new Error('Network error'))
const manager = await createManager()
const repo = testRepo()
const job = { id: 80, branch: 'main' }
const runId = 15
const ctx = await manager.prepare(repo, job, runId)
expect(ctx).not.toBeNull()
expect(ctx!.workspaceId).toBeNull()
expect(ctx!.runBranch).toBe('schedule/80/run-15')
expect(existsSync(ctx!.worktreePath)).toBe(true)
expect(ctx!.worktreePath).toContain(scheduleWorktreesRoot)
// Cleanup
const { removeWorktree } = await import('../../src/services/repo')
await removeWorktree(baseRepoPath, ctx!.worktreePath)
})
})
@@ -0,0 +1,314 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { ScheduleJob, ScheduleRun } from '@opencode-manager/shared/types'
import { buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
const mocks = vi.hoisted(() => ({
getRepoById: vi.fn(),
createScheduleJob: vi.fn(),
createScheduleRun: vi.fn(),
deleteScheduleJob: vi.fn(),
deleteScheduleRunById: vi.fn(),
deleteScheduleRunsByIds: vi.fn(),
listScheduleRunArtifactsByJob: vi.fn(),
cleanupOrphanedSchedules: vi.fn(),
getScheduleJobById: vi.fn(),
getRunningScheduleRunByJob: vi.fn(),
getScheduleRunById: vi.fn(),
listEnabledScheduleJobs: vi.fn(),
listRunningScheduleRuns: vi.fn(),
listScheduleJobIdsByRepo: vi.fn(),
listScheduleJobsByRepo: vi.fn(),
listScheduleRunsByJob: vi.fn(),
updateScheduleJob: vi.fn(),
updateScheduleJobRunState: vi.fn(),
updateScheduleRun: vi.fn(),
updateScheduleRunMetadata: vi.fn(),
buildCreateSchedulePersistenceInput: vi.fn(),
buildUpdatedSchedulePersistenceInput: vi.fn(),
computeNextRunAtForJob: vi.fn(),
resolveOpenCodeModel: vi.fn(),
forward: vi.fn(),
onEvent: vi.fn(),
loggerError: vi.fn(),
updateScheduleRunWorktree: vi.fn(),
stubWorktreeManager: {
prepare: vi.fn().mockResolvedValue(null),
finalize: vi.fn().mockResolvedValue({ commitHash: null }),
pruneRunArtifacts: vi.fn().mockResolvedValue(undefined),
},
}))
vi.mock('../../src/db/queries', () => ({
getRepoById: mocks.getRepoById,
}))
vi.mock('../../src/db/schedules', () => ({
createScheduleJob: mocks.createScheduleJob,
createScheduleRun: mocks.createScheduleRun,
deleteScheduleJob: mocks.deleteScheduleJob,
deleteScheduleRunById: mocks.deleteScheduleRunById,
deleteScheduleRunsByIds: mocks.deleteScheduleRunsByIds,
listScheduleRunArtifactsByJob: mocks.listScheduleRunArtifactsByJob,
cleanupOrphanedSchedules: mocks.cleanupOrphanedSchedules,
getScheduleJobById: mocks.getScheduleJobById,
getRunningScheduleRunByJob: mocks.getRunningScheduleRunByJob,
getScheduleRunById: mocks.getScheduleRunById,
listEnabledScheduleJobs: mocks.listEnabledScheduleJobs,
listRunningScheduleRuns: mocks.listRunningScheduleRuns,
listScheduleJobIdsByRepo: mocks.listScheduleJobIdsByRepo,
listScheduleJobsByRepo: mocks.listScheduleJobsByRepo,
listScheduleRunsByJob: mocks.listScheduleRunsByJob,
updateScheduleJob: mocks.updateScheduleJob,
updateScheduleJobRunState: mocks.updateScheduleJobRunState,
updateScheduleRun: mocks.updateScheduleRun,
updateScheduleRunMetadata: mocks.updateScheduleRunMetadata,
updateScheduleRunWorktree: mocks.updateScheduleRunWorktree,
}))
vi.mock('../../src/services/schedule-config', () => ({
buildCreateSchedulePersistenceInput: mocks.buildCreateSchedulePersistenceInput,
buildUpdatedSchedulePersistenceInput: mocks.buildUpdatedSchedulePersistenceInput,
computeNextRunAtForJob: mocks.computeNextRunAtForJob,
}))
vi.mock('../../src/services/opencode-models', () => ({
resolveOpenCodeModel: mocks.resolveOpenCodeModel,
}))
vi.mock('../../src/services/sse-aggregator', () => ({
sseAggregator: {
onEvent: mocks.onEvent,
},
}))
vi.mock('../../src/utils/logger', () => ({
logger: {
error: mocks.loggerError,
info: vi.fn(),
warn: vi.fn(),
},
}))
const mockCronStop = vi.fn()
vi.mock('croner', () => ({
Cron: vi.fn().mockImplementation(() => ({ stop: mockCronStop })),
}))
import { ScheduleService } from '../../src/services/schedules'
import type { ForwardRequest, OpenCodeClient } from '../../src/services/opencode/client'
function jsonResponse(body: unknown, status: number = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'content-type': 'application/json' },
})
}
function textResponse(body: string, status: number = 200): Response {
return new Response(body, { status })
}
function createOpenCodeClientStub(): OpenCodeClient {
return {
forward: mocks.forward,
forwardRaw: vi.fn(async () => new Response('', { status: 200 })),
getJson: vi.fn(async () => ({}) as unknown),
postJson: vi.fn(async () => ({}) as unknown),
setProviderAuth: vi.fn(async () => true),
deleteProviderAuth: vi.fn(async () => true),
startMcpAuth: vi.fn(async () => new Response('', { status: 200 })),
authenticateMcp: vi.fn(async () => new Response('', { status: 200 })),
} as OpenCodeClient
}
function routeForward(handler: (req: ForwardRequest) => Promise<Response> | Response) {
mocks.forward.mockImplementation((req: ForwardRequest) => Promise.resolve(handler(req)))
}
const repo = {
id: 42,
fullPath: '/workspace/repos/sample-project',
localPath: 'sample-project',
repoUrl: 'https://github.com/example/sample-project',
}
const baseJob: ScheduleJob = {
id: 7,
repoId: 42,
name: 'Weekly engineering summary',
description: 'Summarize repo health and recent changes.',
enabled: true,
scheduleMode: 'interval',
intervalMinutes: 60,
cronExpression: null,
timezone: null,
agentSlug: null,
prompt: 'Review the repository and summarize the current state.',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
}
const baseRun: ScheduleRun = {
id: 5,
jobId: 7,
repoId: 42,
triggerSource: 'manual',
status: 'running',
startedAt: Date.UTC(2026, 2, 9, 12, 5, 0),
finishedAt: null,
createdAt: Date.UTC(2026, 2, 9, 12, 5, 0),
sessionId: null,
sessionTitle: null,
logText: null,
responseText: null,
errorText: null,
runBranch: null,
commitHash: null,
worktreePath: null,
workspaceId: null,
}
describe('ScheduleService permission ruleset in session creation', () => {
beforeEach(() => {
vi.clearAllMocks()
Reflect.get(ScheduleService, 'activeRuns').clear()
Reflect.get(ScheduleService, 'activeTeardowns')?.clear()
mocks.getRepoById.mockReturnValue(repo)
mocks.getRunningScheduleRunByJob.mockReturnValue(null)
mocks.createScheduleRun.mockReturnValue(baseRun)
mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', modelID: 'gpt-5-mini' })
mocks.onEvent.mockReturnValue(vi.fn())
mocks.getScheduleRunById.mockReturnValue({
...baseRun,
sessionId: 'ses-perm-test',
sessionTitle: 'Scheduled: Weekly engineering summary',
logText: 'Run started.',
})
})
it('sends default permission ruleset when job.permissionConfig is null', async () => {
mocks.getScheduleJobById.mockReturnValue(baseJob)
const runWithSession: ScheduleRun = {
...baseRun,
sessionId: 'ses-perm-1',
sessionTitle: 'Scheduled: Weekly engineering summary',
logText: 'Run started.',
}
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
routeForward(({ path, method }) => {
if (path === '/session' && method === 'POST') {
return jsonResponse({ id: 'ses-perm-1' })
}
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'POST') {
return textResponse('')
}
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'GET') {
return jsonResponse([{ info: { role: 'assistant', time: { completed: Date.now() } }, parts: [] }])
}
throw new Error(`Unexpected forward request: ${method} ${path}`)
})
const service = new ScheduleService({} as never, createOpenCodeClientStub(), mocks.stubWorktreeManager as never)
await service.runJob(42, 7, 'manual')
const sessionCall = mocks.forward.mock.calls.find(
([req]) => (req as ForwardRequest).path === '/session' && (req as ForwardRequest).method === 'POST',
)
expect(sessionCall).toBeDefined()
const body = JSON.parse((sessionCall![0] as ForwardRequest).body!)
expect(body.title).toBe('Scheduled: Weekly engineering summary')
expect(body.agent).toBeUndefined()
const expectedRules = buildSchedulePermissionRuleset(null)
expect(body.permission).toEqual(expectedRules)
})
it('sends custom permission ruleset when job has custom permissionConfig', async () => {
const customConfig = { allowExternalDirectory: true, bashDenyPatterns: [] }
mocks.getScheduleJobById.mockReturnValue({ ...baseJob, permissionConfig: customConfig })
const runWithSession: ScheduleRun = {
...baseRun,
sessionId: 'ses-perm-2',
sessionTitle: 'Scheduled: Weekly engineering summary',
logText: 'Run started.',
}
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
routeForward(({ path, method }) => {
if (path === '/session' && method === 'POST') {
return jsonResponse({ id: 'ses-perm-2' })
}
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'POST') {
return textResponse('')
}
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'GET') {
return jsonResponse([{ info: { role: 'assistant', time: { completed: Date.now() } }, parts: [] }])
}
throw new Error(`Unexpected forward request: ${method} ${path}`)
})
const service = new ScheduleService({} as never, createOpenCodeClientStub(), mocks.stubWorktreeManager as never)
await service.runJob(42, 7, 'manual')
const sessionCall = mocks.forward.mock.calls.find(
([req]) => (req as ForwardRequest).path === '/session' && (req as ForwardRequest).method === 'POST',
)
expect(sessionCall).toBeDefined()
const body = JSON.parse((sessionCall![0] as ForwardRequest).body!)
expect(body.title).toBe('Scheduled: Weekly engineering summary')
expect(body.agent).toBeUndefined()
const expectedRules = buildSchedulePermissionRuleset(customConfig)
expect(body.permission).toEqual(expectedRules)
})
it('preserves existing fields (title, agent) when permission is added', async () => {
mocks.getScheduleJobById.mockReturnValue({ ...baseJob, agentSlug: 'my-agent' })
const runWithSession: ScheduleRun = {
...baseRun,
sessionId: 'ses-perm-3',
sessionTitle: 'Scheduled: Weekly engineering summary',
logText: 'Run started.',
}
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
routeForward(({ path, method }) => {
if (path === '/session' && method === 'POST') {
return jsonResponse({ id: 'ses-perm-3' })
}
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'POST') {
return textResponse('')
}
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'GET') {
return jsonResponse([{ info: { role: 'assistant', time: { completed: Date.now() } }, parts: [] }])
}
throw new Error(`Unexpected forward request: ${method} ${path}`)
})
const service = new ScheduleService({} as never, createOpenCodeClientStub(), mocks.stubWorktreeManager as never)
await service.runJob(42, 7, 'manual')
const sessionCall = mocks.forward.mock.calls.find(
([req]) => (req as ForwardRequest).path === '/session' && (req as ForwardRequest).method === 'POST',
)
expect(sessionCall).toBeDefined()
const body = JSON.parse((sessionCall![0] as ForwardRequest).body!)
expect(body.title).toBe('Scheduled: Weekly engineering summary')
expect(body.agent).toBe('my-agent')
expect(body.permission).toBeDefined()
expect(body.permission['*']).toBe('allow')
})
})
+13 -6
View File
@@ -154,6 +154,7 @@ const job: ScheduleJob = {
prompt: 'Review the repository and summarize the current state.',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
@@ -178,6 +179,7 @@ const baseRun: ScheduleRun = {
runBranch: null,
commitHash: null,
worktreePath: null,
workspaceId: null,
}
describe('ScheduleService', () => {
@@ -1412,6 +1414,7 @@ describe('ScheduleRunner', () => {
prompt: 'Test',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: Date.now(),
lastRunAt: null,
@@ -1447,6 +1450,7 @@ describe('ScheduleRunner', () => {
prompt: 'Test',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: Date.now(),
lastRunAt: null,
@@ -1480,6 +1484,7 @@ describe('ScheduleRunner', () => {
prompt: 'Test',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: Date.now(),
lastRunAt: null,
@@ -1512,6 +1517,7 @@ describe('ScheduleRunner', () => {
prompt: 'Test',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: Date.now(),
lastRunAt: null,
@@ -1544,6 +1550,7 @@ describe('ScheduleRunner', () => {
prompt: 'Test',
model: null,
skillMetadata: null,
permissionConfig: null,
branch: null,
nextRunAt: Date.now(),
lastRunAt: null,
@@ -1581,17 +1588,17 @@ describe('ScheduleService run history cleanup', () => {
it('clearRunHistory prunes finished runs and skips a running run', async () => {
mocks.listScheduleRunArtifactsByJob.mockReturnValue([
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null },
{ id: 2, status: 'running', runBranch: 'schedule/7/run-2', worktreePath: '/wt/2' },
{ id: 1, status: 'failed', runBranch: null, worktreePath: null },
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null, workspaceId: null },
{ id: 2, status: 'running', runBranch: 'schedule/7/run-2', worktreePath: '/wt/2', workspaceId: null },
{ id: 1, status: 'failed', runBranch: null, worktreePath: null, workspaceId: null },
])
mocks.deleteScheduleRunsByIds.mockReturnValue(2)
const result = await makeService().clearRunHistory(42, 7)
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, [
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null },
{ id: 1, status: 'failed', runBranch: null, worktreePath: null },
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null, workspaceId: null },
{ id: 1, status: 'failed', runBranch: null, worktreePath: null, workspaceId: null },
])
expect(mocks.deleteScheduleRunsByIds).toHaveBeenCalledWith({}, 42, 7, [3, 1])
expect(result).toEqual({ cleared: 2 })
@@ -1616,7 +1623,7 @@ describe('ScheduleService run history cleanup', () => {
await makeService().deleteRun(42, 7, 5)
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, [
{ runBranch: 'schedule/7/run-5', worktreePath: '/wt/5' },
{ runBranch: 'schedule/7/run-5', worktreePath: '/wt/5', workspaceId: null },
])
expect(mocks.deleteScheduleRunById).toHaveBeenCalledWith({}, 42, 7, 5)
})