fix(ocm): make /ocm-move worktree moves safe and round-trippable

- Answer the old /mirror/target routes with a 410 upgrade message and
  serve the lookup at GET /mirror/checkouts; detect older Managers via
  the token probe (MANAGER_FEATURE_MISSING).
- Create the move worktree and import the bundle in one call; worktree
  setup runs after the import and the worktree is removed on failure.
- Never rewind a server branch: suffix the new worktree branch when the
  server branch has commits the local branch lacks, and skip both the
  source and target branch when updating refs.
- Reuse clean <branch>-ocm[-N] worktrees and legacy worktree repo rows
  instead of creating new ones on every move.
- Let ocm push/pull target the worktree on the local branch via a
  directory parameter on the mirror read routes; no tarball fallback
  for worktrees.
- Share one sibling loader (listRepoSiblings), validate branch names,
  compare canonical paths in isDirectoryInUse, and cut redundant git
  work in the checkouts lookup and the CLI destination choice.
This commit is contained in:
Chris Scott committed 2026-10-08 23:23:00 -04:00
1 parent bd7c3e3fef
commit 67f70e9635
21 files changed
+1777 -517

No files matched your search

+51 -26
View File
@@ -1,13 +1,13 @@
import { createReadStream } from 'fs'
import { Readable } from 'stream'
import {
MirrorMoveTargetResponseSchema,
MirrorCheckoutsResponseSchema,
MirrorWorktreeCreateResponseSchema,
MultiRunSchema,
SessionGoalSchema,
type FuseMultiRunRequest,
type LaunchMultiRunRequest,
type MirrorMoveTargetResponse,
type MirrorCheckoutsResponse,
type MirrorWorktreeCreateResponse,
type MultiRun,
type SessionGoal,
@@ -78,6 +78,13 @@ function createByteCounter(onProgress: (bytesSent: number) => void): TransformSt
export const MANAGER_FEATURE_MISSING = 'MANAGER_FEATURE_MISSING'
const DEFAULT_FEATURE_NAME = 'ocm goals and multi-runs'
const MOVE_FEATURE_NAME = '/ocm-move worktrees'
function directoryQuery(directory: string | undefined): string {
return directory ? `?${new URLSearchParams({ directory }).toString()}` : ''
}
export class ManagerApiError extends Error {
constructor(
message: string,
@@ -141,9 +148,9 @@ export class ManagerApi {
path: string,
operation: string,
parse: (body: unknown) => T,
init?: RequestInit & { feature?: boolean },
init?: RequestInit & { feature?: boolean; featureName?: string },
): Promise<T> {
const { feature, ...requestInit } = init ?? {}
const { feature, featureName, ...requestInit } = init ?? {}
const baseHeaders = this.headers(
typeof requestInit.body === 'string' ? { 'Content-Type': 'application/json' } : {},
)
@@ -151,25 +158,29 @@ export class ManagerApi {
...requestInit,
headers: { ...baseHeaders, ...(requestInit.headers as Record<string, string> | undefined) },
})
if (!res.ok) throw await this.handleErrorResponse(res, operation, feature === true, requestInit.signal ?? undefined)
if (!res.ok) {
const featureLabel = feature === true ? (featureName ?? DEFAULT_FEATURE_NAME) : null
throw await this.handleErrorResponse(res, operation, featureLabel, requestInit.signal ?? undefined)
}
return parse(await res.json())
}
private async handleErrorResponse(
res: Response,
operation: string,
feature: boolean,
featureName: string | null,
signal?: AbortSignal,
): Promise<ManagerApiError> {
const error = await formatErrorResponse(res, operation)
if (feature && error.status === 401) {
return this.probeFeatureSupport(operation, error, signal)
if (featureName !== null && error.status === 401) {
return this.probeFeatureSupport(operation, featureName, error, signal)
}
return error
}
private async probeFeatureSupport(
operation: string,
featureName: string,
fallback: ManagerApiError,
signal?: AbortSignal,
): Promise<ManagerApiError> {
@@ -177,7 +188,7 @@ export class ManagerApi {
const res = await fetch(`${this.baseUrl}/api/internal/opencode-workspaces`, { headers: this.headers(), signal })
if (res.ok) {
return new ManagerApiError(
`${operation} failed: this OpenCode Manager is too old for ocm goals and multi-runs; upgrade the Manager.`,
`${operation} failed: this OpenCode Manager is too old for ${featureName}; upgrade the Manager.`,
401,
MANAGER_FEATURE_MISSING,
operation,
@@ -293,8 +304,8 @@ export class ManagerApi {
return (await res.json()) as MirrorBundleResult
}
async mirrorHead(repoId: number): Promise<MirrorHead> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/head`, {
async mirrorHead(repoId: number, directory?: string): Promise<MirrorHead> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/head${directoryQuery(directory)}`, {
headers: this.headers(),
})
@@ -302,28 +313,42 @@ export class ManagerApi {
return (await res.json()) as MirrorHead
}
async mirrorMoveTarget(repoId: number, branch: string): Promise<MirrorMoveTargetResponse> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/target?branch=${encodeURIComponent(branch)}`, {
async mirrorCheckouts(repoId: number, branch: string): Promise<MirrorCheckoutsResponse> {
const params = new URLSearchParams({ branch })
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/checkouts?${params.toString()}`, {
headers: this.headers(),
})
if (!res.ok) throw await formatErrorResponse(res, 'mirror move target')
return MirrorMoveTargetResponseSchema.parse(await res.json())
if (!res.ok) throw await this.handleErrorResponse(res, 'mirror checkouts', MOVE_FEATURE_NAME)
return MirrorCheckoutsResponseSchema.parse(await res.json())
}
async mirrorCreateWorktree(repoId: number, branch: string): Promise<MirrorWorktreeCreateResponse> {
async mirrorCreateWorktree(
repoId: number,
bundlePath: string,
opts: { branch: string; targetBranch: string; onProgress?: (bytesSent: number) => void },
): Promise<MirrorWorktreeCreateResponse> {
const headers: Record<string, string> = {
...this.headers(),
'Content-Type': 'application/octet-stream',
'X-OCM-Branch': opts.branch,
'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/worktree`, {
method: 'POST',
headers: { ...this.headers(), 'Content-Type': 'application/json' },
body: JSON.stringify({ branch }),
})
headers,
body: body as BodyInit,
duplex: 'half',
} as RequestInit & { duplex: 'half' })
if (!res.ok) throw await formatErrorResponse(res, 'mirror create worktree')
if (!res.ok) throw await this.handleErrorResponse(res, 'mirror create worktree', MOVE_FEATURE_NAME)
return MirrorWorktreeCreateResponseSchema.parse(await res.json())
}
async mirrorContains(repoId: number, sha: string): Promise<{ contained: boolean }> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/contains/${sha}`, {
async mirrorContains(repoId: number, sha: string, directory?: string): Promise<{ contained: boolean }> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/contains/${sha}${directoryQuery(directory)}`, {
headers: this.headers(),
})
@@ -331,8 +356,8 @@ export class ManagerApi {
return (await res.json()) as { repoId: number; contained: boolean }
}
async mirrorDownloadBundle(repoId: number): Promise<ReadableStream<Uint8Array>> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/bundle`, {
async mirrorDownloadBundle(repoId: number, directory?: string): Promise<ReadableStream<Uint8Array>> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/bundle${directoryQuery(directory)}`, {
headers: this.headers(),
})
@@ -340,8 +365,8 @@ export class ManagerApi {
return res.body!
}
async mirrorPatchSnapshot(repoId: number): Promise<MirrorPatchSnapshot> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/patch`, {
async mirrorPatchSnapshot(repoId: number, directory?: string): Promise<MirrorPatchSnapshot> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/patch${directoryQuery(directory)}`, {
headers: this.headers(),
})