feat: add bundle-based OCM mirror sync (#289)

* feat: add bundle-based OCM mirror sync

* feat: add OpenCode model editor and HEAD-safe bundle import

* fix: consolidate discovery-cache, batch bundle refs, remove dead code (#290)

* fix: consolidate discovery-cache, batch bundle refs, remove dead code

* refactor: consolidate discovery cache into generic discoverCached, extract spawnGit helper

* feat: extract project-id-resolver, add CLI full-fallback prompt, wire lint into root scripts

- Extract shared project-id-resolver for origin URL matching (replaces local-repo duplicates)
- Add promptYesNo / confirmFullFallback to ocm CLI before slow full mirror
- Backend: consolidate opencode-workspaces routes with project-id-resolver
- Frontend: fix schedules prompt/global page navigation
- CLI: add eslint config, lint/lint:fix scripts, fix no-fallthrough in ocm.ts
- Root: wire CLI into build, test, typecheck, lint, lint:fix chains
- Fix test lint issues (_code, const, require→import)

* fix: replace polynomial regex with linear-time string ops in gitRemoteParts

* feat: add divergence guards for push/pull, streaming bundle upload, server-side ancestry check

- Backend: GET /:repoId/mirror/head (head+branch+dirty) and GET /:repoId/mirror/contains/:sha (ancestry check)
- CLI: checkPushDivergence warns before overwriting server commits; checkPullDivergence warns before discarding local commits; both require confirm or --force
- Bundle upload now streams from disk instead of buffering entire file in memory
- Version visible in --help and default (no-arg) output
- Version bump 0.1.5 → 0.2.0

* fix: show connecting message before fetching repos in default command

* fix: update default command messages to reflect actual matching behavior
This commit is contained in:
Chris Scott authored and GitHub committed 2026-06-28 11:57:38 -04:00
1 parent bb1df259b6
commit 01e50a7019
34 files changed
+2060 -316

No files matched your search

+78 -16
View File
@@ -1,11 +1,42 @@
import { spawnSync } from 'child_process'
import { spawnSync, type SpawnSyncReturns } from 'child_process'
import { copyFileSync, existsSync, rmSync } from 'fs'
import { join } from 'path'
import { tmpdir } from 'os'
function git(cwd: string, args: string[]): string | null {
const res = spawnSync('git', args, { cwd, encoding: 'utf-8' })
function spawnGit(
cwd: string,
args: string[],
opts: { input?: string; env?: NodeJS.ProcessEnv } = {},
): SpawnSyncReturns<string> {
return spawnSync('git', args, { cwd, input: opts.input, encoding: 'utf-8', env: opts.env ?? process.env })
}
function git(cwd: string, args: string[], env: NodeJS.ProcessEnv = process.env): string | null {
const res = spawnGit(cwd, args, { env })
if (res.status !== 0) return null
return (res.stdout ?? '').trim()
}
function gitRaw(cwd: string, args: string[], env: NodeJS.ProcessEnv = process.env): string | null {
const res = spawnGit(cwd, args, { env })
if (res.status !== 0) return null
return res.stdout ?? ''
}
export function runGit(
cwd: string,
args: string[],
input?: string,
env: NodeJS.ProcessEnv = process.env,
): string {
const res = spawnGit(cwd, args, { input, env })
if (res.status !== 0) {
const stderr = (res.stderr ?? '').trim()
throw new Error(`git ${args.join(' ')} failed${stderr ? `: ${stderr}` : ''}`)
}
return res.stdout ?? ''
}
export function getRepoRoot(cwd: string): string | null {
return git(cwd, ['rev-parse', '--show-toplevel'])
}
@@ -26,20 +57,51 @@ export function getDirtyPaths(dir: string): Set<string> {
return paths
}
function normalizeUrl(url: string): string {
return url
.trim()
.replace(/\.git$/, '')
.replace(/^git@([^:]+):/, 'ssh://git@$1/')
.replace(/\/+$/, '')
.toLowerCase()
}
export function getBranchName(dir: string): string | null {
return git(dir, ['rev-parse', '--abbrev-ref', 'HEAD'])
const branch = git(dir, ['rev-parse', '--abbrev-ref', 'HEAD'])
return branch && branch !== 'HEAD' ? branch : null
}
export function urlsEqual(a: string | null | undefined, b: string | null | undefined): boolean {
if (!a || !b) return false
return normalizeUrl(a) === normalizeUrl(b)
function getWorkingTreeDiff(dir: string): string {
return gitRaw(dir, ['diff', '--binary', 'HEAD', '--']) ?? ''
}
export function getHeadSha(dir: string): string | null {
return git(dir, ['rev-parse', 'HEAD'])
}
export function hasCommit(dir: string, sha: string): boolean {
return git(dir, ['cat-file', '-e', `${sha}^{commit}`]) !== null
}
export function isAncestor(dir: string, ancestor: string, descendant: string): boolean {
return spawnGit(dir, ['merge-base', '--is-ancestor', ancestor, descendant]).status === 0
}
export function countCommitsAhead(dir: string, from: string, to: string): number {
const out = git(dir, ['rev-list', '--count', `${from}..${to}`])
const n = out ? Number(out) : NaN
return Number.isInteger(n) ? n : -1
}
export function getMirrorPatch(dir: string): string {
const untracked = gitRaw(dir, ['ls-files', '--others', '--exclude-standard', '-z'])
?.split('\0')
.filter(Boolean) ?? []
if (untracked.length === 0) return getWorkingTreeDiff(dir)
const indexPath = git(dir, ['rev-parse', '--git-path', 'index'])
const tempIndex = join(tmpdir(), `ocm-index-${Date.now()}-${Math.random().toString(36).slice(2)}`)
const env = { ...process.env, GIT_INDEX_FILE: tempIndex }
try {
if (indexPath && existsSync(indexPath)) {
copyFileSync(indexPath, tempIndex)
}
const add = spawnSync('git', ['add', '-N', '--', ...untracked], { cwd: dir, encoding: 'utf-8', env })
if (add.status !== 0) return getWorkingTreeDiff(dir)
return gitRaw(dir, ['diff', '--binary', 'HEAD', '--'], env) ?? ''
} finally {
rmSync(tempIndex, { force: true })
}
}
+97
View File
@@ -1,3 +1,6 @@
import { createReadStream } from 'fs'
import { Readable } from 'stream'
export interface MirrorBeginOpts {
force?: boolean
create?: { name: string; originUrl: string | null; branch: string | null }
@@ -18,6 +21,37 @@ export interface MirrorCommitResult {
created: boolean
}
export interface MirrorPatchResult {
repoId: number
fullPath: string
branch: string | null
head: string | null
created: false
applied: true
}
export interface MirrorPatchSnapshot {
repoId: number
branch: string | null
head: string | null
patch: string
}
export interface MirrorHead {
repoId: number
branch: string | null
head: string | null
dirty: boolean
}
export interface MirrorBundleResult {
repoId: number
fullPath: string
branch: string | null
head: string | null
created: false
}
export class ManagerApiError extends Error {
constructor(
message: string,
@@ -115,4 +149,67 @@ export class ManagerApi {
if (!res.ok) throw await formatErrorResponse(res, 'mirror download')
return res.body!
}
async mirrorPatch(repoId: number, body: { baseHead: string | null; patch: string; force?: boolean }): Promise<MirrorPatchResult> {
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 }),
})
if (!res.ok) throw await formatErrorResponse(res, 'mirror patch')
return (await res.json()) as MirrorPatchResult
}
async mirrorUploadBundle(repoId: number, bundlePath: string, opts: { branch: string | null; force?: boolean }): Promise<MirrorBundleResult> {
const query = opts.force === true ? '?force=1' : ''
const headers: Record<string, string> = { ...this.headers(), 'Content-Type': 'application/octet-stream' }
if (opts.branch) headers['X-OCM-Branch'] = opts.branch
const body = Readable.toWeb(createReadStream(bundlePath)) as ReadableStream<Uint8Array>
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/bundle${query}`, {
method: 'POST',
headers,
body: body as BodyInit,
duplex: 'half',
} as RequestInit & { duplex: 'half' })
if (!res.ok) throw await formatErrorResponse(res, 'mirror bundle upload')
return (await res.json()) as MirrorBundleResult
}
async mirrorHead(repoId: number): Promise<MirrorHead> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/head`, {
headers: this.headers(),
})
if (!res.ok) throw await formatErrorResponse(res, 'mirror head')
return (await res.json()) as MirrorHead
}
async mirrorContains(repoId: number, sha: string): Promise<{ contained: boolean }> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/contains/${sha}`, {
headers: this.headers(),
})
if (!res.ok) throw await formatErrorResponse(res, 'mirror contains')
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`, {
headers: this.headers(),
})
if (!res.ok) throw await formatErrorResponse(res, 'mirror bundle download')
return res.body!
}
async mirrorPatchSnapshot(repoId: number): Promise<MirrorPatchSnapshot> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/patch`, {
headers: this.headers(),
})
if (!res.ok) throw await formatErrorResponse(res, 'mirror patch snapshot')
return (await res.json()) as MirrorPatchSnapshot
}
}
+171 -9
View File
@@ -1,10 +1,12 @@
import { spawnSync, spawn } from 'child_process'
import { existsSync } from 'fs'
import { createWriteStream, existsSync } from 'fs'
import * as fsp from 'fs/promises'
import { Readable } from 'stream'
import { pipeline } from 'stream/promises'
import { join, dirname } from 'path'
import { tmpdir } from 'os'
import { getRepoRoot, getOriginUrl, getDirtyPaths, urlsEqual } from './local-repo.js'
import { getRepoRoot, getDirtyPaths, getHeadSha, getBranchName, getMirrorPatch, runGit, hasCommit, isAncestor, countCommitsAhead } from './local-repo.js'
import { resolveOpenCodeProjectId } from '@opencode-manager/shared/project-id'
import type { ManagerApi } from './manager-api.js'
import { ManagerApiError } from './manager-api.js'
@@ -45,26 +47,76 @@ export class MirrorAbort extends Error {
export interface RemoteRepoSummary {
repoId: number
name: string
originUrl: string | null
projectId: string | null
branch: string | null
}
export interface MirrorPlan {
repoRoot: string
localOrigin: string
localProjectId: string
matched: RemoteRepoSummary[]
}
export function prepareMirror(cwd: string, remotes: RemoteRepoSummary[]): MirrorPlan {
export async function prepareMirror(cwd: string, remotes: RemoteRepoSummary[]): Promise<MirrorPlan> {
const repoRoot = getRepoRoot(cwd)
if (!repoRoot) throw new MirrorAbort('not in a git repository')
const localOrigin = getOriginUrl(repoRoot)
if (!localOrigin) throw new MirrorAbort('no origin URL found')
const localProjectId = await resolveOpenCodeProjectId(repoRoot)
if (!localProjectId) throw new MirrorAbort('could not resolve an OpenCode project id for this repository')
const matched = remotes.filter((r) => urlsEqual(localOrigin, r.originUrl))
const matched = remotes.filter((r) => r.projectId && r.projectId === localProjectId)
return { repoRoot, localOrigin, matched }
return { repoRoot, localProjectId, matched }
}
export interface PushDivergence {
serverHead: string | null
serverBranch: string | null
serverDirty: boolean
diverged: boolean
lostCommits: number
}
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
const localHead = getHeadSha(repoRoot)
if (!serverHead || serverHead === localHead) {
return { serverHead, serverBranch, serverDirty, diverged: false, lostCommits: 0 }
}
if (!hasCommit(repoRoot, serverHead)) {
return { serverHead, serverBranch, serverDirty, diverged: true, lostCommits: -1 }
}
if (localHead && isAncestor(repoRoot, serverHead, localHead)) {
return { serverHead, serverBranch, serverDirty, diverged: false, lostCommits: 0 }
}
const lostCommits = localHead ? countCommitsAhead(repoRoot, localHead, serverHead) : -1
return { serverHead, serverBranch, serverDirty, diverged: true, lostCommits }
}
export interface PullDivergence {
diverged: boolean
lostCommits: number
serverHead: string | null
}
export async function checkPullDivergence(repoRoot: string, api: ManagerApi, repoId: number): Promise<PullDivergence> {
const localHead = getHeadSha(repoRoot)
if (!localHead) return { diverged: false, lostCommits: 0, serverHead: null }
const { contained } = await api.mirrorContains(repoId, localHead)
if (contained) return { diverged: false, lostCommits: 0, serverHead: null }
let serverHead: string | null = null
let lostCommits = -1
try {
serverHead = (await api.mirrorHead(repoId)).head
if (serverHead) lostCommits = countCommitsAhead(repoRoot, serverHead, localHead)
} catch {
// best-effort: count is informational only
}
return { diverged: true, lostCommits, serverHead }
}
export interface MirrorProgress {
@@ -302,3 +354,113 @@ export async function mirrorDown(
throw error
}
}
export async function mirrorUpPatch(
plan: MirrorPlan,
opts: Pick<MirrorUpOpts, 'api' | 'force'>,
): 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 })
}
function applyPatch(repoRoot: string, patch: string): void {
if (!patch) return
const child = spawnSync('git', ['apply', '--binary', '--whitespace=nowarn', '-'], {
cwd: repoRoot,
input: patch,
encoding: 'utf-8',
})
if (child.status !== 0) {
const stderr = (child.stderr ?? '').trim()
throw new Error(`git apply failed${stderr ? `: ${stderr}` : ''}`)
}
}
async function createLocalBundle(repoRoot: string): Promise<string> {
const bundlePath = join(tmpdir(), `ocm-bundle-${Date.now()}-${Math.random().toString(36).slice(2)}.bundle`)
runGit(repoRoot, ['bundle', 'create', bundlePath, '--all'])
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(''))
}
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])
}
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`)
if (deletes.length > 0) {
runGit(repoRoot, ['update-ref', '--stdin'], deletes.join(''))
}
} catch {
// cleanup of ocm-sync refs is best-effort
}
}
async function writeBundleStream(repoId: number, api: ManagerApi): Promise<string> {
const bundlePath = join(tmpdir(), `ocm-bundle-down-${Date.now()}-${Math.random().toString(36).slice(2)}.bundle`)
const stream = await api.mirrorDownloadBundle(repoId)
await pipeline(
Readable.fromWeb(stream as unknown as Parameters<typeof Readable.fromWeb>[0]),
createWriteStream(bundlePath),
)
return bundlePath
}
export async function mirrorUpFast(
plan: MirrorPlan,
opts: Pick<MirrorUpOpts, 'api' | 'force'>,
): Promise<{ repoId: number; branch: string | null; head: string | null; created: false }> {
const repoId = plan.matched[0]!.repoId
const bundlePath = await createLocalBundle(plan.repoRoot)
try {
await opts.api.mirrorUploadBundle(repoId, bundlePath, { branch: getBranchName(plan.repoRoot), force: opts.force })
const patchResult = await mirrorUpPatch(plan, opts)
return { repoId: patchResult.repoId, branch: patchResult.branch, head: patchResult.head, created: false }
} finally {
await fsp.rm(bundlePath, { force: true }).catch(() => {})
}
}
export async function mirrorDownFast(
repoId: number,
repoRoot: string,
api: ManagerApi,
opts: { force: boolean } = { force: false },
): Promise<void> {
if (!opts.force && getDirtyPaths(repoRoot).size > 0) {
throw new MirrorAbort('working tree has uncommitted changes; rerun with --force')
}
const snapshot = await api.mirrorPatchSnapshot(repoId)
const bundlePath = await writeBundleStream(repoId, api)
try {
importLocalBundle(repoRoot, bundlePath, snapshot.branch)
applyPatch(repoRoot, snapshot.patch)
} finally {
await fsp.rm(bundlePath, { force: true }).catch(() => {})
}
}
+13 -11
View File
@@ -1,36 +1,38 @@
import { getRepoRoot, getOriginUrl, urlsEqual } from './local-repo.js'
import { getRepoRoot } from './local-repo.js'
export interface TargetRepo {
repoId: number
name: string
branch: string | null
directory: string
originUrl?: string | null
projectId?: string | null
}
export type ResolveResult =
| { kind: 'cwd-match'; repo: TargetRepo; repoRoot: string }
| { kind: 'last'; repo: TargetRepo }
| { kind: 'cwd-ambiguous'; matches: TargetRepo[]; localOrigin: string; repoRoot: string }
| { kind: 'cwd-ambiguous'; matches: TargetRepo[]; localProjectId: string; repoRoot: string }
| { kind: 'local'; reason: 'no-match' | 'no-target'; repoRoot: string | null }
export interface ResolveInput {
cwd: string
repos: TargetRepo[]
localProjectId: string | null
last?: { repoId: number; name: string; directory: string; branch: string | null }
}
export function resolveTarget(input: ResolveInput): ResolveResult {
const repoRoot = getRepoRoot(input.cwd)
const localOrigin = repoRoot ? getOriginUrl(repoRoot) : null
if (repoRoot && localOrigin) {
const matches = input.repos.filter((r) => urlsEqual(localOrigin, r.originUrl))
if (matches.length === 1) {
return { kind: 'cwd-match', repo: matches[0]!, repoRoot }
}
if (matches.length > 1) {
return { kind: 'cwd-ambiguous', matches, localOrigin, repoRoot }
if (repoRoot) {
if (input.localProjectId) {
const matches = input.repos.filter((r) => r.projectId && r.projectId === input.localProjectId)
if (matches.length === 1) {
return { kind: 'cwd-match', repo: matches[0]!, repoRoot }
}
if (matches.length > 1) {
return { kind: 'cwd-ambiguous', matches, localProjectId: input.localProjectId, repoRoot }
}
}
return { kind: 'local', reason: 'no-match', repoRoot }
}