diff --git a/backend/src/routes/internal/index.ts b/backend/src/routes/internal/index.ts index 4ca67c54..9d58bafe 100644 --- a/backend/src/routes/internal/index.ts +++ b/backend/src/routes/internal/index.ts @@ -49,7 +49,7 @@ export function createInternalRoutes( repos.route('/', createInternalRepoRoutes(db, settingsService, gitAuthService)) repos.route('/:id/schedules', createScheduleRoutes(scheduleService)) repos.route('/', createInternalRepoSyncRoutes(db)) - repos.route('/', mirrorRoutes(db)) + repos.route('/', mirrorRoutes(db, openCodeClient, gitAuthService, repoWorkspaces)) app.route('/repos', repos) app.route('/opencode-workspaces', createInternalOpenCodeWorkspacesRoutes(db)) app.route('/sessions', createInternalSessionRoutes(db, openCodeClient, permissionModes, repoWorkspaces)) diff --git a/backend/src/routes/internal/repo-mirror.ts b/backend/src/routes/internal/repo-mirror.ts index 817b1573..a2f2fb12 100644 --- a/backend/src/routes/internal/repo-mirror.ts +++ b/backend/src/routes/internal/repo-mirror.ts @@ -10,11 +10,25 @@ import * as fsp from 'fs/promises' import { getReposPath } from '@opencode-manager/shared/config/env' import { MirrorTargetBranchRequestSchema, - type MirrorTargetEnsureResponse, - type MirrorTargetPlanResponse, + type MirrorCheckoutState, + type MirrorMoveTargetResponse, + type MirrorWorktreeCreateResponse, } from '@opencode-manager/shared/schemas' +import { isWorktreeSibling, sanitizeRepoDirectoryName } from '@opencode-manager/shared/utils' +import type { Repo } from '@opencode-manager/shared/types' import { getRepoById, updateLastPulled, updateRepoBranch, deleteRepo } from '../../db/queries' -import { ensureMirrorTargetPath, createRepoRow, isRepoInUse, planMirrorTarget, ensureMirrorTarget } from '../../services/repo' +import { + ensureMirrorTargetPath, + createRepoRow, + isDirectoryInUse, + isRepoInUse, + getSiblingRepos, + listGitWorktrees, + resolveRepoWorkingDirectory, +} from '../../services/repo' +import type { RepoWorkspaceService } from '../../services/repo-workspace' +import type { GitAuthService } from '../../services/git-auth' +import type { OpenCodeClient } from '../../services/opencode/client' import { logger } from '../../utils/logger' import { getErrorMessage } from '../../utils/error-utils' import { mkdirSyncSafe } from '../../utils/fs-safe' @@ -55,6 +69,7 @@ interface PatchBody { baseHead?: string | null patch?: string force?: boolean + directory?: string } const LEGACY_UPGRADE_MESSAGE = 'this ocm CLI is too old for this server; upgrade to ocm-cli >= 0.1.2 (the mirror upload protocol changed to chunked uploads)' @@ -127,7 +142,52 @@ async function listLocalBranchNames(fullPath: string): Promise> { return new Set(out.split('\n').map((l) => l.trim()).filter(Boolean)) } -async function importBundle(fullPath: string, bundlePath: string, branch: string | null, requireCurrentBranch: boolean, force: boolean): Promise { +async function checkoutState(directory: string): Promise { + const branch = await safeGitOut(directory, ['symbolic-ref', '--quiet', '--short', 'HEAD']) + const head = await safeGitOut(directory, ['rev-parse', 'HEAD']) + const status = await safeGitOut(directory, ['status', '--porcelain', '--untracked-files=all']) + return { + directory, + branch: branch?.trim() || null, + head: head?.trim() || null, + dirty: (status?.trim().length ?? 0) > 0, + } +} + +async function listMirrorWorktreeSiblings( + db: Database, + repo: Repo, + gitAuthService: GitAuthService, + openCodeClient: OpenCodeClient, +): Promise> { + const siblings = await getSiblingRepos(db, repo.id, gitAuthService.getGitEnvironment(), openCodeClient, { includeBranch: false }) + return siblings.filter((sibling) => isWorktreeSibling(sibling) && sibling.worktreeSource !== 'schedule') +} + +async function resolveMirrorDirectory( + db: Database, + repo: Repo, + directory: string | undefined, + gitAuthService: GitAuthService, + openCodeClient: OpenCodeClient, +): Promise { + return resolveRepoWorkingDirectory(repo, directory, () => + listMirrorWorktreeSiblings(db, repo, gitAuthService, openCodeClient), + ) +} + +function nextWorktreeBranch(branch: string, localBranches: Set, checkedOut: Set): string { + if (!checkedOut.has(branch)) return branch + let candidate = `${branch}-ocm` + let suffix = 2 + while (localBranches.has(candidate) || checkedOut.has(candidate)) { + candidate = `${branch}-ocm-${suffix}` + suffix += 1 + } + return candidate +} + +async function importBundle(fullPath: string, bundlePath: string, branch: string | null, requireCurrentBranch: boolean, force: boolean, targetBranch: string | null = branch): Promise { await gitRaw(fullPath, ['fetch', bundlePath, '+refs/heads/*:refs/remotes/ocm-sync/*', '+refs/tags/*:refs/tags/*']) try { const refs = await gitRaw(fullPath, ['for-each-ref', '--format=%(refname:strip=3) %(objectname)', 'refs/remotes/ocm-sync']) @@ -149,26 +209,28 @@ async function importBundle(fullPath: string, bundlePath: string, branch: string if (branch) { const incomingSha = incoming.get(branch) if (!incomingSha) throw new Error(`incoming bundle has no branch '${branch}'`) - if (locked.has(branch)) { - throw new Error(`branch '${branch}' is checked out in another worktree; release it there before pushing`) + const target = targetBranch ?? branch + if (locked.has(target)) { + throw new Error(`branch '${target}' is checked out in another worktree; release it there before pushing`) } - if (requireCurrentBranch && actualBranch !== branch) { - throw new Error(`repo is on branch '${actualBranch ?? 'detached HEAD'}' but the bundle targets '${branch}'`) + if (requireCurrentBranch && actualBranch !== target) { + throw new Error(`repo is on branch '${actualBranch ?? 'detached HEAD'}' but the bundle targets '${target}'`) } targetSha = incomingSha - if (actualBranch !== branch) { + if (actualBranch !== target) { const checkoutArgs = force ? ['-f'] : [] - if ((await listLocalBranchNames(fullPath)).has(branch)) { - await gitRaw(fullPath, ['checkout', ...checkoutArgs, branch]) + if ((await listLocalBranchNames(fullPath)).has(target)) { + await gitRaw(fullPath, ['checkout', ...checkoutArgs, target]) } else { - await gitRaw(fullPath, ['checkout', ...checkoutArgs, '-b', branch, incomingSha]) + await gitRaw(fullPath, ['checkout', ...checkoutArgs, '-b', target, incomingSha]) } } } + const skipRef = targetBranch ?? branch const updates: string[] = [] for (const [name, sha] of incoming) { - if (targetSha !== undefined && name === branch) continue + if (skipRef !== null && name === skipRef) continue if (locked.has(name)) continue updates.push(`update refs/heads/${name} ${sha}\n`) } @@ -198,7 +260,12 @@ async function createBundle(fullPath: string): Promise { return bundlePath } -export function createInternalRepoMirrorRoutes(db: Database) { +export function createInternalRepoMirrorRoutes( + db: Database, + openCodeClient: OpenCodeClient, + gitAuthService: GitAuthService, + repoWorkspaces: RepoWorkspaceService, +) { const app = new Hono() app.post('/:repoId/mirror', (c) => { @@ -398,8 +465,12 @@ export function createInternalRepoMirrorRoutes(db: Database) { if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400) const repo = getRepoById(db, repoId) if (!repo) return c.json({ error: 'repo not found' }, 404) + + const directory = await resolveMirrorDirectory(db, repo, c.req.query('directory'), gitAuthService, openCodeClient) + if (!directory) return c.json({ error: 'Directory is not part of this repository' }, 400) + const force = c.req.query('force') === '1' - if (isRepoInUse(db, repoId) && !force) { + if (isDirectoryInUse(directory) && !force) { return c.json({ error: 'repo_in_use', message: 'open OpenCode sessions are using this repo; rerun with force=1' }, 409) } @@ -411,21 +482,24 @@ export function createInternalRepoMirrorRoutes(db: Database) { const bundleDir = mkdtempSync(join(stagingRoot, 'bundle-upload-')) const bundlePath = join(bundleDir, 'repo.bundle') const branch = c.req.header('x-ocm-branch')?.trim() || null + const targetBranch = c.req.header('x-ocm-target-branch')?.trim() || branch const requireCurrentBranch = c.req.header('x-ocm-require-current-branch')?.trim() === '1' try { const body = Readable.fromWeb(rawBody as unknown as Parameters[0]) await pipeline(body, createWriteStream(bundlePath)) - await importBundle(repo.fullPath, bundlePath, branch, requireCurrentBranch, force) + await importBundle(directory, bundlePath, branch, requireCurrentBranch, force, targetBranch) - const branchName = await safeGitOut(repo.fullPath, ['rev-parse', '--abbrev-ref', 'HEAD']) - const head = await safeGitOut(repo.fullPath, ['rev-parse', 'HEAD']) - if (branchName) updateRepoBranch(db, repoId, branchName.trim()) - updateLastPulled(db, repoId) + const branchName = await safeGitOut(directory, ['rev-parse', '--abbrev-ref', 'HEAD']) + const head = await safeGitOut(directory, ['rev-parse', 'HEAD']) + if (directory === repo.fullPath) { + if (branchName) updateRepoBranch(db, repoId, branchName.trim()) + updateLastPulled(db, repoId) + } return c.json({ repoId, - fullPath: repo.fullPath, + fullPath: directory, branch: branchName?.trim() || null, head: head?.trim() || null, created: false, @@ -448,18 +522,35 @@ export function createInternalRepoMirrorRoutes(db: Database) { if (!repo) return c.json({ error: 'repo not found' }, 404) try { - const plan = await planMirrorTarget(db, repo, branch) - const response: MirrorTargetPlanResponse = plan.kind === 'new' - ? { kind: plan.kind, repoId: null, fullPath: plan.fullPath, localPath: plan.localPath, branch, currentBranch: plan.currentBranch } - : { kind: plan.kind, repoId: plan.repo.id, fullPath: plan.repo.fullPath, localPath: plan.repo.localPath, branch, currentBranch: plan.currentBranch } + const main = await checkoutState(repo.fullPath) + const siblings = await listMirrorWorktreeSiblings(db, repo, gitAuthService, openCodeClient) + let branchWorktree: MirrorCheckoutState | null = null + for (const sibling of siblings) { + const state = await checkoutState(sibling.fullPath) + if (state.branch === branch) { + branchWorktree = state + break + } + } + + const gitWorktrees = await listGitWorktrees(repo.fullPath, gitAuthService.getGitEnvironment()) + const checkedOut = new Set( + gitWorktrees.map((worktree) => worktree.branch).filter((name): name is string => name !== null), + ) + const localBranches = await listLocalBranchNames(repo.fullPath) + const response: MirrorMoveTargetResponse = { + main, + branchWorktree, + newWorktreeBranch: nextWorktreeBranch(branch, localBranches, checkedOut), + } return c.json(response) } catch (error) { - logger.error('mirror target plan failed:', error) + logger.error('mirror target resolution failed:', error) return c.json({ error: getErrorMessage(error) }, 500) } }) - app.post('/:repoId/mirror/target', async (c) => { + app.post('/:repoId/mirror/worktree', async (c) => { const repoId = Number(c.req.param('repoId')) if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400) let json: unknown @@ -474,18 +565,17 @@ export function createInternalRepoMirrorRoutes(db: Database) { const repo = getRepoById(db, repoId) if (!repo) return c.json({ error: 'repo not found' }, 404) + const gitWorktrees = await listGitWorktrees(repo.fullPath, gitAuthService.getGitEnvironment()) + if (gitWorktrees.some((worktree) => worktree.branch === branch)) { + return c.json({ error: 'branch_in_use', message: `branch '${branch}' is checked out in a worktree of this repository` }, 409) + } + try { - const { repo: target, created } = await ensureMirrorTarget(db, repo, branch) - const response: MirrorTargetEnsureResponse = { - repoId: target.id, - fullPath: target.fullPath, - localPath: target.localPath, - branch, - created, - } + const worktree = await repoWorkspaces.create(repo, { name: sanitizeRepoDirectoryName(branch, 'move') }) + const response: MirrorWorktreeCreateResponse = { directory: worktree.directory, branch } return c.json(response) } catch (error) { - logger.error('mirror target ensure failed:', error) + logger.error('mirror worktree create failed:', error) return c.json({ error: getErrorMessage(error) }, 409) } }) @@ -497,14 +587,12 @@ export function createInternalRepoMirrorRoutes(db: Database) { const repo = getRepoById(db, repoId) if (!repo) return c.json({ error: 'repo not found' }, 404) - const branchName = await safeGitOut(repo.fullPath, ['rev-parse', '--abbrev-ref', 'HEAD']) - const head = await safeGitOut(repo.fullPath, ['rev-parse', 'HEAD']) - const status = await safeGitOut(repo.fullPath, ['status', '--porcelain', '--untracked-files=all']) + const state = await checkoutState(repo.fullPath) return c.json({ repoId: repo.id, - branch: branchName?.trim() || null, - head: head?.trim() || null, - dirty: (status?.trim().length ?? 0) > 0, + branch: state.branch, + head: state.head, + dirty: state.dirty, }) }) @@ -559,29 +647,38 @@ export function createInternalRepoMirrorRoutes(db: Database) { const repo = getRepoById(db, repoId) if (!repo) return c.json({ error: 'repo not found' }, 404) if (!body.patch && body.patch !== '') return c.json({ error: 'patch required' }, 400) - if (body.force !== true && isRepoInUse(db, repoId)) { + if (body.directory !== undefined && typeof body.directory !== 'string') { + return c.json({ error: 'Directory is not part of this repository' }, 400) + } + + const directory = await resolveMirrorDirectory(db, repo, body.directory, gitAuthService, openCodeClient) + if (!directory) return c.json({ error: 'Directory is not part of this repository' }, 400) + + if (body.force !== true && isDirectoryInUse(directory)) { return c.json({ error: 'repo_in_use', message: 'open OpenCode sessions are using this repo; rerun with force=1' }, 409) } try { - const currentHead = await safeGitOut(repo.fullPath, ['rev-parse', 'HEAD']) + const currentHead = await safeGitOut(directory, ['rev-parse', 'HEAD']) const currentHeadTrimmed = currentHead?.trim() || null const baseHead = body.baseHead?.trim() || null if (baseHead && currentHeadTrimmed && baseHead !== currentHeadTrimmed) { return c.json({ error: 'head_mismatch', message: 'Manager repo HEAD differs from patch base' }, 409) } - await applyMirrorPatch(repo.fullPath, body.patch) + await applyMirrorPatch(directory, body.patch) - const branchName = await safeGitOut(repo.fullPath, ['rev-parse', '--abbrev-ref', 'HEAD']) - const head = await safeGitOut(repo.fullPath, ['rev-parse', 'HEAD']) + const branchName = await safeGitOut(directory, ['rev-parse', '--abbrev-ref', 'HEAD']) + const head = await safeGitOut(directory, ['rev-parse', 'HEAD']) - if (branchName) updateRepoBranch(db, repoId, branchName.trim()) - updateLastPulled(db, repoId) + if (directory === repo.fullPath) { + if (branchName) updateRepoBranch(db, repoId, branchName.trim()) + updateLastPulled(db, repoId) + } return c.json({ repoId, - fullPath: repo.fullPath, + fullPath: directory, branch: branchName?.trim() || null, head: head?.trim() || null, created: false, diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index 4b8ba817..0ba58b88 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -7,7 +7,7 @@ import type { Database } from 'bun:sqlite' import type { Repo, CreateRepoInput } from '../types/repo' import { logger } from '../utils/logger' import { getReposPath } from '@opencode-manager/shared/config/env' -import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, getRepoBaseDirectoryName, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, SCP_STYLE_URL_PATTERN, ASSISTANT_REPO_ID, type RepoSibling, type RepoWorktreeSource } from '@opencode-manager/shared/utils' +import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, SCP_STYLE_URL_PATTERN, ASSISTANT_REPO_ID, type RepoSibling, type RepoWorktreeSource } from '@opencode-manager/shared/utils' import type { GitAuthService } from './git-auth' import { isGitHubHttpsUrl } from '../utils/git-auth' import path from 'path' @@ -1076,61 +1076,6 @@ export async function createWorktreeSafely(baseRepoPath: string, worktreePath: s } } -export type MirrorTargetPlan = - | { kind: 'in-place'; repo: Repo; currentBranch: string | null } - | { kind: 'existing'; repo: Repo; currentBranch: string | null } - | { kind: 'new'; localPath: string; fullPath: string; currentBranch: string | null } - -export async function planMirrorTarget(database: Database, repo: Repo, branch: string): Promise { - const currentBranch = await safeGetCurrentBranch(repo.fullPath, {}) - if (currentBranch === branch) return { kind: 'in-place', repo, currentBranch } - - const localPath = `${getRepoBaseDirectoryName(repo)}-${sanitizeBranchForDirectory(branch)}` - const fullPath = path.join(getReposPath(), localPath) - const existing = getRepoByLocalPath(database, localPath) - - if (existing) { - if (existing.branch !== branch) { - throw new Error(`Mirror target '${localPath}' is occupied by repo ${existing.id} registered for branch '${existing.branch ?? 'none'}' instead of '${branch}'`) - } - - if (!existsSync(existing.fullPath)) { - throw new Error(`Repo ${existing.id} for branch '${branch}' is missing its worktree directory at '${existing.fullPath}'`) - } - - const checkedOutBranch = await safeGetCurrentBranch(existing.fullPath, {}) - if (checkedOutBranch !== branch) { - throw new Error(`Repo ${existing.id} for branch '${branch}' has branch '${checkedOutBranch ?? 'none'}' checked out at '${existing.fullPath}'`) - } - - return { kind: 'existing', repo: existing, currentBranch } - } - - return { kind: 'new', localPath, fullPath, currentBranch } -} - -export async function ensureMirrorTarget(database: Database, repo: Repo, branch: string): Promise<{ repo: Repo; created: boolean }> { - const plan = await planMirrorTarget(database, repo, branch) - if (plan.kind !== 'new') return { repo: plan.repo, created: false } - - await createWorktreeSafely(repo.fullPath, plan.fullPath, branch, {}) - - try { - const worktreeRepo = createRepo(database, repo.repoUrl - ? { repoUrl: repo.repoUrl, localPath: plan.localPath, branch, defaultBranch: branch, cloneStatus: 'ready', clonedAt: Date.now(), isWorktree: true } - : { isLocal: true, localPath: plan.localPath, branch, defaultBranch: branch, cloneStatus: 'ready', clonedAt: Date.now(), isWorktree: true }) - - if (worktreeRepo.localPath !== plan.localPath) { - throw new Error(`branch ${branch} is already registered as repo ${worktreeRepo.id} at ${worktreeRepo.fullPath}`) - } - - return { repo: worktreeRepo, created: true } - } catch (error: unknown) { - await removeWorktree(repo.fullPath, plan.fullPath) - throw error - } -} - export function ensureMirrorTargetPath(name: string): { fullPath: string; localPath: string } { const slugified = name .toLowerCase() @@ -1181,13 +1126,17 @@ export function createRepoRow( return { repo, created: true } } +export function isDirectoryInUse(directory: string): boolean { + return sseAggregator.getActiveDirectories().includes(directory) +} + export function isRepoInUse(db: Database, repoId: number): boolean { const repo = getRepoById(db, repoId) if (!repo) { return false } - return sseAggregator.getActiveDirectories().includes(repo.fullPath) + return isDirectoryInUse(repo.fullPath) } export async function resolveRepoProjectId(openCodeClient: OpenCodeClient, directory: string): Promise { diff --git a/backend/test/routes/internal/repo-mirror.test.ts b/backend/test/routes/internal/repo-mirror.test.ts index a1897799..6e655846 100644 --- a/backend/test/routes/internal/repo-mirror.test.ts +++ b/backend/test/routes/internal/repo-mirror.test.ts @@ -4,6 +4,7 @@ import { spawnSync } from 'child_process' import { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'fs' import { join } from 'path' import { tmpdir } from 'os' +import { sanitizeRepoDirectoryName } from '@opencode-manager/shared/utils' const { mockGetActiveDirectories, mockGitOut, mockSafeGitOut, getTmpRoot, setTmpRoot } = vi.hoisted(() => { const mockGetActiveDirectories = vi.fn().mockReturnValue([]) @@ -55,17 +56,26 @@ vi.mock('../../../src/db/queries', () => ({ const mockEnsureMirrorTargetPath = vi.fn() const mockCreateRepoRow = vi.fn() const mockIsRepoInUse = vi.fn() -const mockPlanMirrorTarget = vi.fn() -const mockEnsureMirrorTarget = vi.fn() +const mockIsDirectoryInUse = vi.fn() +const mockResolveRepoWorkingDirectory = vi.fn() +const mockGetSiblingRepos = vi.fn() +const mockListGitWorktrees = vi.fn() vi.mock('../../../src/services/repo', () => ({ ensureMirrorTargetPath: (...args: unknown[]) => mockEnsureMirrorTargetPath(...args), createRepoRow: (...args: unknown[]) => mockCreateRepoRow(...args), isRepoInUse: (...args: unknown[]) => mockIsRepoInUse(...args), - planMirrorTarget: (...args: unknown[]) => mockPlanMirrorTarget(...args), - ensureMirrorTarget: (...args: unknown[]) => mockEnsureMirrorTarget(...args), + isDirectoryInUse: (...args: unknown[]) => mockIsDirectoryInUse(...args), + resolveRepoWorkingDirectory: (...args: unknown[]) => mockResolveRepoWorkingDirectory(...args), + getSiblingRepos: (...args: unknown[]) => mockGetSiblingRepos(...args), + listGitWorktrees: (...args: unknown[]) => mockListGitWorktrees(...args), })) +const mockGetGitEnvironment = vi.fn().mockReturnValue({}) +const mockGitAuthService = { getGitEnvironment: mockGetGitEnvironment } +const mockRepoWorkspaces = { create: vi.fn() } +const mockOpenCodeClient = {} + import { createInternalRepoMirrorRoutes } from '../../../src/routes/internal/repo-mirror' const CHUNK_SIZE = 8 * 1024 * 1024 @@ -148,11 +158,20 @@ describe('internal-repo-mirror routes', () => { setTmpRoot(tmpRootValue) mkdirSync(tmpRootValue, { recursive: true }) app = new Hono() - app.route('/api/internal/repos', createInternalRepoMirrorRoutes({} as any)) + app.route('/api/internal/repos', createInternalRepoMirrorRoutes({} as any, mockOpenCodeClient as any, mockGitAuthService as any, mockRepoWorkspaces as any)) mockGetActiveDirectories.mockReturnValue([]) mockEnsureMirrorTargetPath.mockReturnValue({ localPath: 'test-repo', fullPath: join(getTmpRoot(), 'test-repo') }) mockCreateRepoRow.mockImplementation((_db: any, input: any) => ({ repo: { id: 1, fullPath: input.fullPath, localPath: input.localPath }, created: true })) mockIsRepoInUse.mockReturnValue(false) + mockIsDirectoryInUse.mockReturnValue(false) + mockResolveRepoWorkingDirectory.mockImplementation(async (repo: any, directory: string | undefined) => { + if (directory === undefined || directory === repo.fullPath) return repo.fullPath + return null + }) + mockGetSiblingRepos.mockResolvedValue([]) + mockListGitWorktrees.mockResolvedValue([]) + mockGetGitEnvironment.mockReturnValue({}) + mockRepoWorkspaces.create.mockReset() mockGetRepoById.mockReturnValue(null) }) @@ -246,7 +265,7 @@ describe('internal-repo-mirror routes', () => { it('returns head, branch and dirty state for the manager repo', async () => { mockGetRepoById.mockReturnValue({ id: 7, fullPath: join(getTmpRoot(), 'repo7') }) mockSafeGitOut.mockImplementation((_path: string, args: string[]) => { - if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref') return Promise.resolve('feature\n') + if (args[0] === 'symbolic-ref') return Promise.resolve('feature\n') if (args[0] === 'rev-parse') return Promise.resolve('abc123\n') if (args[0] === 'status') return Promise.resolve(' M file.txt\n') return Promise.resolve(null) @@ -260,6 +279,21 @@ describe('internal-repo-mirror routes', () => { expect(json.dirty).toBe(true) }) + it('reports a detached HEAD as a null branch', async () => { + mockGetRepoById.mockReturnValue({ id: 9, fullPath: join(getTmpRoot(), 'repo9') }) + mockSafeGitOut.mockImplementation((_path: string, args: string[]) => { + if (args[0] === 'symbolic-ref') return Promise.resolve(null) + if (args[0] === 'rev-parse') return Promise.resolve('abc123\n') + if (args[0] === 'status') return Promise.resolve('') + return Promise.resolve(null) + }) + + const res = await app.request('/api/internal/repos/9/mirror/head') + expect(res.status).toBe(200) + const json = (await res.json()) as { branch: string | null } + expect(json.branch).toBeNull() + }) + it('reports a clean repo as not dirty', async () => { mockGetRepoById.mockReturnValue({ id: 8, fullPath: join(getTmpRoot(), 'repo8') }) mockSafeGitOut.mockImplementation((_path: string, args: string[]) => { @@ -447,6 +481,46 @@ describe('internal-repo-mirror routes', () => { expect(spawnSync('git', ['status', '--porcelain'], { cwd: baseDir, encoding: 'utf-8' }).stdout.trim()).toBe('') }) + it('checks out the target branch on a detached worktree while the main checkout keeps the source branch', async () => { + const sourceDir = initGitRepo('target-branch-source') + gitCommitFile(sourceDir, 'main.txt', 'source main\n') + gitCmd(sourceDir, ['checkout', '-b', 'feature']) + const incomingFeatureSha = gitCommitFile(sourceDir, 'feature.txt', 'source feature\n') + gitCmd(sourceDir, ['checkout', 'main']) + const bundle = makeBundle(sourceDir, 'target-branch') + + const baseDir = initGitRepo('target-branch-base') + gitCommitFile(baseDir, 'main.txt', 'base main\n') + gitCmd(baseDir, ['checkout', '-b', 'feature']) + const baseFeatureSha = gitCommitFile(baseDir, 'base-feature.txt', 'base feature\n') + + const worktreeDir = join(getTmpRoot(), 'target-branch-wt') + gitCmd(baseDir, ['worktree', 'add', '--detach', worktreeDir, baseFeatureSha]) + expect(currentBranchOf(worktreeDir)).toBe('HEAD') + + mockGetRepoById.mockReturnValue({ id: 1, fullPath: baseDir }) + mockResolveRepoWorkingDirectory.mockResolvedValue(worktreeDir) + + const res = await app.request(`/api/internal/repos/1/mirror/bundle?directory=${encodeURIComponent(worktreeDir)}`, { + method: 'POST', + body: bundle, + headers: { + 'content-type': 'application/octet-stream', + 'x-ocm-branch': 'feature', + 'x-ocm-target-branch': 'feature-ocm', + }, + }) + + expect(res.status).toBe(200) + expect(currentBranchOf(worktreeDir)).toBe('feature-ocm') + expect(revRef(worktreeDir, 'HEAD')).toBe(incomingFeatureSha) + expect(revRef(worktreeDir, 'refs/heads/feature-ocm')).toBe(incomingFeatureSha) + expect(currentBranchOf(baseDir)).toBe('feature') + expect(revRef(baseDir, 'refs/heads/feature')).toBe(baseFeatureSha) + expect(mockUpdateLastPulled).not.toHaveBeenCalled() + expect(mockUpdateRepoBranch).not.toHaveBeenCalled() + }) + function gitCmd(cwd: string, args: string[], input?: string) { return spawnSync('git', args, { cwd, encoding: 'utf-8', input }) } @@ -1138,98 +1212,123 @@ describe('internal-repo-mirror routes', () => { }) describe('GET /:repoId/mirror/target', () => { + let mainDir: string let repo: { id: number; fullPath: string; localPath: string } beforeEach(() => { - repo = { id: 1, fullPath: join(getTmpRoot(), 'test-repo'), localPath: 'test-repo' } + mainDir = join(getTmpRoot(), 'target-repo') + mkdirSync(mainDir, { recursive: true }) + spawnSync('git', ['init', '-b', 'main'], { cwd: mainDir, stdio: 'ignore' }) + repo = { id: 1, fullPath: mainDir, localPath: 'target-repo' } + mockGetRepoById.mockReturnValue(repo) }) - it('returns a new-worktree plan with repoId null when no worktree exists', async () => { - mockGetRepoById.mockReturnValue(repo) - mockPlanMirrorTarget.mockResolvedValue({ kind: 'new', localPath: 'test-repo-feature', fullPath: join(getTmpRoot(), 'test-repo-feature'), currentBranch: 'main' }) + function mockCheckoutStates(states: Record) { + mockSafeGitOut.mockImplementation(async (dir: string, args: string[]) => { + const state = states[dir] + if (!state) return null + if (args[0] === 'symbolic-ref') return state.branch + if (args[0] === 'rev-parse') return state.head + if (args[0] === 'status') return state.dirty ? ' M file.txt\n' : '' + return null + }) + } + + it('reports main state and the branch itself when it is not checked out anywhere', async () => { + mockGetSiblingRepos.mockResolvedValue([]) + mockListGitWorktrees.mockResolvedValue([{ path: mainDir, branch: 'main' }]) + mockCheckoutStates({ [mainDir]: { branch: 'main', head: 'abc', dirty: false } }) const res = await app.request('/api/internal/repos/1/mirror/target?branch=feature') expect(res.status).toBe(200) expect(await res.json()).toEqual({ - kind: 'new', - repoId: null, - fullPath: join(getTmpRoot(), 'test-repo-feature'), - localPath: 'test-repo-feature', - branch: 'feature', - currentBranch: 'main', + main: { directory: mainDir, branch: 'main', head: 'abc', dirty: false }, + branchWorktree: null, + newWorktreeBranch: 'feature', }) - expect(mockPlanMirrorTarget).toHaveBeenCalledWith({}, repo, 'feature') }) - it('returns an in-place plan with the repo id', async () => { - mockGetRepoById.mockReturnValue(repo) - mockPlanMirrorTarget.mockResolvedValue({ kind: 'in-place', repo, currentBranch: 'feature' }) + it('returns the worktree already sitting on the requested branch with its state', async () => { + const worktreeDir = join(getTmpRoot(), 'target-repo-feature') + mockGetSiblingRepos.mockResolvedValue([{ fullPath: worktreeDir, worktreeSource: 'opencode' }]) + mockListGitWorktrees.mockResolvedValue([{ path: mainDir, branch: 'main' }]) + mockCheckoutStates({ + [mainDir]: { branch: 'main', head: 'mainhead', dirty: false }, + [worktreeDir]: { branch: 'feature', head: 'wthead', dirty: true }, + }) const res = await app.request('/api/internal/repos/1/mirror/target?branch=feature') expect(res.status).toBe(200) - expect(await res.json()).toEqual({ - kind: 'in-place', - repoId: 1, - fullPath: repo.fullPath, - localPath: 'test-repo', + const json = (await res.json()) as { main: unknown; branchWorktree: unknown; newWorktreeBranch: string } + expect(json.branchWorktree).toEqual({ + directory: worktreeDir, branch: 'feature', - currentBranch: 'feature', + head: 'wthead', + dirty: true, }) + expect(json.newWorktreeBranch).toBe('feature') }) - it('returns an existing-worktree plan with the worktree repo id', async () => { - mockGetRepoById.mockReturnValue(repo) - const worktreeRepo = { id: 5, fullPath: join(getTmpRoot(), 'test-repo-wt'), localPath: 'test-repo-wt' } - mockPlanMirrorTarget.mockResolvedValue({ kind: 'existing', repo: worktreeRepo, currentBranch: 'main' }) + it('ignores schedule worktrees when matching the branch worktree', async () => { + const scheduleDir = join(getTmpRoot(), 'target-repo-schedule') + mockGetSiblingRepos.mockResolvedValue([{ fullPath: scheduleDir, worktreeSource: 'schedule' }]) + mockListGitWorktrees.mockResolvedValue([{ path: mainDir, branch: 'main' }]) + mockCheckoutStates({ + [mainDir]: { branch: 'main', head: 'mainhead', dirty: false }, + [scheduleDir]: { branch: 'feature', head: 'sched', dirty: false }, + }) const res = await app.request('/api/internal/repos/1/mirror/target?branch=feature') expect(res.status).toBe(200) - expect(await res.json()).toEqual({ - kind: 'existing', - repoId: 5, - fullPath: worktreeRepo.fullPath, - localPath: 'test-repo-wt', - branch: 'feature', - currentBranch: 'main', - }) + const json = (await res.json()) as { branchWorktree: unknown } + expect(json.branchWorktree).toBeNull() }) - it('returns 400 for a missing branch without calling the plan service', async () => { + it('suffixes the branch when it is already checked out in a worktree', async () => { + mockGetSiblingRepos.mockResolvedValue([]) + mockListGitWorktrees.mockResolvedValue([{ path: mainDir, branch: 'feature' }]) + mockCheckoutStates({ [mainDir]: { branch: 'feature', head: 'abc', dirty: false } }) + + const res = await app.request('/api/internal/repos/1/mirror/target?branch=feature') + + expect(res.status).toBe(200) + const json = (await res.json()) as { newWorktreeBranch: string } + expect(json.newWorktreeBranch).toBe('feature-ocm') + }) + + it('skips suffixed branch names that already exist locally', async () => { + spawnSync('git', ['config', 'user.email', 'test@test.com'], { cwd: mainDir, stdio: 'ignore' }) + spawnSync('git', ['config', 'user.name', 'Test'], { cwd: mainDir, stdio: 'ignore' }) + spawnSync('git', ['commit', '--allow-empty', '-m', 'init'], { cwd: mainDir, stdio: 'ignore' }) + spawnSync('git', ['branch', 'feature-ocm'], { cwd: mainDir, stdio: 'ignore' }) + spawnSync('git', ['branch', 'feature-ocm-2'], { cwd: mainDir, stdio: 'ignore' }) + mockGetSiblingRepos.mockResolvedValue([]) + mockListGitWorktrees.mockResolvedValue([{ path: mainDir, branch: 'feature' }]) + mockCheckoutStates({ [mainDir]: { branch: 'feature', head: 'abc', dirty: false } }) + + const res = await app.request('/api/internal/repos/1/mirror/target?branch=feature') + + expect(res.status).toBe(200) + const json = (await res.json()) as { newWorktreeBranch: string } + expect(json.newWorktreeBranch).toBe('feature-ocm-3') + }) + + it('returns 400 for a missing branch', async () => { const res = await app.request('/api/internal/repos/1/mirror/target') expect(res.status).toBe(400) const json = (await res.json()) as { error: string } expect(json.error).toBe('branch required') - expect(mockPlanMirrorTarget).not.toHaveBeenCalled() expect(mockGetRepoById).not.toHaveBeenCalled() }) - it('returns 400 for a whitespace-only branch without calling the plan service', async () => { - const res = await app.request('/api/internal/repos/1/mirror/target?branch=%20%20%20') - - expect(res.status).toBe(400) - const json = (await res.json()) as { error: string } - expect(json.error).toBe('branch required') - expect(mockPlanMirrorTarget).not.toHaveBeenCalled() - }) - - it('trims the branch before calling the plan service', async () => { - mockGetRepoById.mockReturnValue(repo) - mockPlanMirrorTarget.mockResolvedValue({ kind: 'in-place', repo, currentBranch: 'feature' }) - - await app.request('/api/internal/repos/1/mirror/target?branch=%20feature%20') - - expect(mockPlanMirrorTarget).toHaveBeenCalledWith({}, repo, 'feature') - }) - it('returns 400 for an invalid repoId', async () => { const res = await app.request('/api/internal/repos/abc/mirror/target?branch=feature') expect(res.status).toBe(400) - expect(mockPlanMirrorTarget).not.toHaveBeenCalled() }) it('returns 404 for a non-existent repo', async () => { @@ -1238,76 +1337,55 @@ describe('internal-repo-mirror routes', () => { const res = await app.request('/api/internal/repos/99999/mirror/target?branch=feature') expect(res.status).toBe(404) - expect(mockPlanMirrorTarget).not.toHaveBeenCalled() - }) - - it('returns 500 when planning fails', async () => { - mockGetRepoById.mockReturnValue(repo) - mockPlanMirrorTarget.mockRejectedValue(new Error('worktree occupied')) - - const res = await app.request('/api/internal/repos/1/mirror/target?branch=feature') - - expect(res.status).toBe(500) - const json = (await res.json()) as { error: string } - expect(json.error).toContain('worktree occupied') }) }) - describe('POST /:repoId/mirror/target', () => { + describe('POST /:repoId/mirror/worktree', () => { let repo: { id: number; fullPath: string; localPath: string } beforeEach(() => { repo = { id: 1, fullPath: join(getTmpRoot(), 'test-repo'), localPath: 'test-repo' } + mockGetRepoById.mockReturnValue(repo) }) async function request(branchBody: unknown): Promise { - const res = await app.request('/api/internal/repos/1/mirror/target', { + return app.request('/api/internal/repos/1/mirror/worktree', { method: 'POST', body: JSON.stringify(branchBody), headers: { 'content-type': 'application/json' }, }) - return res } - it('ensures the target and returns the target repo contract', async () => { - mockGetRepoById.mockReturnValue(repo) - const targetRepo = { id: 5, fullPath: join(getTmpRoot(), 'test-repo-wt'), localPath: 'test-repo-wt' } - mockEnsureMirrorTarget.mockResolvedValue({ repo: targetRepo, created: true }) + it('creates an OpenCode worktree named after the branch', async () => { + const worktreeDir = join(getTmpRoot(), 'feature-x') + mockListGitWorktrees.mockResolvedValue([{ path: repo.fullPath, branch: 'main' }]) + mockRepoWorkspaces.create.mockResolvedValue({ directory: worktreeDir, branch: 'feature/x' }) - const res = await request({ branch: 'feature' }) + const res = await request({ branch: 'feature/x' }) expect(res.status).toBe(200) - expect(await res.json()).toEqual({ - repoId: 5, - fullPath: targetRepo.fullPath, - localPath: 'test-repo-wt', - branch: 'feature', - created: true, - }) - expect(mockEnsureMirrorTarget).toHaveBeenCalledWith({}, repo, 'feature') + expect(await res.json()).toEqual({ directory: worktreeDir, branch: 'feature/x' }) + expect(mockRepoWorkspaces.create).toHaveBeenCalledWith(repo, { name: sanitizeRepoDirectoryName('feature/x', 'move') }) }) - it('reports created=false when the target already exists', async () => { - mockGetRepoById.mockReturnValue(repo) - mockEnsureMirrorTarget.mockResolvedValue({ repo, created: false }) + it('returns 409 when the branch is already checked out in a worktree', async () => { + mockListGitWorktrees.mockResolvedValue([{ path: repo.fullPath, branch: 'feature' }]) const res = await request({ branch: 'feature' }) - expect(res.status).toBe(200) - const json = (await res.json()) as { created: boolean; repoId: number } - expect(json.created).toBe(false) - expect(json.repoId).toBe(1) + expect(res.status).toBe(409) + expect(mockRepoWorkspaces.create).not.toHaveBeenCalled() }) it('returns 400 for malformed JSON body without calling services', async () => { - const res = await app.request('/api/internal/repos/1/mirror/target', { + const res = await app.request('/api/internal/repos/1/mirror/worktree', { method: 'POST', body: 'not json{', headers: { 'content-type': 'application/json' }, }) expect(res.status).toBe(400) - expect(mockEnsureMirrorTarget).not.toHaveBeenCalled() + expect(mockRepoWorkspaces.create).not.toHaveBeenCalled() expect(mockGetRepoById).not.toHaveBeenCalled() }) @@ -1317,46 +1395,18 @@ describe('internal-repo-mirror routes', () => { expect(res.status).toBe(400) const json = (await res.json()) as { error: string } expect(json.error).toBe('branch required') - expect(mockEnsureMirrorTarget).not.toHaveBeenCalled() - expect(mockGetRepoById).not.toHaveBeenCalled() - }) - - it.each([ - ['null branch', null], - ['numeric branch', 123], - ['object branch', { branch: 'feature' }], - ])('returns 400 for %s without calling services', async (_label, branchValue) => { - const res = await request({ branch: branchValue }) - - expect(res.status).toBe(400) - expect(mockEnsureMirrorTarget).not.toHaveBeenCalled() - }) - - it('returns 400 for a whitespace-only branch without calling services', async () => { - const res = await request({ branch: ' ' }) - - expect(res.status).toBe(400) - expect(mockEnsureMirrorTarget).not.toHaveBeenCalled() - }) - - it('trims the branch before calling the ensure service', async () => { - mockGetRepoById.mockReturnValue(repo) - mockEnsureMirrorTarget.mockResolvedValue({ repo, created: false }) - - await request({ branch: ' feature ' }) - - expect(mockEnsureMirrorTarget).toHaveBeenCalledWith({}, repo, 'feature') + expect(mockRepoWorkspaces.create).not.toHaveBeenCalled() }) it('returns 400 for an invalid repoId', async () => { - const res = await app.request('/api/internal/repos/abc/mirror/target', { + const res = await app.request('/api/internal/repos/abc/mirror/worktree', { method: 'POST', body: JSON.stringify({ branch: 'feature' }), headers: { 'content-type': 'application/json' }, }) expect(res.status).toBe(400) - expect(mockEnsureMirrorTarget).not.toHaveBeenCalled() + expect(mockRepoWorkspaces.create).not.toHaveBeenCalled() }) it('returns 404 for a non-existent repo', async () => { @@ -1365,18 +1415,50 @@ describe('internal-repo-mirror routes', () => { const res = await request({ branch: 'feature' }) expect(res.status).toBe(404) - expect(mockEnsureMirrorTarget).not.toHaveBeenCalled() + expect(mockRepoWorkspaces.create).not.toHaveBeenCalled() }) - it('returns 409 when ensure fails', async () => { - mockGetRepoById.mockReturnValue(repo) - mockEnsureMirrorTarget.mockRejectedValue(new Error('git worktree add failed')) + it('returns 409 when worktree creation fails', async () => { + mockListGitWorktrees.mockResolvedValue([{ path: repo.fullPath, branch: 'main' }]) + mockRepoWorkspaces.create.mockRejectedValue(new Error('worktree create failed')) const res = await request({ branch: 'feature' }) expect(res.status).toBe(409) const json = (await res.json()) as { error: string } - expect(json.error).toContain('git worktree add failed') + expect(json.error).toContain('worktree create failed') + }) + }) + + describe('mirror directory scoping', () => { + it('returns 400 when the bundle directory is not part of the repository', async () => { + mockGetRepoById.mockReturnValue({ id: 1, fullPath: join(getTmpRoot(), 'repo') }) + mockResolveRepoWorkingDirectory.mockResolvedValue(null) + + const res = await app.request('/api/internal/repos/1/mirror/bundle?directory=/elsewhere', { + method: 'POST', + body: Buffer.from('bundle'), + headers: { 'content-type': 'application/octet-stream' }, + }) + + expect(res.status).toBe(400) + const json = (await res.json()) as { error: string } + expect(json.error).toBe('Directory is not part of this repository') + }) + + it('returns 400 when the patch directory is not part of the repository', async () => { + mockGetRepoById.mockReturnValue({ id: 1, fullPath: join(getTmpRoot(), 'repo') }) + mockResolveRepoWorkingDirectory.mockResolvedValue(null) + + const res = await app.request('/api/internal/repos/1/mirror/patch', { + method: 'POST', + body: JSON.stringify({ patch: '', directory: '/elsewhere' }), + headers: { 'content-type': 'application/json' }, + }) + + expect(res.status).toBe(400) + const json = (await res.json()) as { error: string } + expect(json.error).toBe('Directory is not part of this repository') }) }) }) diff --git a/backend/test/services/repo-git.test.ts b/backend/test/services/repo-git.test.ts index d5c42331..1d77238e 100644 --- a/backend/test/services/repo-git.test.ts +++ b/backend/test/services/repo-git.test.ts @@ -774,41 +774,6 @@ describe('repo service real git', () => { }) describe('mirror helpers', () => { - it('plans and ensures a mirror worktree', async () => { - const { ensureMirrorTarget, planMirrorTarget } = await import('../../src/services/repo') - const baseName = uniqueName('mirror-base') - const basePath = path.join(reposPath, baseName) - createCommittedRepo(basePath) - const base = registerLocalRepo(baseName) - - const inPlace = await planMirrorTarget(db, base, 'main') - expect(inPlace.kind).toBe('in-place') - - const planned = await planMirrorTarget(db, base, 'feature/x') - expect(planned.kind).toBe('new') - - const created = await ensureMirrorTarget(db, base, 'feature/x') - expect(created.created).toBe(true) - expect(existsSync(created.repo.fullPath)).toBe(true) - - const existing = await ensureMirrorTarget(db, base, 'feature/x') - expect(existing.created).toBe(false) - expect(existing.repo.id).toBe(created.repo.id) - }) - - it('resolves the base directory name from a worktree repo row', async () => { - const { ensureMirrorTarget, planMirrorTarget } = await import('../../src/services/repo') - const baseName = uniqueName('mirror-name-base') - const basePath = path.join(reposPath, baseName) - createCommittedRepo(basePath) - const base = registerLocalRepo(baseName) - const created = await ensureMirrorTarget(db, base, 'feature/x') - - const planned = await planMirrorTarget(db, created.repo, 'other') - - expect(planned).toMatchObject({ kind: 'new', localPath: `${baseName}-other` }) - }) - it('creates a unique mirror target path', async () => { const { ensureMirrorTargetPath } = await import('../../src/services/repo') const name = uniqueName('Mirror Name') diff --git a/backend/test/services/repo-mirror-target.test.ts b/backend/test/services/repo-mirror-target.test.ts deleted file mode 100644 index eca8f6ee..00000000 --- a/backend/test/services/repo-mirror-target.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest' -import { execSync } from 'child_process' -import { mkdtempSync, existsSync } from 'fs' -import { tmpdir } from 'os' -import { join } from 'path' -import { rm } from 'fs/promises' -import type { Database } from 'bun:sqlite' -import type { Repo } from '../../src/types/repo' - -let tmpRoot: string -vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => { - const actual = await importOriginal() - return { - ...(actual as object), - getReposPath: () => tmpRoot, - getWorkspacePath: vi.fn(() => '/tmp/fake-workspace'), - } -}) - -describe('mirror target resolution', () => { - let db: Database - let base: Repo - let baseRepoPath: string - - beforeAll(async () => { - tmpRoot = mkdtempSync(join(tmpdir(), 'repo-mirror-target-')) - baseRepoPath = join(tmpRoot, 'my-app') - execSync(`git init -b main "${baseRepoPath}"`) - execSync(`git -C "${baseRepoPath}" config user.email test@test.com`) - execSync(`git -C "${baseRepoPath}" config user.name Test`) - execSync(`git -C "${baseRepoPath}" commit --allow-empty -m "Initial commit"`) - - const { createTestDb } = await import('../helpers/assistant-workspace') - const { createRepo } = await import('../../src/db/queries') - db = createTestDb() - base = createRepo(db, { isLocal: true, localPath: 'my-app', branch: 'main', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now() }) - }) - - afterAll(async () => { - await rm(tmpRoot, { recursive: true, force: true }) - }) - - it('targets the repo in place when its checked-out branch matches', async () => { - const { planMirrorTarget } = await import('../../src/services/repo') - const plan = await planMirrorTarget(db, base, 'main') - expect(plan.kind).toBe('in-place') - expect(plan.currentBranch).toBe('main') - }) - - it('plans a new sibling worktree when the checked-out branch differs', async () => { - const { planMirrorTarget } = await import('../../src/services/repo') - const plan = await planMirrorTarget(db, base, 'feature/x') - expect(plan).toMatchObject({ kind: 'new', localPath: 'my-app-feature-x', fullPath: join(tmpRoot, 'my-app-feature-x'), currentBranch: 'main' }) - }) - - it('creates the worktree, the branch, and a worktree repo row without touching the base checkout', async () => { - const { ensureMirrorTarget, planMirrorTarget } = await import('../../src/services/repo') - const { repo: target, created } = await ensureMirrorTarget(db, base, 'feature/x') - - expect(created).toBe(true) - expect(target.id).not.toBe(base.id) - expect(target.isWorktree).toBe(true) - expect(target.branch).toBe('feature/x') - expect(target.fullPath).toBe(join(tmpRoot, 'my-app-feature-x')) - expect(existsSync(target.fullPath)).toBe(true) - expect(execSync(`git -C "${target.fullPath}" rev-parse --abbrev-ref HEAD`, { encoding: 'utf-8' }).trim()).toBe('feature/x') - expect(execSync(`git -C "${baseRepoPath}" rev-parse --abbrev-ref HEAD`, { encoding: 'utf-8' }).trim()).toBe('main') - - const again = await planMirrorTarget(db, base, 'feature/x') - expect(again.kind).toBe('existing') - if (again.kind === 'existing') expect(again.repo.id).toBe(target.id) - - const second = await ensureMirrorTarget(db, base, 'feature/x') - expect(second.created).toBe(false) - expect(second.repo.id).toBe(target.id) - }) - - it('rejects a branch whose sanitized path is occupied by a worktree for another branch and preserves that worktree', async () => { - const { planMirrorTarget } = await import('../../src/services/repo') - const { getRepoByLocalPath } = await import('../../src/db/queries') - - const occupiedPath = join(tmpRoot, 'my-app-feature-x') - expect(existsSync(occupiedPath)).toBe(true) - - await expect(planMirrorTarget(db, base, 'feature-x')).rejects.toThrow(/occupied by repo .* 'feature\/x' instead of 'feature-x'/) - - const ownerRow = getRepoByLocalPath(db, 'my-app-feature-x')! - expect(ownerRow.branch).toBe('feature/x') - expect(existsSync(occupiedPath)).toBe(true) - expect(execSync(`git -C "${occupiedPath}" rev-parse --abbrev-ref HEAD`, { encoding: 'utf-8' }).trim()).toBe('feature/x') - }) - - it('rejects an existing row matching the branch when its directory has a different branch checked out', async () => { - const { planMirrorTarget } = await import('../../src/services/repo') - const { createRepo } = await import('../../src/db/queries') - - const stalePath = join(tmpRoot, 'my-app-stale') - execSync(`git clone "${baseRepoPath}" "${stalePath}"`) - expect(execSync(`git -C "${stalePath}" rev-parse --abbrev-ref HEAD`, { encoding: 'utf-8' }).trim()).toBe('main') - - createRepo(db, { isLocal: true, localPath: 'my-app-stale', branch: 'stale', defaultBranch: 'stale', cloneStatus: 'ready', clonedAt: Date.now() }) - - await expect(planMirrorTarget(db, base, 'stale')).rejects.toThrow(/has branch 'main' checked out at/) - expect(existsSync(stalePath)).toBe(true) - }) - - it('rejects an existing row matching the branch when its worktree directory is missing', async () => { - const { planMirrorTarget } = await import('../../src/services/repo') - const { createRepo } = await import('../../src/db/queries') - - createRepo(db, { isLocal: true, localPath: 'my-app-ghost', branch: 'ghost', defaultBranch: 'ghost', cloneStatus: 'ready', clonedAt: Date.now() }) - - await expect(planMirrorTarget(db, base, 'ghost')).rejects.toThrow(/missing its worktree directory/) - expect(existsSync(join(tmpRoot, 'my-app-ghost'))).toBe(false) - }) - - it('removes the created worktree and rethrows when registration fails', async () => { - const { ensureMirrorTarget } = await import('../../src/services/repo') - const { getRepoByLocalPath } = await import('../../src/db/queries') - - db.exec(`CREATE TRIGGER fail_mirror_repo_insert BEFORE INSERT ON repos - WHEN NEW.local_path = 'my-app-feature-fail' - BEGIN - SELECT RAISE(ABORT, 'registration failed'); - END;`) - - try { - const failedPath = join(tmpRoot, 'my-app-feature-fail') - await expect(ensureMirrorTarget(db, base, 'feature/fail')).rejects.toThrow(/registration failed/) - - expect(existsSync(failedPath)).toBe(false) - expect(execSync(`git -C "${baseRepoPath}" worktree list`, { encoding: 'utf-8' })).not.toContain('feature-fail') - expect(getRepoByLocalPath(db, 'my-app-feature-fail')).toBeNull() - } finally { - db.exec('DROP TRIGGER fail_mirror_repo_insert') - } - }) - - it('resolves the base directory name when asked from a worktree repo row', async () => { - const { planMirrorTarget } = await import('../../src/services/repo') - const { getRepoByLocalPath } = await import('../../src/db/queries') - const worktreeRepo = getRepoByLocalPath(db, 'my-app-feature-x')! - const plan = await planMirrorTarget(db, worktreeRepo, 'other') - expect(plan).toMatchObject({ kind: 'new', localPath: 'my-app-other' }) - }) -}) diff --git a/ocm-cli/README.md b/ocm-cli/README.md index beadfda3..b443c618 100644 --- a/ocm-cli/README.md +++ b/ocm-cli/README.md @@ -141,23 +141,24 @@ package export. Configure the package name and OpenCode resolves that TUI entrypoint automatically. When attached to a Manager via `ocm`, the plugin shows a ` ยท ` indicator in the prompt and home footers; local launches show nothing. It registers `/ocm-move`, which keeps the local session and -copies the active session to the Manager after replacing the Manager repo's -working tree with your local one (commits, staged, unstaged, and untracked -files; gitignored files on the Manager are preserved). The Manager's current -checkout is never switched: if it is on your branch the repo is replaced in -place; otherwise your branch goes into a sibling worktree (`-`, -registered as its own Manager repo), created on demand if it does not exist -yet. When multiple Manager repos match, the one already on your branch is -chosen; otherwise a picker dialog lets you choose. A confirmation dialog gates -the move before any push, states where the state will land, and lists any -server-side work (uncommitted changes or commits not present locally) that will -be discarded there. The session moves by exporting it from the local OpenCode 2 -server and importing it through the Manager proxy, followed by a synthetic -reminder. While the move runs, a spinner with the current phase and a -progress bar is shown next to the prompt. On success -you can optionally warp โ€” exit the local TUI and attach to the moved session -on the Manager immediately. Use it from inside an OpenCode session after -`ocm login` and after the repo already exists on the Manager +copies the active session to the Manager after pushing your local working tree +(commits, staged, unstaged, and untracked files; gitignored files on the Manager +are preserved). Server-side work is never discarded. The Manager checkout is +replaced in place only when it is already on your branch, clean, and has nothing +your local branch lacks; otherwise the push lands in an OpenCode worktree of the +same Manager repo โ€” reusing an existing clean OpenCode worktree on your branch +when one exists, or creating a new OpenCode worktree. When your branch is already +checked out on the server, the new worktree uses a suffixed `-ocm` +branch, and the server checkout is left untouched. A detached HEAD is refused +before anything is pushed. When multiple Manager repos match, the one already on +your branch is chosen; otherwise a picker dialog lets you choose. A confirmation +dialog gates the move before any push and states the destination path and branch. +The session moves by exporting it from the local OpenCode 2 server and importing +it through the Manager proxy, followed by a synthetic reminder. While the move +runs, a spinner with the current phase and a progress bar is shown next to the +prompt. On success you can optionally warp โ€” exit the local TUI and attach to +the moved session on the Manager immediately. Use it from inside an OpenCode +session after `ocm login` and after the repo already exists on the Manager (`ocm push --create` if needed). It refuses, before pushing anything, a session that is already on the Manager and a subagent session whose parent is not. @@ -169,7 +170,8 @@ that is already attached, the picker offers the other Manager repos (the current one is listed as disabled) and **Local opencode**, which stays available even when the Manager cannot be reached. Switching exits the TUI and reattaches; switching to a repo also remembers it as the last repo. The current -session stays where it is (use `/ocm-move` to bring a local session along). +session stays where it is (use `/ocm-move` to push your local state and bring a +local session along). The plugin also registers two Manager-backed commands, both of which need an attached Manager repo through `ocm`: diff --git a/ocm-cli/src/manager-api.ts b/ocm-cli/src/manager-api.ts index 366afe73..1c9fbc97 100644 --- a/ocm-cli/src/manager-api.ts +++ b/ocm-cli/src/manager-api.ts @@ -1,14 +1,14 @@ import { createReadStream } from 'fs' import { Readable } from 'stream' import { - MirrorTargetEnsureResponseSchema, - MirrorTargetPlanResponseSchema, + MirrorMoveTargetResponseSchema, + MirrorWorktreeCreateResponseSchema, MultiRunSchema, SessionGoalSchema, type FuseMultiRunRequest, type LaunchMultiRunRequest, - type MirrorTargetEnsureResponse, - type MirrorTargetPlanResponse, + type MirrorMoveTargetResponse, + type MirrorWorktreeCreateResponse, type MultiRun, type SessionGoal, type StartSessionGoalRequest, @@ -244,11 +244,16 @@ export class ManagerApi { return res.body! } - async mirrorPatch(repoId: number, body: { baseHead: string | null; patch: string; force?: boolean }): Promise { + async mirrorPatch( + repoId: number, + body: { baseHead: string | null; patch: string; force?: boolean; directory?: string }, + ): Promise { + const payload: Record = { baseHead: body.baseHead, patch: body.patch, force: body.force === true } + if (body.directory) payload.directory = body.directory const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/patch`, { method: 'POST', headers: { ...this.headers(), 'Content-Type': 'application/json' }, - body: JSON.stringify({ baseHead: body.baseHead, patch: body.patch, force: body.force === true }), + body: JSON.stringify(payload), }) if (!res.ok) throw await formatErrorResponse(res, 'mirror patch') @@ -258,12 +263,23 @@ export class ManagerApi { async mirrorUploadBundle( repoId: number, bundlePath: string, - opts: { branch: string | null; force?: boolean; requireCurrentBranch?: boolean; onProgress?: (bytesSent: number) => void }, + opts: { + branch: string | null + force?: boolean + requireCurrentBranch?: boolean + directory?: string + targetBranch?: string + onProgress?: (bytesSent: number) => void + }, ): Promise { - const query = opts.force === true ? '?force=1' : '' + const params = new URLSearchParams() + if (opts.force === true) params.set('force', '1') + if (opts.directory) params.set('directory', opts.directory) + const query = params.size > 0 ? `?${params.toString()}` : '' const headers: Record = { ...this.headers(), 'Content-Type': 'application/octet-stream' } if (opts.branch) headers['X-OCM-Branch'] = opts.branch if (opts.requireCurrentBranch === true) headers['X-OCM-Require-Current-Branch'] = '1' + if (opts.targetBranch) headers['X-OCM-Target-Branch'] = opts.targetBranch const fileStream = Readable.toWeb(createReadStream(bundlePath)) as unknown as ReadableStream const body = opts.onProgress ? fileStream.pipeThrough(createByteCounter(opts.onProgress)) : fileStream const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/bundle${query}`, { @@ -286,24 +302,24 @@ export class ManagerApi { return (await res.json()) as MirrorHead } - async mirrorTargetPlan(repoId: number, branch: string): Promise { + async mirrorMoveTarget(repoId: number, branch: string): Promise { const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/target?branch=${encodeURIComponent(branch)}`, { headers: this.headers(), }) - if (!res.ok) throw await formatErrorResponse(res, 'mirror target plan') - return MirrorTargetPlanResponseSchema.parse(await res.json()) + if (!res.ok) throw await formatErrorResponse(res, 'mirror move target') + return MirrorMoveTargetResponseSchema.parse(await res.json()) } - async mirrorEnsureTarget(repoId: number, branch: string): Promise { - const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/target`, { + async mirrorCreateWorktree(repoId: number, branch: string): Promise { + const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/worktree`, { method: 'POST', headers: { ...this.headers(), 'Content-Type': 'application/json' }, body: JSON.stringify({ branch }), }) - if (!res.ok) throw await formatErrorResponse(res, 'mirror target') - return MirrorTargetEnsureResponseSchema.parse(await res.json()) + if (!res.ok) throw await formatErrorResponse(res, 'mirror create worktree') + return MirrorWorktreeCreateResponseSchema.parse(await res.json()) } async mirrorContains(repoId: number, sha: string): Promise<{ contained: boolean }> { diff --git a/ocm-cli/src/mirror.ts b/ocm-cli/src/mirror.ts index 1afb8b5c..85bfc4f6 100644 --- a/ocm-cli/src/mirror.ts +++ b/ocm-cli/src/mirror.ts @@ -7,6 +7,7 @@ import { join, dirname } from 'path' import { tmpdir } from 'os' import { getRepoRoot, getDirtyPaths, getHeadSha, getBranchName, getMirrorPatch, runGit, hasCommit, isAncestor, countCommitsAhead } from './local-repo.js' import { resolveOpenCodeProjectId } from '@opencode-manager/shared/project-id' +import type { MirrorCheckoutState, MirrorMoveTargetResponse } from '@opencode-manager/shared/schemas' import type { ManagerApi } from './manager-api.js' import { ManagerApiError } from './manager-api.js' import { delay } from './delay.js' @@ -86,7 +87,14 @@ export interface PushDivergence { export async function checkPushDivergence(repoRoot: string, api: ManagerApi, repoId: number): Promise { const info = await api.mirrorHead(repoId) - const { head: serverHead, branch: serverBranch, dirty: serverDirty } = info + return assessPushDivergence(repoRoot, info) +} + +export function assessPushDivergence( + repoRoot: string, + state: { head: string | null; branch: string | null; dirty: boolean }, +): PushDivergence { + const { head: serverHead, branch: serverBranch, dirty: serverDirty } = state const localHead = getHeadSha(repoRoot) if (!serverHead || serverHead === localHead) { @@ -102,6 +110,59 @@ export async function checkPushDivergence(repoRoot: string, api: ManagerApi, rep return { serverHead, serverBranch, serverDirty, diverged: true, lostCommits } } +export type MoveDestinationKind = 'in-place' | 'existing-worktree' | 'new-worktree' + +export interface MoveDestination { + kind: MoveDestinationKind + directory: string | null + branch: string + reasons: string[] +} + +function isCheckoutSafe(repoRoot: string, state: MirrorCheckoutState): boolean { + return !state.dirty && !assessPushDivergence(repoRoot, state).diverged +} + +function checkoutUnusableReasons( + repoRoot: string, + label: string, + state: MirrorCheckoutState, + localBranch: string, +): string[] { + if (state.branch !== localBranch) return [`${label} is on ${state.branch ?? 'a detached HEAD'}`] + const reasons: string[] = [] + if (state.dirty) reasons.push(`${label} has uncommitted changes`) + if (assessPushDivergence(repoRoot, state).diverged) reasons.push(`${label} has commits not in your local branch`) + return reasons +} + +export function chooseMoveDestination( + repoRoot: string, + localBranch: string, + target: MirrorMoveTargetResponse, +): MoveDestination { + if (target.main.branch === localBranch && isCheckoutSafe(repoRoot, target.main)) { + return { kind: 'in-place', directory: target.main.directory, branch: localBranch, reasons: [] } + } + + if (target.branchWorktree && isCheckoutSafe(repoRoot, target.branchWorktree)) { + return { kind: 'existing-worktree', directory: target.branchWorktree.directory, branch: localBranch, reasons: [] } + } + + const reasons = checkoutUnusableReasons(repoRoot, 'the server checkout', target.main, localBranch) + if (target.branchWorktree) { + reasons.push( + ...checkoutUnusableReasons( + repoRoot, + `the worktree on ${target.branchWorktree.branch ?? 'another branch'}`, + target.branchWorktree, + localBranch, + ), + ) + } + return { kind: 'new-worktree', directory: null, branch: target.newWorktreeBranch, reasons } +} + export function describePushDivergence(div: PushDivergence): string[] { const reasons: string[] = [] if (div.diverged) { @@ -371,11 +432,11 @@ export async function mirrorDown( export async function mirrorUpPatch( plan: MirrorPlan, - opts: Pick, + opts: Pick & { directory?: string }, ): Promise<{ repoId: number; fullPath: string; branch: string | null; head: string | null; created: false; applied: true }> { const repoId = plan.matched[0]!.repoId const patch = getMirrorPatch(plan.repoRoot) - return opts.api.mirrorPatch(repoId, { baseHead: getHeadSha(plan.repoRoot), patch, force: opts.force }) + return opts.api.mirrorPatch(repoId, { baseHead: getHeadSha(plan.repoRoot), patch, force: opts.force, directory: opts.directory }) } function applyPatch(repoRoot: string, patch: string): void { @@ -532,6 +593,8 @@ export type MirrorUpFastPhase = type MirrorUpFastOpts = Pick & { requireCurrentBranch?: boolean + directory?: string + targetBranch?: string onPhase?: (phase: MirrorUpFastPhase) => void } @@ -550,6 +613,8 @@ export async function mirrorUpFast( branch: getBranchName(plan.repoRoot), force: opts.force, requireCurrentBranch: opts.requireCurrentBranch, + directory: opts.directory, + targetBranch: opts.targetBranch, onProgress: onPhase ? (bytesSent) => { onPhase({ kind: 'uploading', bytesSent, totalBytes: size }) diff --git a/ocm-cli/src/tui-plugin.ts b/ocm-cli/src/tui-plugin.ts index 27b86b9a..b372fc2f 100644 --- a/ocm-cli/src/tui-plugin.ts +++ b/ocm-cli/src/tui-plugin.ts @@ -2,10 +2,9 @@ import type { Context } from '@opencode/plugin/tui/context' import { readInstallNotice } from './state.js' import { resolveManagerAuth } from './manager-auth.js' import { fetchRepos, toRemoteRepoSummaries } from './manager-repos.js' -import { ManagerApi, ManagerApiError } from './manager-api.js' -import type { MirrorTargetPlanResponse } from '@opencode-manager/shared/schemas' -import { prepareMirror, checkPushDivergence, describePushDivergence, mirrorUpFast, pickMatchedRepo } from './mirror.js' -import type { MirrorPlan, RemoteRepoSummary } from './mirror.js' +import { ManagerApi } from './manager-api.js' +import { prepareMirror, mirrorUpFast, pickMatchedRepo, chooseMoveDestination } from './mirror.js' +import type { MirrorPlan, MoveDestination } from './mirror.js' import { getBranchName } from './local-repo.js' import { transferSession, moveReminderText } from './session-move.js' import { createManagerSessionTransfer } from './remote-session.js' @@ -123,39 +122,24 @@ async function describeMoveBlocker(transfer: ManagerSessionTransfer, sessionID: return null } -async function describeRemoteDiscard(repoRoot: string, managerApi: ManagerApi, repoId: number): Promise { - try { - return describePushDivergence(await checkPushDivergence(repoRoot, managerApi, repoId)) - } catch (error) { - if (error instanceof ManagerApiError && error.status === 404) return [] - throw error - } -} - -function describeMoveTarget(repoName: string, target: MirrorTargetPlanResponse): string { - switch (target.kind) { +function moveConfirmMessage(repoName: string, destination: MoveDestination, localBranch: string): string { + switch (destination.kind) { case 'in-place': - return `Replace the repo state of ${repoName} (${target.fullPath}) with your local working tree and move this session there?` - case 'existing': - return `${repoName} is checked out on ${target.currentBranch ?? 'another branch'}; branch ${target.branch} lives in worktree ${target.localPath} (${target.fullPath}).\n\nReplace that worktree with your local working tree and move this session there?` - case 'new': - return `${repoName} is checked out on ${target.currentBranch ?? 'another branch'}; it will not be touched.\n\nCreate worktree ${target.localPath} (${target.fullPath}) for branch ${target.branch}, push your local working tree there, and move this session?` + return `Replace the repo state of ${repoName} (${destination.directory}) with your local working tree and move this session there?` + case 'existing-worktree': + return `${repoName} is checked out on another branch; branch ${destination.branch} lives in worktree ${destination.directory}.\n\nReplace that worktree with your local working tree and move this session there?` + case 'new-worktree': { + const reasons = destination.reasons.length > 0 + ? `\n\nThe server checkout was not used because:\n${destination.reasons.map((r) => ` - ${r}`).join('\n')}` + : '' + const suffix = destination.branch !== localBranch + ? `\n\n${localBranch} is checked out on the server, so ${destination.branch} is used instead.` + : '' + return `The ${repoName} server checkout will not be touched.${reasons}\n\nCreate a new OpenCode worktree for branch ${destination.branch}, push your local working tree there, and move this session?${suffix}` + } } } -function moveConfirmMessage(repoName: string, target: MirrorTargetPlanResponse, discardReasons: string[]): string { - const base = describeMoveTarget(repoName, target) - if (discardReasons.length === 0) return base - return `${base}\n\nThis discards server-side work:\n${discardReasons.map((r) => ` - ${r}`).join('\n')}` -} - -async function resolveMoveTarget(managerApi: ManagerApi, matched: RemoteRepoSummary, remoteDirectory: string, localBranch: string | null): Promise { - if (!localBranch) { - return { kind: 'in-place', repoId: matched.repoId, fullPath: remoteDirectory, localPath: remoteDirectory, branch: '', currentBranch: null } - } - return managerApi.mirrorTargetPlan(matched.repoId, localBranch) -} - async function runSessionMove(context: Context, setMoveProgress: MoveProgressSetter): Promise { try { const sessionTarget = requireSessionTarget(context) @@ -177,11 +161,14 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet } const localBranch = getBranchName(plan.repoRoot) + if (!localBranch) { + context.ui.toast.show({ variant: 'error', message: 'Check out a branch before moving; a detached HEAD cannot be moved.' }) + return + } const matched = pickMatchedRepo(plan.matched, localBranch) ?? await selectDialog(context, 'Move session to Manager repo', plan.matched.map((r) => ({ title: r.name, description: `id=${r.repoId} branch=${r.branch ?? '-'}`, value: r }))) if (!matched) return const matchedRepoId = matched.repoId - const remoteRepo = repos.find((r) => r.repoId === matchedRepoId)! await warmRepoProxy(auth.managerUrl, auth.token, matchedRepoId) @@ -193,25 +180,33 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet } const managerApi = new ManagerApi(auth.managerUrl, auth.token) - const target = await resolveMoveTarget(managerApi, matched, remoteRepo.directory, localBranch) - const discardReasons = target.repoId === null ? [] : await describeRemoteDiscard(plan.repoRoot, managerApi, target.repoId) + const target = await managerApi.mirrorMoveTarget(matched.repoId, localBranch) + const destination = chooseMoveDestination(plan.repoRoot, localBranch, target) const proceed = await confirmDialog(context, { title: 'Move session to Manager', - message: moveConfirmMessage(matched.name, target, discardReasons), + message: moveConfirmMessage(matched.name, destination, localBranch), }) if (!proceed) return - let targetRepoId = target.repoId - if (targetRepoId === null) { - setMoveProgress({ label: `creating worktree ${target.localPath}`, fraction: null }) - targetRepoId = (await managerApi.mirrorEnsureTarget(matched.repoId, target.branch)).repoId + let pushDirectory: string | undefined + let pushTargetBranch: string | undefined + if (destination.kind === 'new-worktree') { + setMoveProgress({ label: `creating worktree ${destination.branch}`, fraction: null }) + const worktree = await managerApi.mirrorCreateWorktree(matched.repoId, destination.branch) + pushDirectory = worktree.directory + pushTargetBranch = destination.branch + } else if (destination.kind === 'existing-worktree') { + pushDirectory = destination.directory ?? undefined } - const selectedPlan: MirrorPlan = { ...plan, matched: [{ ...matched, repoId: targetRepoId }] } + + const selectedPlan: MirrorPlan = { ...plan, matched: [matched] } const pushed = await mirrorUpFast(selectedPlan, { api: managerApi, force: true, - requireCurrentBranch: true, + requireCurrentBranch: destination.kind !== 'new-worktree', + directory: pushDirectory, + targetBranch: pushTargetBranch, onPhase: (phase) => setMoveProgress(pushPhaseProgress(phase)), }) const remoteDirectory = pushed.fullPath @@ -232,10 +227,10 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet setMoveProgress(null) const warp = await confirmDialog(context, { title: 'Attach to moved session?', message: 'Exit this TUI and attach to the moved session on the Manager now?' }) if (warp) { - await warmRepoProxy(auth.managerUrl, auth.token, pushed.repoId) + await warmRepoProxy(auth.managerUrl, auth.token, matched.repoId) setPendingWarp({ kind: 'attach', - target: { managerUrl: auth.managerUrl, token: auth.token, repoId: pushed.repoId, sessionID: result.sessionID, repoName: matched.name }, + target: { managerUrl: auth.managerUrl, token: auth.token, repoId: matched.repoId, sessionID: result.sessionID, repoName: matched.name }, }) context.keymap.dispatch('app.exit') return diff --git a/ocm-cli/test/mirror.test.ts b/ocm-cli/test/mirror.test.ts index 12ff10b7..af60760d 100644 --- a/ocm-cli/test/mirror.test.ts +++ b/ocm-cli/test/mirror.test.ts @@ -4,7 +4,7 @@ import { join } from 'path' import { tmpdir } from 'os' import { randomBytes } from 'crypto' import { spawnSync, execSync } from 'child_process' -import { prepareMirror, MirrorAbort, mirrorDown, mirrorDownFast, mirrorUp, mirrorUpPatch, mirrorUpFast, checkPushDivergence, checkPullDivergence, describePushDivergence, pickMatchedRepo, type MirrorUpFastPhase } from '../src/mirror' +import { prepareMirror, MirrorAbort, mirrorDown, mirrorDownFast, mirrorUp, mirrorUpPatch, mirrorUpFast, checkPushDivergence, checkPullDivergence, describePushDivergence, pickMatchedRepo, chooseMoveDestination, assessPushDivergence, type MirrorUpFastPhase } from '../src/mirror' import { getBranchName } from '../src/local-repo' import { ManagerApi } from '../src/manager-api' import { gitRemoteProjectId } from '@opencode-manager/shared/project-id' @@ -685,6 +685,158 @@ describe('describePushDivergence', () => { }) }) +describe('assessPushDivergence', () => { + let tmpDir: string + + beforeEach(() => { + tmpDir = mkdtempSync(join(tmpdir(), 'assess-divergence-test-')) + }) + + afterEach(() => { + rmSync(tmpDir, { recursive: true, force: true }) + }) + + function initRepo(name: string): string { + const repoRoot = join(tmpDir, name) + mkdirSync(repoRoot) + spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' }) + spawnSync('git', ['config', 'user.email', 'test@test.com'], { cwd: repoRoot, stdio: 'ignore' }) + spawnSync('git', ['config', 'user.name', 'Test'], { cwd: repoRoot, stdio: 'ignore' }) + return repoRoot + } + + function commit(repoRoot: string, file: string, content: string): string { + writeFileSync(join(repoRoot, file), content) + spawnSync('git', ['add', '.'], { cwd: repoRoot, stdio: 'ignore' }) + spawnSync('git', ['commit', '-m', `add ${file}`], { cwd: repoRoot, stdio: 'ignore' }) + return execSync('git rev-parse HEAD', { cwd: repoRoot, encoding: 'utf-8' }).trim() + } + + it('reports no divergence from server state alone when heads match', () => { + const repoRoot = initRepo('assess-equal') + const head = commit(repoRoot, 'a.txt', 'a') + + const result = assessPushDivergence(repoRoot, { head, branch: 'main', dirty: false }) + + expect(result.diverged).toBe(false) + expect(result.serverBranch).toBe('main') + }) + + it('surfaces the dirty flag from the server state', () => { + const repoRoot = initRepo('assess-dirty') + const head = commit(repoRoot, 'a.txt', 'a') + + const result = assessPushDivergence(repoRoot, { head, branch: 'main', dirty: true }) + + expect(result.serverDirty).toBe(true) + expect(result.diverged).toBe(false) + }) +}) + +describe('chooseMoveDestination', () => { + let tmpDir: string + + beforeEach(() => { + tmpDir = mkdtempSync(join(tmpdir(), 'move-destination-test-')) + }) + + afterEach(() => { + rmSync(tmpDir, { recursive: true, force: true }) + }) + + function initRepo(name: string): string { + const repoRoot = join(tmpDir, name) + mkdirSync(repoRoot) + spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' }) + spawnSync('git', ['config', 'user.email', 'test@test.com'], { cwd: repoRoot, stdio: 'ignore' }) + spawnSync('git', ['config', 'user.name', 'Test'], { cwd: repoRoot, stdio: 'ignore' }) + return repoRoot + } + + function commit(repoRoot: string, file: string, content: string): string { + writeFileSync(join(repoRoot, file), content) + spawnSync('git', ['add', '.'], { cwd: repoRoot, stdio: 'ignore' }) + spawnSync('git', ['commit', '-m', `add ${file}`], { cwd: repoRoot, stdio: 'ignore' }) + return execSync('git rev-parse HEAD', { cwd: repoRoot, encoding: 'utf-8' }).trim() + } + + const checkout = (directory: string, branch: string | null, head: string | null, dirty = false) => ({ directory, branch, head, dirty }) + + it('replaces the main checkout in place when it is on the local branch, clean, and not ahead', () => { + const repoRoot = initRepo('in-place') + const head = commit(repoRoot, 'a.txt', 'a') + + const destination = chooseMoveDestination(repoRoot, 'main', { + main: checkout('/repos/repo', 'main', head), + branchWorktree: null, + newWorktreeBranch: 'main', + }) + + expect(destination).toEqual({ kind: 'in-place', directory: '/repos/repo', branch: 'main', reasons: [] }) + }) + + it('reuses a safe branch worktree when the main checkout is on another branch', () => { + const repoRoot = initRepo('reuse-worktree') + const head = commit(repoRoot, 'a.txt', 'a') + + const destination = chooseMoveDestination(repoRoot, 'feature', { + main: checkout('/repos/repo', 'main', head), + branchWorktree: checkout('/repos/repo-feature', 'feature', head), + newWorktreeBranch: 'feature', + }) + + expect(destination).toEqual({ kind: 'existing-worktree', directory: '/repos/repo-feature', branch: 'feature', reasons: [] }) + }) + + it('creates a suffixed worktree and reports only the branch when the main checkout is on another branch', () => { + const repoRoot = initRepo('new-worktree') + const head = commit(repoRoot, 'a.txt', 'a') + + const destination = chooseMoveDestination(repoRoot, 'feature', { + main: checkout('/repos/repo', 'main', head, true), + branchWorktree: null, + newWorktreeBranch: 'feature-ocm', + }) + + expect(destination.kind).toBe('new-worktree') + expect(destination.directory).toBeNull() + expect(destination.branch).toBe('feature-ocm') + expect(destination.reasons).toEqual(['the server checkout is on main']) + }) + + it('explains why an unusable branch worktree was skipped', () => { + const repoRoot = initRepo('unusable-worktree') + const head = commit(repoRoot, 'a.txt', 'a') + + const destination = chooseMoveDestination(repoRoot, 'feature', { + main: checkout('/repos/repo', 'main', head), + branchWorktree: checkout('/repos/repo-feature', 'feature', head, true), + newWorktreeBranch: 'feature-ocm', + }) + + expect(destination.kind).toBe('new-worktree') + expect(destination.reasons).toContain('the worktree on feature has uncommitted changes') + }) + + it('reports a diverged main checkout as commits not in the local branch', () => { + const repoRoot = initRepo('diverged-main') + commit(repoRoot, 'a.txt', 'a') + spawnSync('git', ['checkout', '-b', 'server'], { cwd: repoRoot, stdio: 'ignore' }) + const serverHead = commit(repoRoot, 'server.txt', 'server-work') + spawnSync('git', ['checkout', '-'], { cwd: repoRoot, stdio: 'ignore' }) + commit(repoRoot, 'local.txt', 'local-work') + + const destination = chooseMoveDestination(repoRoot, 'feature', { + main: checkout('/repos/repo', 'feature', serverHead), + branchWorktree: null, + newWorktreeBranch: 'feature', + }) + + expect(destination.kind).toBe('new-worktree') + expect(destination.reasons).toContain('the server checkout has commits not in your local branch') + }) +}) + describe('checkPullDivergence', () => { let tmpDir: string @@ -1006,6 +1158,37 @@ describe('mirrorUpFast targets the selected repo', () => { expect(uploadCalls).toEqual([3]) expect(patchCalls).toEqual([3]) }) + + it('forwards the worktree directory and target branch to the bundle upload and patch', async () => { + const repoRoot = join(tmpDir, 'repo-worktree-target') + mkdirSync(repoRoot) + spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' }) + spawnSync('git', ['config', 'user.email', 'test@test.com'], { cwd: repoRoot, stdio: 'ignore' }) + spawnSync('git', ['config', 'user.name', 'Test'], { cwd: repoRoot, stdio: 'ignore' }) + writeFileSync(join(repoRoot, 'a.txt'), 'a\n') + spawnSync('git', ['add', '.'], { cwd: repoRoot, stdio: 'ignore' }) + spawnSync('git', ['commit', '-m', 'init'], { cwd: repoRoot, stdio: 'ignore' }) + writeFileSync(join(repoRoot, 'a.txt'), 'a-updated\n') + + const api = { + mirrorUploadBundle: vi.fn().mockResolvedValue(undefined), + mirrorPatch: vi.fn().mockResolvedValue({ repoId: 1, fullPath: '/repos/repo-feature-ocm', branch: 'feature-ocm', head: 'abc', created: false, applied: true }), + } + + const plan = { + repoRoot, + localProjectId: 'proj', + matched: [{ repoId: 1, name: 'repo-A', projectId: 'proj', branch: 'main' }], + } + + await mirrorUpFast(plan, { api: api as any, force: true, directory: '/repos/repo-feature-ocm', targetBranch: 'feature-ocm' }) + + const bundleOpts = api.mirrorUploadBundle.mock.calls[0]![2] + expect(bundleOpts.directory).toBe('/repos/repo-feature-ocm') + expect(bundleOpts.targetBranch).toBe('feature-ocm') + expect(bundleOpts.requireCurrentBranch).toBeUndefined() + expect(api.mirrorPatch.mock.calls[0]![1].directory).toBe('/repos/repo-feature-ocm') + }) }) describe('mirrorDownFast preflight', () => { @@ -1187,84 +1370,72 @@ describe('mirrorDownFast preflight', () => { }) }) -describe('ManagerApi target response validation', () => { +describe('ManagerApi move target and worktree validation', () => { afterEach(() => { vi.unstubAllGlobals() }) const api = new ManagerApi('http://localhost:5003', 'test-token') - it('parses a valid new-worktree target plan response', async () => { + const checkout = (directory: string, branch: string | null, head: string | null, dirty = false) => ({ directory, branch, head, dirty }) + + it('parses a valid move target response with a branch worktree', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, - json: () => Promise.resolve({ kind: 'new', repoId: null, fullPath: '/repos/repo-feature', localPath: 'repo-feature', branch: 'feature', currentBranch: 'main' }), + json: () => Promise.resolve({ + main: checkout('/repos/repo', 'main', 'abc'), + branchWorktree: checkout('/repos/repo-feature', 'feature', 'def'), + newWorktreeBranch: 'feature', + }), })) - const plan = await api.mirrorTargetPlan(1, 'feature') + const target = await api.mirrorMoveTarget(1, 'feature') - expect(plan.kind).toBe('new') - expect(plan.repoId).toBeNull() - expect(plan.branch).toBe('feature') + expect(target.main.branch).toBe('main') + expect(target.branchWorktree?.directory).toBe('/repos/repo-feature') + expect(target.newWorktreeBranch).toBe('feature') }) - it('parses a valid existing-worktree target plan response', async () => { + it('parses a move target response with no branch worktree and a suffixed branch', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, - json: () => Promise.resolve({ kind: 'existing', repoId: 5, fullPath: '/repos/repo-feature', localPath: 'repo-feature', branch: 'feature', currentBranch: null }), + json: () => Promise.resolve({ main: checkout('/repos/repo', 'main', 'abc'), branchWorktree: null, newWorktreeBranch: 'feature-ocm' }), })) - const plan = await api.mirrorTargetPlan(1, 'feature') + const target = await api.mirrorMoveTarget(1, 'feature') - expect(plan.kind).toBe('existing') - expect(plan.repoId).toBe(5) + expect(target.branchWorktree).toBeNull() + expect(target.newWorktreeBranch).toBe('feature-ocm') }) - it('rejects a target plan response whose repoId contradicts its kind', async () => { + it('rejects a move target response missing the main checkout', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, - json: () => Promise.resolve({ kind: 'new', repoId: 7, fullPath: '/repos/repo-feature', localPath: 'repo-feature', branch: 'feature', currentBranch: 'main' }), + json: () => Promise.resolve({ branchWorktree: null, newWorktreeBranch: 'feature' }), })) - await expect(api.mirrorTargetPlan(1, 'feature')).rejects.toThrow() + await expect(api.mirrorMoveTarget(1, 'feature')).rejects.toThrow() }) - it('rejects a target plan response with an unknown kind', async () => { + it('parses a valid worktree create response', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, - json: () => Promise.resolve({ kind: 'bogus', repoId: 1, fullPath: '/x', localPath: 'x', branch: 'main', currentBranch: null }), + json: () => Promise.resolve({ directory: '/repos/repo-feature-ocm', branch: 'feature-ocm' }), })) - await expect(api.mirrorTargetPlan(1, 'main')).rejects.toThrow() + const created = await api.mirrorCreateWorktree(1, 'feature-ocm') + + expect(created.directory).toBe('/repos/repo-feature-ocm') + expect(created.branch).toBe('feature-ocm') }) - it('parses a valid ensure target response', async () => { + it('rejects a worktree create response missing the branch', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, - json: () => Promise.resolve({ repoId: 9, fullPath: '/repos/repo-feature', localPath: 'repo-feature', branch: 'feature', created: true }), + json: () => Promise.resolve({ directory: '/repos/repo-feature-ocm' }), })) - const target = await api.mirrorEnsureTarget(1, 'feature') - - expect(target.repoId).toBe(9) - expect(target.created).toBe(true) - }) - - it('rejects an ensure target response missing fields', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ repoId: 9, fullPath: '/repos/repo-feature' }), - })) - - await expect(api.mirrorEnsureTarget(1, 'feature')).rejects.toThrow() - }) - - it('rejects an ensure target response with a non-positive repoId', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ repoId: 0, fullPath: '/x', localPath: 'x', branch: 'main', created: false }), - })) - - await expect(api.mirrorEnsureTarget(1, 'main')).rejects.toThrow() + await expect(api.mirrorCreateWorktree(1, 'feature-ocm')).rejects.toThrow() }) }) @@ -1306,4 +1477,29 @@ describe('ManagerApi mirrorUploadBundle strict branch header', () => { expect(headers['X-OCM-Require-Current-Branch']).toBeUndefined() expect(headers['X-OCM-Branch']).toBe('main') }) + + it('sends the target branch header and URL-encoded directory query', async () => { + const bundlePath = join(tmpDir, 'repo.bundle') + writeFileSync(bundlePath, 'bundle bytes') + let capturedUrl: string | undefined + let capturedHeaders: Record | undefined + vi.stubGlobal('fetch', vi.fn().mockImplementation(async (url: unknown, init?: RequestInit) => { + capturedUrl = String(url) + capturedHeaders = init!.headers as Record + return { ok: true, json: () => Promise.resolve({ repoId: 1, fullPath: '/repos/x', branch: 'feature-ocm', head: 'abc', created: false }) } + })) + + await api.mirrorUploadBundle(1, bundlePath, { + branch: 'feature', + force: true, + directory: '/repos/work trees/repo', + targetBranch: 'feature-ocm', + }) + + const parsed = new URL(capturedUrl!) + expect(parsed.searchParams.get('force')).toBe('1') + expect(parsed.searchParams.get('directory')).toBe('/repos/work trees/repo') + expect(capturedHeaders!['X-OCM-Target-Branch']).toBe('feature-ocm') + expect(capturedHeaders!['X-OCM-Branch']).toBe('feature') + }) }) diff --git a/ocm-cli/test/tui-plugin.test.ts b/ocm-cli/test/tui-plugin.test.ts index 9e14bea0..ffac785b 100644 --- a/ocm-cli/test/tui-plugin.test.ts +++ b/ocm-cli/test/tui-plugin.test.ts @@ -12,15 +12,15 @@ const mocks = vi.hoisted(() => ({ fetchRepos: vi.fn(), toRemoteRepoSummaries: vi.fn((repos: unknown) => repos), prepareMirror: vi.fn(), - checkPushDivergence: vi.fn(), - describePushDivergence: vi.fn(() => []), + chooseMoveDestination: vi.fn(), mirrorUpFast: vi.fn(), pickMatchedRepo: vi.fn(), getBranchName: vi.fn(), createManagerSessionTransfer: vi.fn(), setPendingWarp: vi.fn(), runPendingWarp: vi.fn(), - mirrorTargetPlan: vi.fn(), + mirrorMoveTarget: vi.fn(), + mirrorCreateWorktree: vi.fn(), warmRepoProxy: vi.fn(), })) @@ -38,8 +38,7 @@ vi.mock('../src/manager-repos.js', () => ({ vi.mock('../src/mirror.js', () => ({ prepareMirror: mocks.prepareMirror, - checkPushDivergence: mocks.checkPushDivergence, - describePushDivergence: mocks.describePushDivergence, + chooseMoveDestination: mocks.chooseMoveDestination, mirrorUpFast: mocks.mirrorUpFast, pickMatchedRepo: mocks.pickMatchedRepo, })) @@ -63,8 +62,8 @@ vi.mock('../src/manager-api.js', () => ({ public readonly managerUrl: string, public readonly token: string, ) {} - mirrorTargetPlan = mocks.mirrorTargetPlan - mirrorEnsureTarget = vi.fn() + mirrorMoveTarget = mocks.mirrorMoveTarget + mirrorCreateWorktree = mocks.mirrorCreateWorktree }, ManagerApiError: class ManagerApiError extends Error { constructor( @@ -163,22 +162,17 @@ function configureMove(fake: ReturnType) { mocks.prepareMirror.mockResolvedValue({ repoRoot: '/Users/x/repo', localProjectId: 'proj_1', matched: [matched] }) mocks.getBranchName.mockReturnValue('main') mocks.pickMatchedRepo.mockReturnValue(matched) - mocks.mirrorTargetPlan.mockResolvedValue({ + mocks.mirrorMoveTarget.mockResolvedValue({ + main: { directory: '/workspace/repos/repo', branch: 'main', head: null, dirty: false }, + branchWorktree: null, + newWorktreeBranch: 'main', + }) + mocks.chooseMoveDestination.mockReturnValue({ kind: 'in-place', - repoId: 1, - fullPath: '/workspace/repos/repo', - localPath: '/workspace/repos/repo', + directory: '/workspace/repos/repo', branch: 'main', - currentBranch: null, + reasons: [], }) - mocks.checkPushDivergence.mockResolvedValue({ - serverHead: null, - serverBranch: 'main', - serverDirty: false, - diverged: false, - lostCommits: 0, - }) - mocks.describePushDivergence.mockReturnValue([]) mocks.mirrorUpFast.mockResolvedValue({ repoId: 1, fullPath: '/workspace/repos/repo', @@ -331,7 +325,7 @@ describe('ocm.session.move command', () => { }) function expectNothingPushed(fake: ReturnType, importSession: ReturnType) { - expect(mocks.mirrorTargetPlan).not.toHaveBeenCalled() + expect(mocks.mirrorMoveTarget).not.toHaveBeenCalled() expect(fake.confirm).not.toHaveBeenCalled() expect(mocks.mirrorUpFast).not.toHaveBeenCalled() expect(fake.exportMock).not.toHaveBeenCalled() @@ -401,4 +395,100 @@ describe('ocm.session.move command', () => { expect(importSession).not.toHaveBeenCalled() expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: tooOld }) }) + + it('refuses to move from a detached HEAD before pushing anything', async () => { + const fake = createFakeContext() + configureMove(fake) + const { importSession } = stubTransfer() + mocks.getBranchName.mockReturnValue(null) + + await invokeMove(fake) + + expect(mocks.mirrorMoveTarget).not.toHaveBeenCalled() + expect(mocks.mirrorUpFast).not.toHaveBeenCalled() + expect(fake.exportMock).not.toHaveBeenCalled() + expect(importSession).not.toHaveBeenCalled() + expect(fake.toast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'error', message: expect.stringContaining('detached HEAD') })) + }) + + it('pushes in place with the strict current-branch guard when the main checkout is safe', async () => { + const fake = createFakeContext() + configureMove(fake) + const { importSession } = stubTransfer() + fake.exportMock.mockResolvedValue(makeTransfer()) + + await invokeMove(fake) + + expect(mocks.mirrorMoveTarget).toHaveBeenCalledWith(1, 'main') + expect(mocks.mirrorCreateWorktree).not.toHaveBeenCalled() + expect(mocks.mirrorUpFast).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ force: true, requireCurrentBranch: true, directory: undefined, targetBranch: undefined }), + ) + expect(importSession).toHaveBeenCalledWith('/workspace/repos/repo', expect.anything()) + }) + + it('pushes into an existing worktree directory with the strict current-branch guard', async () => { + const fake = createFakeContext() + configureMove(fake) + const { importSession } = stubTransfer() + fake.exportMock.mockResolvedValue(makeTransfer()) + mocks.chooseMoveDestination.mockReturnValue({ + kind: 'existing-worktree', + directory: '/workspace/repos/repo-feature', + branch: 'feature', + reasons: [], + }) + mocks.mirrorUpFast.mockResolvedValue({ + repoId: 1, + fullPath: '/workspace/repos/repo-feature', + branch: 'feature', + head: null, + created: false, + }) + + await invokeMove(fake) + + expect(mocks.mirrorCreateWorktree).not.toHaveBeenCalled() + expect(mocks.mirrorUpFast).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ force: true, requireCurrentBranch: true, directory: '/workspace/repos/repo-feature' }), + ) + expect(importSession).toHaveBeenCalledWith('/workspace/repos/repo-feature', expect.anything()) + }) + + it('creates a new worktree and pushes with a target branch when no safe checkout exists', async () => { + const fake = createFakeContext() + configureMove(fake) + const { importSession } = stubTransfer() + fake.exportMock.mockResolvedValue(makeTransfer()) + mocks.chooseMoveDestination.mockReturnValue({ + kind: 'new-worktree', + directory: null, + branch: 'feature-ocm', + reasons: ['the server checkout is on main'], + }) + mocks.mirrorCreateWorktree.mockResolvedValue({ directory: '/workspace/repos/repo-feature-ocm', branch: 'feature-ocm' }) + mocks.mirrorUpFast.mockResolvedValue({ + repoId: 1, + fullPath: '/workspace/repos/repo-feature-ocm', + branch: 'feature-ocm', + head: null, + created: false, + }) + + await invokeMove(fake) + + expect(mocks.mirrorCreateWorktree).toHaveBeenCalledWith(1, 'feature-ocm') + expect(mocks.mirrorUpFast).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + force: true, + requireCurrentBranch: false, + directory: '/workspace/repos/repo-feature-ocm', + targetBranch: 'feature-ocm', + }), + ) + expect(importSession).toHaveBeenCalledWith('/workspace/repos/repo-feature-ocm', expect.anything()) + }) }) diff --git a/shared/src/schemas/repo.ts b/shared/src/schemas/repo.ts index 0f1fd2e8..fae5c971 100644 --- a/shared/src/schemas/repo.ts +++ b/shared/src/schemas/repo.ts @@ -147,27 +147,26 @@ export const MirrorTargetBranchRequestSchema = z.object({ export type MirrorTargetBranchRequest = z.infer -const MirrorTargetPlanBaseSchema = z.object({ - fullPath: z.string().min(1), - localPath: z.string().min(1), - branch: z.string().min(1), - currentBranch: z.string().min(1).nullable(), +export const MirrorCheckoutStateSchema = z.object({ + directory: z.string().min(1), + branch: z.string().min(1).nullable(), + head: z.string().min(1).nullable(), + dirty: z.boolean(), }) -export const MirrorTargetPlanResponseSchema = z.discriminatedUnion('kind', [ - MirrorTargetPlanBaseSchema.extend({ kind: z.literal('new'), repoId: z.literal(null) }), - MirrorTargetPlanBaseSchema.extend({ kind: z.literal('in-place'), repoId: z.number().int().positive() }), - MirrorTargetPlanBaseSchema.extend({ kind: z.literal('existing'), repoId: z.number().int().positive() }), -]) +export type MirrorCheckoutState = z.infer -export type MirrorTargetPlanResponse = z.infer - -export const MirrorTargetEnsureResponseSchema = z.object({ - repoId: z.number().int().positive(), - fullPath: z.string().min(1), - localPath: z.string().min(1), - branch: z.string().min(1), - created: z.boolean(), +export const MirrorMoveTargetResponseSchema = z.object({ + main: MirrorCheckoutStateSchema, + branchWorktree: MirrorCheckoutStateSchema.nullable(), + newWorktreeBranch: z.string().min(1), }) -export type MirrorTargetEnsureResponse = z.infer +export type MirrorMoveTargetResponse = z.infer + +export const MirrorWorktreeCreateResponseSchema = z.object({ + directory: z.string().min(1), + branch: z.string().min(1), +}) + +export type MirrorWorktreeCreateResponse = z.infer