Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

9.3 KB
Raw Blame
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
  syncForkDefaultBranch,
  validateGitForkSyncExpectedUpstream,
  type GitForkSyncRunner
} from './git-fork-sync'

afterEach(() => {
  vi.restoreAllMocks()
})

function createRunner(overrides: {
  remotes?: string
  upstreamUrl?: string
  defaultBranchOutput?: string
  originExists?: boolean
  upstreamExists?: boolean
  aheadBehind?: string
  equalTips?: boolean
  ancestryError?: boolean
  commitOutput?: string
  countError?: boolean
}): { runGit: GitForkSyncRunner; calls: string[][] } {
  const calls: string[][] = []
  const runGit = vi.fn(async (args: string[]) => {
    calls.push(args)
    if (args[0] === 'remote' && args[1] === 'get-url') {
      return { stdout: overrides.upstreamUrl ?? '[email protected]:stablyai/orca.git\n' }
    }
    if (args[0] === 'remote') {
      return { stdout: overrides.remotes ?? 'origin\nupstream\n' }
    }
    if (args[0] === 'ls-remote') {
      return {
        stdout:
          overrides.defaultBranchOutput ??
          'ref: refs/heads/main\tHEAD\n0123456789012345678901234567890123456789\tHEAD\n'
      }
    }
    if (args[0] === 'rev-parse') {
      const ref = args[2] ?? ''
      if (ref.includes('origin/main') && overrides.originExists === false) {
        throw new Error('missing origin branch')
      }
      if (ref.includes('upstream/main') && overrides.upstreamExists === false) {
        throw new Error('missing upstream branch')
      }
      return {
        stdout:
          overrides.commitOutput ??
          (ref.includes('upstream') && !overrides.equalTips
            ? '2222222222222222222222222222222222222222\n'
            : '1111111111111111111111111111111111111111\n')
      }
    }
    if (args[0] === 'rev-list') {
      if (overrides.countError) {
        throw new Error('invalid revision')
      }
      return { stdout: overrides.aheadBehind ?? '0\t2\n' }
    }
    if (args[0] === 'merge-base' && overrides.ancestryError) {
      throw new Error('missing parent object')
    }
    return { stdout: '' }
  })
  return { runGit, calls }
}

function flattenedCommands(calls: string[][]): string {
  return calls.map((args) => args.join(' ')).join('\n')
}

describe('syncForkDefaultBranch', () => {
  it('pushes the upstream default branch when the fork is only behind', async () => {
    const { runGit, calls } = createRunner({ aheadBehind: '0\t3\n' })

    const result = await syncForkDefaultBranch(runGit)

    expect(result).toMatchObject({ status: 'synced', branchName: 'main', ahead: 0, behind: 3 })
    expect(calls.filter((args) => args[0] === 'remote' && args.length === 1)).toEqual([['remote']])
    expect(calls).toContainEqual([
      'push',
      'origin',
      '2222222222222222222222222222222222222222:refs/heads/main'
    ])
    expect(calls).toContainEqual([
      'fetch',
      '--no-tags',
      '--prune',
      'upstream',
      '+refs/heads/main:refs/remotes/upstream/main'
    ])
  })

  it('supports default branch names with slashes', async () => {
    const { runGit, calls } = createRunner({
      defaultBranchOutput:
        'ref: refs/heads/release/1.0\tHEAD\n0123456789012345678901234567890123456789\tHEAD\n',
      aheadBehind: '0\t1\n'
    })

    await syncForkDefaultBranch(runGit)

    expect(calls).toContainEqual([
      'push',
      'origin',
      '2222222222222222222222222222222222222222:refs/heads/release/1.0'
    ])
  })

  it('does nothing when the fork default branch already matches upstream', async () => {
    const { runGit, calls } = createRunner({ aheadBehind: '0\t0\n' })

    const result = await syncForkDefaultBranch(runGit)

    expect(result).toMatchObject({ status: 'up-to-date', branchName: 'main' })
    expect(flattenedCommands(calls)).not.toContain('push origin')
  })

  it('skips history counts for equal verified tips while retaining fetches and ancestry validation', async () => {
    const { runGit, calls } = createRunner({ equalTips: true })

    await expect(syncForkDefaultBranch(runGit)).resolves.toMatchObject({
      status: 'up-to-date',
      ahead: 0,
      behind: 0
    })
    expect(calls.filter((args) => args[0] === 'fetch')).toHaveLength(2)
    expect(calls.filter((args) => args[0] === 'rev-parse')).toHaveLength(2)
    expect(calls.some((args) => args[0] === 'rev-list' || args[0] === 'push')).toBe(false)
    expect(calls).toContainEqual([
      'merge-base',
      '--is-ancestor',
      '1111111111111111111111111111111111111111',
      '1111111111111111111111111111111111111111'
    ])
  })

  it('still blocks equal tips when ancestry cannot be verified', async () => {
    const { runGit, calls } = createRunner({ equalTips: true, ancestryError: true })

    await expect(syncForkDefaultBranch(runGit)).resolves.toMatchObject({
      status: 'blocked',
      reason: 'diverged',
      ahead: 0,
      behind: 0
    })
    expect(calls.some((args) => args[0] === 'push')).toBe(false)
  })

  it('keeps the count query error when a wrapper returns identical non-object output', async () => {
    const { runGit, calls } = createRunner({
      commitOutput: 'wrapper banner\n',
      countError: true
    })

    await expect(syncForkDefaultBranch(runGit)).rejects.toThrow('invalid revision')
    expect(calls.some((args) => args[0] === 'rev-list')).toBe(true)
    expect(calls.some((args) => args[0] === 'push')).toBe(false)
  })

  it('scans newline-heavy remote and default-branch output without line-array splitting', async () => {
    const splitSpy = vi.spyOn(String.prototype, 'split')
    const { runGit } = createRunner({
      remotes: `${'\r\n'.repeat(10_000)}origin\r\nupstream\r\n`,
      defaultBranchOutput: `${'metadata\r\n'.repeat(
        10_000
      )}ref: refs/heads/main\tHEAD\r\n0123456789012345678901234567890123456789\tHEAD\r\n`,
      aheadBehind: '0\t0\n'
    })

    await expect(syncForkDefaultBranch(runGit)).resolves.toMatchObject({
      status: 'up-to-date',
      branchName: 'main'
    })

    const usedLineSplit = splitSpy.mock.calls.some(
      ([separator]) =>
        (typeof separator === 'string' && separator === '\n') ||
        (separator instanceof RegExp && separator.source === '\\r?\\n')
    )
    expect(usedLineSplit).toBe(false)
  })

  it('blocks when the fork has commits that are not upstream', async () => {
    const { runGit, calls } = createRunner({ aheadBehind: '2\t4\n' })

    const result = await syncForkDefaultBranch(runGit)

    expect(result).toMatchObject({
      status: 'blocked',
      reason: 'diverged',
      ahead: 2,
      behind: 4
    })
    const commands = flattenedCommands(calls)
    expect(commands).not.toContain('push origin')
    expect(commands).not.toContain('reset --hard')
    expect(commands).not.toContain('pull')
    expect(commands).not.toContain('rebase')
    expect(commands).not.toContain('force')
  })

  it('blocks when the upstream remote is missing', async () => {
    const { runGit, calls } = createRunner({ remotes: 'origin\n' })

    await expect(syncForkDefaultBranch(runGit)).resolves.toMatchObject({
      status: 'blocked',
      reason: 'missing-upstream'
    })
    expect(calls).toEqual([['remote']])
  })

  it('reports missing origin first when both remotes are missing', async () => {
    const { runGit, calls } = createRunner({ remotes: '' })

    await expect(syncForkDefaultBranch(runGit)).resolves.toMatchObject({
      status: 'blocked',
      reason: 'missing-origin'
    })
    expect(calls).toEqual([['remote']])
  })

  it('blocks when the upstream remote no longer matches the expected fork metadata', async () => {
    const { runGit, calls } = createRunner({
      upstreamUrl: '[email protected]:someone-else/orca.git\n'
    })

    await expect(
      syncForkDefaultBranch(runGit, {
        expectedUpstream: { owner: 'stablyai', repo: 'orca' }
      })
    ).resolves.toMatchObject({
      status: 'blocked',
      reason: 'upstream-mismatch'
    })
    expect(flattenedCommands(calls)).not.toContain('fetch')
    expect(flattenedCommands(calls)).not.toContain('push')
  })

  it('blocks when a non-GitHub upstream remote has the expected owner and repo suffix', async () => {
    const { runGit, calls } = createRunner({
      upstreamUrl: 'ssh://evil.example.com/stablyai/orca.git\n'
    })

    await expect(
      syncForkDefaultBranch(runGit, {
        expectedUpstream: { owner: 'stablyai', repo: 'orca' }
      })
    ).resolves.toMatchObject({
      status: 'blocked',
      reason: 'upstream-mismatch'
    })
    expect(flattenedCommands(calls)).not.toContain('fetch')
    expect(flattenedCommands(calls)).not.toContain('push')
  })

  it('rejects malformed expected upstream metadata instead of disabling identity validation', async () => {
    const { runGit } = createRunner({})

    await expect(
      syncForkDefaultBranch(runGit, {
        expectedUpstream: { owner: '   ', repo: 'orca' }
      })
    ).rejects.toThrow('Invalid expected upstream.')
  })

  it('rejects missing expected upstream metadata when required by a boundary', () => {
    expect(() => validateGitForkSyncExpectedUpstream(undefined, { required: true })).toThrow(
      'Expected upstream is required.'
    )
  })

  it('blocks when origin lacks the upstream default branch', async () => {
    const { runGit } = createRunner({ originExists: false })

    await expect(syncForkDefaultBranch(runGit)).resolves.toMatchObject({
      status: 'blocked',
      reason: 'missing-origin-branch',
      branchName: 'main'
    })
  })
})