feat(ocm): move sessions into OpenCode worktrees instead of replacing the Manager checkout

/ocm-move previously failed when the Manager checkout was dirty, behind, or on
another branch. Choose the destination instead: replace in place only when the
checkout is on the local branch, clean, and has nothing the local branch lacks;
otherwise reuse an existing OpenCode worktree on that branch when it is equally
safe; otherwise create a new OpenCode worktree through the same service the UI
and multi-runs use, so it appears in the repo's worktree lists. The new
worktree's branch is the local branch when free, else <branch>-ocm, -ocm-2 and
so on. Server work is never discarded, the confirmation states the destination
and why the main checkout was skipped, and a detached HEAD is refused.

The mirror push endpoints (bundle upload and patch) accept a worktree
directory, rejected unless it belongs to the repo, and a new endpoint creates
the worktree. The old <repo>-<branch> path that registered a plain git worktree
as a separate Manager repo is removed.
This commit is contained in:
Chris Scott committed 2026-10-08 20:47:02 -04:00
1 parent ae0dff6e84
commit bd7c3e3fef
13 files changed
+895 -585

No files matched your search

+20 -18
View File
@@ -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
`<host> · <repo>` 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 (`<repo>-<branch>`,
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 `<branch>-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`:
+31 -15
View File
@@ -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<MirrorPatchResult> {
async mirrorPatch(
repoId: number,
body: { baseHead: string | null; patch: string; force?: boolean; directory?: string },
): Promise<MirrorPatchResult> {
const payload: Record<string, unknown> = { 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<MirrorBundleResult> {
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<string, string> = { ...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<Uint8Array>
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<MirrorTargetPlanResponse> {
async mirrorMoveTarget(repoId: number, branch: string): Promise<MirrorMoveTargetResponse> {
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<MirrorTargetEnsureResponse> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/target`, {
async mirrorCreateWorktree(repoId: number, branch: string): Promise<MirrorWorktreeCreateResponse> {
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 }> {
+68 -3
View File
@@ -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<PushDivergence> {
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<MirrorUpOpts, 'api' | 'force'>,
opts: Pick<MirrorUpOpts, 'api' | 'force'> & { 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<MirrorUpOpts, 'api' | 'force'> & {
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 })
+40 -45
View File
@@ -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<string[]> {
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<MirrorTargetPlanResponse> {
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<void> {
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
+239 -43
View File
@@ -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<string, string> | undefined
vi.stubGlobal('fetch', vi.fn().mockImplementation(async (url: unknown, init?: RequestInit) => {
capturedUrl = String(url)
capturedHeaders = init!.headers as Record<string, string>
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')
})
})
+111 -21
View File
@@ -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<typeof createFakeContext>) {
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<typeof createFakeContext>, importSession: ReturnType<typeof vi.fn>) {
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())
})
})