feat(ocm-move): plan worktree mirror targets and stream move progress (#345)

* feat(ocm-move): plan worktree mirror targets and stream move progress

- Plan/ensure mirror targets per branch via new internal endpoints, creating a worktree repo when the target branch is not checked out in the source repo
- Skip branches checked out in other worktrees during bundle import and reset/clean before checkout on both server and CLI
- Rewrite workspace paths in message.updated events when replaying moved sessions
- Stream live move progress (bundle, upload, import, patch, replay) in the TUI
- Prefer branch-matched repos when moving sessions and share push-divergence descriptions

* chore(ocm-cli): bump version to 0.2.7

* fix(ocm): harden worktree mirror synchronization

* fix(ocm): protect active branch during branchless pull
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-01 22:14:48 -04:00
1 parent 4ed3460759
commit 68d586f183
23 files changed
+2026 -158

No files matched your search

+112 -27
View File
@@ -69,6 +69,12 @@ export async function prepareMirror(cwd: string, remotes: RemoteRepoSummary[]):
return { repoRoot, localProjectId, matched }
}
export function pickMatchedRepo(matched: RemoteRepoSummary[], localBranch: string | null): RemoteRepoSummary | null {
const onBranch = matched.filter((r) => localBranch !== null && r.branch === localBranch)
if (onBranch.length === 1) return onBranch[0]!
return matched.length === 1 ? matched[0]! : null
}
export interface PushDivergence {
serverHead: string | null
serverBranch: string | null
@@ -95,6 +101,17 @@ export async function checkPushDivergence(repoRoot: string, api: ManagerApi, rep
return { serverHead, serverBranch, serverDirty, diverged: true, lostCommits }
}
export function describePushDivergence(div: PushDivergence): string[] {
const reasons: string[] = []
if (div.diverged) {
reasons.push(div.lostCommits >= 0
? `the server is ${div.lostCommits} commit(s) ahead of your local branch`
: 'the server has commit(s) not present in your local branch')
}
if (div.serverDirty) reasons.push('the server has uncommitted changes')
return reasons
}
export interface PullDivergence {
diverged: boolean
lostCommits: number
@@ -393,30 +410,38 @@ async function createLocalBundle(repoRoot: string): Promise<string> {
return bundlePath
}
function importLocalBundle(repoRoot: string, bundlePath: string, branch: string | null): void {
runGit(repoRoot, ['fetch', bundlePath, '+refs/heads/*:refs/remotes/ocm-sync/*', '+refs/tags/*:refs/tags/*'])
const refs = runGit(repoRoot, ['for-each-ref', '--format=%(refname:strip=3) %(objectname)', 'refs/remotes/ocm-sync'])
const updates: string[] = []
for (const line of refs.split('\n')) {
const trimmed = line.trim()
if (!trimmed) continue
const firstSpace = trimmed.indexOf(' ')
if (firstSpace === -1) continue
const name = trimmed.slice(0, firstSpace)
if (name === 'HEAD') continue
const sha = trimmed.slice(firstSpace + 1)
updates.push(`update refs/heads/${name} ${sha}\n`)
}
if (updates.length > 0) {
runGit(repoRoot, ['update-ref', '--stdin'], updates.join(''))
function listWorktreeBranches(repoRoot: string): Map<string, string[]> {
const out = runGit(repoRoot, ['worktree', 'list', '--porcelain'])
const ownership = new Map<string, string[]>()
let currentPath: string | null = null
for (const line of out.split('\n')) {
if (line.startsWith('worktree ')) {
currentPath = line.slice('worktree '.length).trim()
} else if (line.startsWith('branch ')) {
if (!currentPath) continue
const branch = line.slice('branch '.length).trim().replace(/^refs\/heads\//, '')
const paths = ownership.get(branch) ?? []
paths.push(currentPath)
ownership.set(branch, paths)
}
}
return ownership
}
if (branch) {
runGit(repoRoot, ['checkout', branch])
const head = runGit(repoRoot, ['rev-parse', `refs/remotes/ocm-sync/${branch}`]).trim()
if (head) runGit(repoRoot, ['reset', '--hard', head])
}
function listLocalBranches(repoRoot: string): Set<string> {
const out = runGit(repoRoot, ['for-each-ref', '--format=%(refname:short)', 'refs/heads'])
return new Set(out.split('\n').map((l) => l.trim()).filter(Boolean))
}
function branchOwnedElsewhere(ownership: Map<string, string[]>, repoRoot: string): Set<string> {
const locked = new Set<string>()
for (const [branch, paths] of ownership) {
if (paths.some((path) => path !== repoRoot)) locked.add(branch)
}
return locked
}
function deleteSyncRefs(repoRoot: string): void {
try {
const syncRefsOut = runGit(repoRoot, ['for-each-ref', '--format=%(refname)', 'refs/remotes/ocm-sync'])
const deletes = syncRefsOut.split('\n').map((l) => l.trim()).filter(Boolean).map((ref) => `delete ${ref}\n`)
@@ -424,7 +449,62 @@ function importLocalBundle(repoRoot: string, bundlePath: string, branch: string
runGit(repoRoot, ['update-ref', '--stdin'], deletes.join(''))
}
} catch {
// cleanup of ocm-sync refs is best-effort
return
}
}
function importLocalBundle(repoRoot: string, bundlePath: string, branch: string | null, force: boolean): void {
runGit(repoRoot, ['fetch', bundlePath, '+refs/heads/*:refs/remotes/ocm-sync/*', '+refs/tags/*:refs/tags/*'])
try {
const refs = runGit(repoRoot, ['for-each-ref', '--format=%(refname:strip=3) %(objectname)', 'refs/remotes/ocm-sync'])
const incoming = new Map<string, string>()
for (const line of refs.split('\n')) {
const trimmed = line.trim()
if (!trimmed) continue
const firstSpace = trimmed.indexOf(' ')
if (firstSpace === -1) continue
const name = trimmed.slice(0, firstSpace)
if (name === 'HEAD') continue
incoming.set(name, trimmed.slice(firstSpace + 1))
}
const lockedElsewhere = branchOwnedElsewhere(listWorktreeBranches(repoRoot), repoRoot)
const currentBranch = getBranchName(repoRoot)
if (branch) {
const incomingSha = incoming.get(branch)
if (!incomingSha) throw new MirrorAbort(`no incoming branch '${branch}' in the server bundle`)
if (lockedElsewhere.has(branch)) {
throw new MirrorAbort(`branch '${branch}' is checked out in another worktree; release it there before pulling`)
}
if (currentBranch !== branch) {
const checkoutArgs = force ? ['-f'] : []
if (listLocalBranches(repoRoot).has(branch)) {
runGit(repoRoot, ['checkout', ...checkoutArgs, branch])
} else {
runGit(repoRoot, ['checkout', ...checkoutArgs, '-b', branch, incomingSha])
}
}
}
const updates: string[] = []
for (const [name, sha] of incoming) {
if (branch === name) continue
if (lockedElsewhere.has(name)) continue
if (branch === null && name === currentBranch) continue
updates.push(`update refs/heads/${name} ${sha}\n`)
}
if (updates.length > 0) {
runGit(repoRoot, ['update-ref', '--stdin'], updates.join(''))
}
if (branch) {
const targetSha = incoming.get(branch)!
runGit(repoRoot, ['reset', '--hard', targetSha])
runGit(repoRoot, ['clean', '-fd'])
}
} finally {
deleteSyncRefs(repoRoot)
}
}
@@ -444,10 +524,15 @@ export type MirrorUpFastPhase =
| { kind: 'processing' }
| { kind: 'patching' }
type MirrorUpFastOpts = Pick<MirrorUpOpts, 'api' | 'force'> & {
requireCurrentBranch?: boolean
onPhase?: (phase: MirrorUpFastPhase) => void
}
export async function mirrorUpFast(
plan: MirrorPlan,
opts: Pick<MirrorUpOpts, 'api' | 'force'> & { onPhase?: (phase: MirrorUpFastPhase) => void },
): Promise<{ repoId: number; branch: string | null; head: string | null; created: false }> {
opts: MirrorUpFastOpts,
): Promise<{ repoId: number; fullPath: string; branch: string | null; head: string | null; created: false }> {
const repoId = plan.matched[0]!.repoId
const onPhase = opts.onPhase
onPhase?.({ kind: 'bundling' })
@@ -458,6 +543,7 @@ export async function mirrorUpFast(
await opts.api.mirrorUploadBundle(repoId, bundlePath, {
branch: getBranchName(plan.repoRoot),
force: opts.force,
requireCurrentBranch: opts.requireCurrentBranch,
onProgress: onPhase
? (bytesSent) => {
onPhase({ kind: 'uploading', bytesSent, totalBytes: size })
@@ -467,7 +553,7 @@ export async function mirrorUpFast(
})
onPhase?.({ kind: 'patching' })
const patchResult = await mirrorUpPatch(plan, opts)
return { repoId: patchResult.repoId, branch: patchResult.branch, head: patchResult.head, created: false }
return { repoId: patchResult.repoId, fullPath: patchResult.fullPath, branch: patchResult.branch, head: patchResult.head, created: false }
} finally {
await fsp.rm(bundlePath, { force: true }).catch(() => {})
}
@@ -486,11 +572,10 @@ export async function mirrorDownFast(
const snapshot = await api.mirrorPatchSnapshot(repoId)
const bundlePath = await writeBundleStream(repoId, api)
try {
importLocalBundle(repoRoot, bundlePath, snapshot.branch)
importLocalBundle(repoRoot, bundlePath, snapshot.branch, opts.force)
applyPatch(repoRoot, snapshot.patch)
} finally {
await fsp.rm(bundlePath, { force: true }).catch(() => {})
}
}