Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

39.9 KB
Raw Blame
/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
import { inspectJournal } from '@boxlite-ai/ci-listener/testing'
import { testCapacity } from '@boxlite-ai/ci-listener/testing'
import { randomUUID } from 'node:crypto'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Header } from 'tar'
import {
  ConfirmedWorkerAbsent,
  ConfirmedWorkerCreationRejected,
  ExecutionJournal,
  ExecutionLease,
  ExecutionScope,
  ListenerState,
  WorkerExecutor,
  WorkerPool,
  parseResourceLabels,
} from '@boxlite-ai/ci-listener'
import { SqliteStateDatabase } from '@boxlite-ai/ci-listener/sqlite'
import { BoxLiteWorkers } from './boxlite-workers'
import { BoxLiteRequestError } from './boxlite-http'

describe('Standalone BoxLite execution boundary', () => {
  const originalFetch = global.fetch
  let directory: string,
    db: SqliteStateDatabase,
    state: ListenerState,
    journal: ExecutionJournal,
    lease: ExecutionLease,
    service: BoxLiteWorkers,
    worker: WorkerExecutor,
    scope: ExecutionScope,
    namespace: string,
    key: string,
    name: string,
    box: { box_id: string; name: string; status: string } | undefined,
    principal: { sub: string; principal_type: string; path_prefix: string },
    loseCreate: boolean,
    loseStart: boolean,
    notFound: boolean,
    listDenied: boolean,
    listOriginal: boolean,
    uploadFailed: boolean,
    allowed: boolean,
    initialStatus: string,
    afterUpload: (() => void) | undefined,
    afterList: (() => void) | undefined,
    calls: { path: string; method: string; body: unknown }[]
  let meGate: { entered(): void; wait: Promise<void> } | undefined
  let createHttpStatus: number | undefined
  let createHttpBody: unknown
  beforeEach(async () => {
    directory = mkdtempSync(join(tmpdir(), 'ci-self-rest-'))
    db = new SqliteStateDatabase(directory)
    namespace = 'ci:' + randomUUID()
    state = new ListenerState(db, namespace)
    journal = new ExecutionJournal(state)
    principal = { sub: 'owner-a', principal_type: 'service_account', path_prefix: 'tenant-a' }
    loseCreate = loseStart = notFound = listDenied = listOriginal = uploadFailed = false
    allowed = true
    initialStatus = 'running'
    createHttpStatus = undefined
    createHttpBody = {}
    meGate = undefined
    afterUpload = afterList = undefined
    box = undefined
    calls = []
    global.fetch = jest.fn(async (input, options) => {
      const path = new URL(String(input)).pathname,
        method = options?.method ?? 'GET',
        body = typeof options?.body === 'string' ? JSON.parse(options.body) : options?.body
      calls.push({ path, method, body })
      const json = (value: unknown, status = 200) => new Response(JSON.stringify(value), { status })
      if (path === '/v1/me') {
        meGate?.entered()
        if (meGate) await meGate.wait
        return json(principal)
      }
      if (path === '/v1/tenant-a/boxes' && method === 'POST') {
        const input = body as { name: string }
        box = { box_id: 'original-box', name: input.name, status: initialStatus }
        if (loseCreate) throw new Error('Lost create response')
        if (createHttpStatus) return json(createHttpBody, createHttpStatus)
        return json(box, 201)
      }
      if (path === '/v1/tenant-a/boxes' && method === 'GET') {
        if (listDenied) return json({}, 403)
        const result = json({ boxes: listOriginal && box ? [box] : [] })
        afterList?.()
        return result
      }
      if (path === '/v1/tenant-a/boxes/original-box' && method === 'GET')
        return box && !notFound ? json(box) : json({}, 404)
      if (path === '/v1/tenant-a/boxes/original-box/start') {
        expect((await state.read(['box-rest/' + name]))[0]).toBeDefined()
        box!.status = 'running'
        if (loseStart) throw new Error('Lost start response')
        return json(box)
      }
      if (path === '/v1/tenant-a/boxes/original-box/stop') {
        box!.status = 'stopped'
        return new Response(null, { status: 204 })
      }
      if (path === '/v1/tenant-a/boxes/original-box' && method === 'DELETE') {
        box = undefined
        return new Response(null, { status: 204 })
      }
      if (path === '/v1/tenant-a/boxes/original-box/files') {
        if (uploadFailed) return json({}, 503)
        afterUpload?.()
        return new Response(null, { status: 204 })
      }
      throw new Error('Unexpected test API request')
    }) as typeof fetch
    service = await BoxLiteWorkers.connect(state, 'https://box.test', 'private-box-api-key')
    lease = (await state.acquire('test-owner', 300000))!
    scope = {
      binding: 'binding',
      generation: 1,
      organization: 'tenant-a',
      actor: 'owner-a',
      installation: { id: 1, account: { id: 7, login: 'owner', type: 'User' } },
      runners: {
        kind: 'repository',
        repository: { id: 21, owner: { id: 7, login: 'owner' }, name: 'repo', private: true },
        allowPrivate: true,
        allowPublic: false,
      },
    }
    key = await journal.define(lease, scope)
    const row = (await journal.reserve(lease, key, null, testCapacity({ account: 1, tenant: 1 }), {
      labels: ['boxlite'],
      scaleSet: 9,
    }))!
    name = row.value.name
    worker = service.bind(scope, lease, async () => {
      if (!allowed) throw new Error('Admission revoked')
    })
  })
  afterEach(async () => {
    global.fetch = originalFetch
    await db.close()
    rmSync(directory, { recursive: true, force: true })
  })
  const launch = () => ({ name, image: 'runner-test', cpus: 2, memoryMiB: 2048, entrypoint: ['bash', '-c', 'run'] })
  const advance = async (change: Parameters<ExecutionJournal['advance']>[3]) => {
    const row = [...(await inspectJournal(state, lease)).allocations.values()][0]
    return journal.advance(lease, row.record.key, row.record.version, change)
  }
  const create = async () => {
    await advance({ box: { phase: 'requested', id: null }, effect: { id: randomUUID(), kind: 'box-create' } })
    const result = await worker.create(launch())
    await advance({ box: { phase: 'known', id: result.box_id } })
    return result
  }
  const prepareDelivery = async () => {
    await create()
    await advance({ runner: { phase: 'requested', id: null }, effect: { id: randomUUID(), kind: 'runner-register' } })
    await advance({ runner: { phase: 'known', id: 91 } })
    await advance({ delivery: 'requested', effect: { id: randomUUID(), kind: 'jit-deliver' } })
  }
  const posts = () => calls.filter((call) => call.path === '/v1/tenant-a/boxes' && call.method === 'POST')
  it('Docker bootstrap requests a privileged guest through REST', async () => {
    await create()
    expect(posts()[0].body).toMatchObject({ user: 'root', advanced: { privileged: true } })
  })
  describe('boxlite-workers timeout-ID recovery', () => {
    const timeoutCreate = async () => {
      await advance({ box: { phase: 'requested', id: null }, effect: { id: randomUUID(), kind: 'box-create' } })
      createHttpStatus = 408
      createHttpBody = { boxId: 'original-box', message: 'private timeout details' }
    }
    const restart = async () => {
      await db.close()
      db = new SqliteStateDatabase(directory)
      state = new ListenerState(db, namespace)
      journal = new ExecutionJournal(state)
      service = await BoxLiteWorkers.connect(state, 'https://box.test', 'private-box-api-key')
      worker = service.bind(scope, lease, async () => {
        if (!allowed) throw new Error('Admission revoked')
      })
    }
    it('persists the timeout ID before any following principal or Box read', async () => {
      await timeoutCreate()
      const previous = global.fetch
      let dispatched = false
      global.fetch = jest.fn(async (input, options) => {
        if (new URL(String(input)).pathname === '/v1/tenant-a/boxes' && options?.method === 'POST') {
          dispatched = true
        } else if (dispatched) {
          const [ledger] = await state.read(['box-rest/' + name])
          expect(ledger.payload).toMatchObject({ box: 'original-box', name, scope: key })
          expect(ledger.payload).toHaveProperty('dispatchEffect', expect.any(String))
          throw new Error('Following reads unavailable')
        }
        return previous(input, options)
      }) as typeof fetch
      await expect(worker.create(launch())).rejects.toThrow()
      const [ledger] = await state.read(['box-rest/' + name])
      expect(ledger.payload).toMatchObject({ box: 'original-box' })
      global.fetch = previous
      await restart()
      expect(await worker.get(name)).toMatchObject({ box_id: 'original-box', status: 'running' })
      expect(posts()).toHaveLength(1)
      expect(JSON.stringify(await state.recover(lease))).not.toContain('private timeout details')
    })
    it.each(['unknown', 'stopping'])(
      'retains requested recovery for %s and boots that original after restart',
      async (status) => {
        await timeoutCreate()
        initialStatus = status
        await expect(worker.create(launch())).rejects.toThrow('boot is pending')
        const unexpected = async (): Promise<never> => {
          throw new Error('Unexpected admission or runner operation')
        }
        const pool = new WorkerPool(
          journal,
          key,
          async () => ({ workers: worker, admit: unexpected, job: unexpected, runners: unexpected }),
          { image: 'runner', cpus: 2, memoryMiB: 2048, labels: ['boxlite'] },
        )
        try {
          await expect(
            pool.balanceScaleSets(lease, [], testCapacity({ account: 1, tenant: 1 }), new AbortController().signal),
          ).rejects.toThrow('boot is pending')
        } finally {
          await pool.close()
        }
        const row = [...(await inspectJournal(state, lease)).allocations.values()][0]
        expect(row.value.box).toEqual({ phase: 'requested', id: null })
        expect(await journal.hasCapacity(lease, key, testCapacity({ account: 1, tenant: 1 }))).toBe(false)
        expect(calls.filter((call) => call.path.endsWith('/start'))).toHaveLength(0)
        await restart()
        box!.status = 'configured'
        expect(await worker.get(name)).toMatchObject({ box_id: 'original-box', status: 'running' })
        expect(posts()).toHaveLength(1)
        expect(calls.filter((call) => call.path.endsWith('/start'))).toHaveLength(1)
      },
    )
    it.each(['GET', 'start'])('recovers after a failed original %s request and SQLite restart', async (operation) => {
      await timeoutCreate()
      initialStatus = 'configured'
      const previous = global.fetch
      let failures = 0
      global.fetch = jest.fn(async (input, options) => {
        const path = new URL(String(input)).pathname
        if (failures === 0 && (operation === 'GET' ? path.endsWith('/original-box') : path.endsWith('/start'))) {
          failures++
          return new Response('{}', { status: 503 })
        }
        return previous(input, options)
      }) as typeof fetch
      await expect(worker.create(launch())).rejects.toThrow('request failed')
      expect(failures).toBe(1)
      const [ledger] = await state.read(['box-rest/' + name])
      expect(ledger.payload).toMatchObject({ box: 'original-box' })
      await restart()
      expect(await worker.get(name)).toMatchObject({ box_id: 'original-box', status: 'running' })
      expect(posts()).toHaveLength(1)
    })
    it.each(['allocation', 'dispatch'])('fences timeout-ID persistence against changed %s state', async (changed) => {
      await timeoutCreate()
      const previous = global.fetch
      global.fetch = jest.fn(async (input, options) => {
        const result = await previous(input, options)
        if (new URL(String(input)).pathname === '/v1/tenant-a/boxes' && options?.method === 'POST') {
          if (changed === 'allocation') await advance({ closing: true })
          else {
            const [ledger] = await state.read(['box-rest/' + name])
            await state.commit(lease, [{ key: ledger.key, expected: ledger.version, payload: ledger.payload }])
          }
        }
        return result
      }) as typeof fetch
      await expect(worker.create(launch())).rejects.toThrow('changed')
      const [ledger] = await state.read(['box-rest/' + name])
      expect(ledger.payload).toMatchObject({ box: null })
      expect(calls.filter((call) => call.path.endsWith('/start'))).toHaveLength(0)
      expect(posts()).toHaveLength(1)
    })
    it('observes a lost start response after SQLite restart without repeating either mutation', async () => {
      await timeoutCreate()
      initialStatus = 'configured'
      loseStart = true
      await expect(worker.create(launch())).rejects.toThrow('request failed')
      await restart()
      expect(await worker.get(name)).toMatchObject({ box_id: 'original-box', status: 'running' })
      expect(posts()).toHaveLength(1)
      expect(calls.filter((call) => call.path.endsWith('/start'))).toHaveLength(1)
    })
    it('keeps an ID persistence failure uncertain without subsequent network reads', async () => {
      await timeoutCreate()
      const commit = state.commit.bind(state)
      const spy = jest.spyOn(state, 'commit').mockImplementation(async (owner, changes, checks) => {
        if (changes.some((change) => (change.payload as { box?: unknown } | undefined)?.box === 'original-box'))
          throw new Error('Original ID persistence unavailable')
        return commit(owner, changes, checks)
      })
      await expect(worker.create(launch())).rejects.toThrow('persistence unavailable')
      spy.mockRestore()
      const post = calls.findIndex((call) => call.path === '/v1/tenant-a/boxes' && call.method === 'POST')
      expect(calls.slice(post + 1)).toEqual([])
      await restart()
      await expect(worker.get(name)).rejects.toThrow('not durably known')
      expect(posts()).toHaveLength(1)
    })
    it.each(['known', 'closing'])('leaves %s observations passive', async (phase) => {
      await timeoutCreate()
      initialStatus = 'unknown'
      await worker.create(launch()).catch(() => {})
      if (phase === 'known') await advance({ box: { phase: 'known', id: 'original-box' } })
      else await advance({ closing: true })
      box!.status = 'configured'
      expect(await worker.get(name)).toMatchObject({ status: 'starting' })
      expect(calls.filter((call) => call.path.endsWith('/start'))).toHaveLength(0)
    })
    it.each([
      'admission',
      'principal',
      'effect',
      'allocation-version',
      'ledger-id',
      'ledger-effect',
      'ledger-version',
      'lease',
    ])('rechecks %s at the recovery start boundary', async (changed) => {
      await timeoutCreate()
      initialStatus = 'unknown'
      await worker.create(launch()).catch(() => {})
      box!.status = 'configured'
      const bound = service.bind(scope, lease, async () => {
        if (changed === 'admission') throw new Error('Admission revoked')
        if (changed === 'principal') principal.sub = 'different-owner'
        if (changed === 'effect') await advance({ effect: { id: randomUUID(), kind: 'box-create' } })
        if (changed === 'allocation-version') await advance({ closing: false })
        if (changed.startsWith('ledger-')) {
          const [ledger] = await state.read(['box-rest/' + name])
          await state.commit(lease, [
            {
              key: ledger.key,
              expected: ledger.version,
              payload: {
                ...(ledger.payload as object),
                ...(changed === 'ledger-id' ? { box: 'foreign-box' } : {}),
                ...(changed === 'ledger-effect' ? { dispatchEffect: randomUUID() } : {}),
              },
            },
          ])
        }
        if (changed === 'lease')
          await db.transaction(namespace, async (tx) => {
            const owner = (await tx.get('@owner', true))!
            await tx.put(
              { ...owner, version: randomUUID(), payload: { ...(owner.payload as object), epoch: lease.epoch + 1 } },
              owner.version,
            )
          })
      })
      await expect(bound.get(name)).rejects.toThrow()
      expect(calls.filter((call) => call.path.endsWith('/start'))).toHaveLength(0)
      expect(posts()).toHaveLength(1)
    })
    it('does not accept a renamed or replaced original after a timeout', async () => {
      await timeoutCreate()
      initialStatus = 'unknown'
      await worker.create(launch()).catch(() => {})
      box!.name = 'different-name'
      box!.status = 'configured'
      await expect(worker.get(name)).rejects.toThrow('identity or state changed')
      expect(calls.filter((call) => call.path.endsWith('/start'))).toHaveLength(0)
      expect(posts()).toHaveLength(1)
    })
  })
  it.each(['admission', 'principal-read'])('settles a create rejected before dispatch: %s', async (failure) => {
    const effect = randomUUID()
    const row = await advance({ box: { phase: 'requested', id: null }, effect: { id: effect, kind: 'box-create' } })
    if (failure === 'admission') allowed = false
    else {
      const previous = global.fetch
      global.fetch = jest.fn(async (input, options) => {
        if (new URL(String(input)).pathname === '/v1/me') throw new Error('Principal read unavailable')
        return previous(input, options)
      }) as typeof fetch
    }
    await expect(worker.create(launch())).rejects.toBeInstanceOf(ConfirmedWorkerCreationRejected)
    await expect(worker.create(launch())).rejects.toMatchObject({ rejectedCreationEffect: effect })
    expect(posts()).toHaveLength(0)
    const recovered = service.bind(scope, lease, async () => {
      throw new Error('Admission remains unavailable')
    })
    await expect(recovered.get(name)).rejects.toMatchObject({ rejectedCreationEffect: effect })
    await journal.rejectCreation(lease, row.record.key, row.record.version, effect)
    expect(await journal.hasCapacity(lease, key, testCapacity({ account: 1, tenant: 1 }))).toBe(true)
  })
  it('fences concurrent create attempts before either POST', async () => {
    await advance({ box: { phase: 'requested', id: null }, effect: { id: randomUUID(), kind: 'box-create' } })
    const outcomes = await Promise.allSettled([worker.create(launch()), worker.create(launch())])
    expect(posts()).toHaveLength(1)
    expect(outcomes.filter((outcome) => outcome.status === 'fulfilled')).toHaveLength(1)
  })
  it('lets durable rejection win against a create paused before dispatch', async () => {
    const effect = randomUUID(),
      row = await advance({ box: { phase: 'requested', id: null }, effect: { id: effect, kind: 'box-create' } })
    let entered!: () => void, resume!: () => void
    const started = new Promise<void>((resolve) => {
        entered = resolve
      }),
      wait = new Promise<void>((resolve) => {
        resume = resolve
      })
    meGate = { entered, wait }
    const pending = worker.create(launch()).catch((error) => error)
    await started
    try {
      const rejecting = service.bind(scope, lease, async () => {
        throw new Error('Admission revoked')
      })
      await expect(rejecting.create(launch())).rejects.toMatchObject({ rejectedCreationEffect: effect })
    } finally {
      resume()
    }
    expect(await pending).toBeInstanceOf(Error)
    expect(posts()).toHaveLength(0)
    await journal.rejectCreation(lease, row.record.key, row.record.version, effect)
    expect(await journal.hasCapacity(lease, key, testCapacity({ account: 1, tenant: 1 }))).toBe(true)
  })
  it('keeps an in-flight POST reserved when a rejection arrives late', async () => {
    const effect = randomUUID()
    await advance({ box: { phase: 'requested', id: null }, effect: { id: effect, kind: 'box-create' } })
    let entered!: () => void, resume!: () => void
    const started = new Promise<void>((resolve) => {
        entered = resolve
      }),
      wait = new Promise<void>((resolve) => {
        resume = resolve
      }),
      previous = global.fetch
    global.fetch = jest.fn(async (input, options) => {
      if (new URL(String(input)).pathname === '/v1/tenant-a/boxes' && options?.method === 'POST') {
        entered()
        await wait
      }
      return previous(input, options)
    }) as typeof fetch
    const pending = worker.create(launch())
    await started
    try {
      const rejecting = service.bind(scope, lease, async () => {
        throw new Error('Admission revoked')
      })
      await expect(rejecting.rejectUndispatchedCreate(name, effect)).rejects.not.toBeInstanceOf(
        ConfirmedWorkerCreationRejected,
      )
      expect(await journal.hasCapacity(lease, key, testCapacity({ account: 1, tenant: 1 }))).toBe(false)
      const [record] = await state.read(['box-rest/' + name])
      expect(record.payload).toMatchObject({ box: null, dispatchEffect: effect })
    } finally {
      resume()
      await pending
    }
    expect(posts()).toHaveLength(1)
  })
  it.each(['response', 'persistence'])(
    'retains an uncertain %s across SQLite restart without repeating POST',
    async (failure) => {
      await advance({ box: { phase: 'requested', id: null }, effect: { id: randomUUID(), kind: 'box-create' } })
      loseCreate = failure === 'response'
      const commit = state.commit.bind(state),
        spy = jest.spyOn(state, 'commit').mockImplementation(async (owner, changes, checks) => {
          if (
            failure === 'persistence' &&
            changes.some(
              (change) =>
                change.key === 'box-rest/' + name &&
                typeof (change.payload as { box?: unknown } | undefined)?.box === 'string',
            )
          )
            throw new Error('Original ID persistence unavailable')
          return commit(owner, changes, checks)
        })
      try {
        await expect(worker.create(launch())).rejects.toThrow()
      } finally {
        spy.mockRestore()
      }
      await db.close()
      db = new SqliteStateDatabase(directory)
      state = new ListenerState(db, namespace)
      journal = new ExecutionJournal(state)
      service = await BoxLiteWorkers.connect(state, 'https://box.test', 'private-box-api-key')
      const bound = service.bind(scope, lease, async () => {})
      await expect(bound.get(name)).rejects.toThrow('not durably known')
      const allocation = [...(await inspectJournal(state, lease)).allocations.values()][0]
      await expect(bound.rejectUndispatchedCreate(name, allocation.value.effect!.id)).rejects.not.toBeInstanceOf(
        ConfirmedWorkerCreationRejected,
      )
      const unexpected = async (): Promise<never> => {
          throw new Error('Unexpected retry effect')
        },
        pool = new WorkerPool(
          journal,
          key,
          async () => ({ workers: bound, admit: unexpected, job: unexpected, runners: unexpected }),
          { image: 'runner', cpus: 2, memoryMiB: 2048, labels: ['boxlite'] },
        )
      try {
        for (let attempt = 0; attempt < 2; attempt++)
          await expect(
            pool.balanceScaleSets(lease, [], testCapacity({ account: 1, tenant: 1 }), new AbortController().signal),
          ).rejects.toThrow()
      } finally {
        await pool.close()
      }
      expect(await journal.hasCapacity(lease, key, testCapacity({ account: 1, tenant: 1 }))).toBe(false)
      expect(posts()).toHaveLength(1)
    },
  )
  it.each(['effect', 'identity', 'lease', 'scope'])(
    'refuses a rejection after original %s changes',
    async (changed) => {
      const effect = randomUUID()
      await advance({ box: { phase: 'requested', id: null }, effect: { id: effect, kind: 'box-create' } })
      const bound = service.bind(scope, lease, async () => {})
      if (changed === 'effect') await advance({ effect: { id: randomUUID(), kind: 'box-create' } })
      if (changed === 'identity') {
        const [root] = await state.read(['backend/boxlite'])
        await state.commit(lease, [{ key: root.key, expected: root.version }])
      }
      if (changed === 'lease')
        await db.transaction(namespace, async (tx) => {
          const owner = (await tx.get('@owner', true))!,
            payload = owner.payload as { epoch: number }
          await tx.put(
            { ...owner, version: randomUUID(), payload: { ...(owner.payload as object), epoch: payload.epoch + 1 } },
            owner.version,
          )
        })
      if (changed === 'scope') {
        const [record] = await state.read(['box-rest/' + name])
        expect(record).toBeUndefined()
        const foreign = service.bind({ ...scope, binding: 'different-binding' }, lease, async () => {})
        await expect(foreign.rejectUndispatchedCreate(name, effect)).rejects.not.toBeInstanceOf(
          ConfirmedWorkerCreationRejected,
        )
        expect((await state.read(['box-rest/' + name])).length).toBe(0)
        return
      }
      await expect(bound.rejectUndispatchedCreate(name, effect)).rejects.not.toBeInstanceOf(
        ConfirmedWorkerCreationRejected,
      )
      expect((await state.read(['box-rest/' + name])).length).toBe(0)
      expect(posts()).toHaveLength(0)
    },
  )
  it('recovers durable rejection after SQLite restart while upstream verification is unavailable', async () => {
    const effect = randomUUID(),
      row = await advance({ box: { phase: 'requested', id: null }, effect: { id: effect, kind: 'box-create' } })
    allowed = false
    await expect(worker.create(launch())).rejects.toBeInstanceOf(ConfirmedWorkerCreationRejected)
    await db.close()
    db = new SqliteStateDatabase(directory)
    state = new ListenerState(db, namespace)
    journal = new ExecutionJournal(state)
    service = await BoxLiteWorkers.connect(state, 'https://box.test', 'private-box-api-key')
    const bound = service.bind(scope, lease, async () => {
      throw new Error('Admission unavailable')
    })
    global.fetch = jest.fn(async () => {
      throw new Error('All upstream reads unavailable')
    }) as typeof fetch
    await expect(bound.get(name)).rejects.toMatchObject({ rejectedCreationEffect: effect })
    await expect(bound.rejectUndispatchedCreate(name, effect)).rejects.toMatchObject({ rejectedCreationEffect: effect })
    expect(global.fetch).not.toHaveBeenCalled()
    await journal.rejectCreation(lease, row.record.key, row.record.version, effect)
    expect(await journal.hasCapacity(lease, key, testCapacity({ account: 1, tenant: 1 }))).toBe(true)
    expect(posts()).toHaveLength(0)
  })
  it('keeps a legacy requested allocation uncertain when it has no REST ledger', async () => {
    await advance({ box: { phase: 'requested', id: null }, effect: { id: randomUUID(), kind: 'box-create' } })
    await expect(worker.get(name)).rejects.toThrow('not durably known')
    expect((await state.read(['box-rest/' + name])).length).toBe(0)
    expect(await journal.hasCapacity(lease, key, testCapacity({ account: 1, tenant: 1 }))).toBe(false)
    expect(posts()).toHaveLength(0)
  })
  it('translates parsed resource quantities into the real REST create request', async () => {
    const selected = parseResourceLabels(['boxlite-2vcpu-4gbmem-10gbdisk'])!
    await advance({ box: { phase: 'requested', id: null }, effect: { id: randomUUID(), kind: 'box-create' } })
    await worker.create({ ...launch(), ...selected.resources })
    expect(posts()[0].body).toMatchObject({ cpus: 2, memory_mib: 4096, disk_size_gb: 10 })
  })
  it.each([
    { cpus: 0 },
    { cpus: 17 },
    { memoryMiB: Infinity },
    { memoryMiB: 131073 },
    { diskGiB: 0 },
    { diskGiB: 8388608 },
    { diskGiB: NaN },
  ])('rejects invalid launch resources before HTTP: %j', async (resources) => {
    await expect(worker.create({ ...launch(), ...resources })).rejects.toThrow('Invalid CI worker resources')
    expect(posts()).toHaveLength(0)
  })
  it('requires the durable intent and records a positive original ID before boot', async () => {
    await expect(worker.create(launch())).rejects.toThrow('intent missing')
    expect(posts()).toHaveLength(0)
    initialStatus = 'configured'
    expect(await create()).toMatchObject({ box_id: 'original-box', status: 'running' })
    expect(posts()[0].body).toMatchObject({
      name,
      user: 'root',
      working_dir: '/home/runner',
      memory_mib: 2048,
      auto_stop: 0,
      auto_resume: false,
    })
    const [ledger] = await state.read(['box-rest/' + name])
    expect(ledger.payload).toMatchObject({ box: 'original-box', name, scope: key })
    expect(JSON.stringify(await state.recover(lease))).not.toContain('private-box-api-key')
  })
  it('recovers a known original ID after the start response is lost without repeating create', async () => {
    initialStatus = 'configured'
    loseStart = true
    await advance({ box: { phase: 'requested', id: null }, effect: { id: randomUUID(), kind: 'box-create' } })
    await expect(worker.create(launch())).rejects.toThrow('request failed')
    expect(await worker.get(name)).toMatchObject({ box_id: 'original-box', status: 'running' })
    expect(posts()).toHaveLength(1)
  })
  it('does not adopt a same-name Box after an unknown create response', async () => {
    loseCreate = true
    await advance({ box: { phase: 'requested', id: null }, effect: { id: randomUUID(), kind: 'box-create' } })
    await expect(worker.create(launch())).rejects.toThrow()
    await expect(worker.get(name)).rejects.toThrow('not durably known')
    expect(box?.name).toBe(name)
    expect(posts()).toHaveLength(1)
    expect(calls.filter((call) => call.path.startsWith('/v1/tenant-a/boxes/') && call.method === 'GET')).toEqual([])
  })
  it.each([0, 137, null])('recovery regression: preserves the observed exit code %s', async (exit_code) => {
    await create()
    Object.assign(box!, { status: 'stopped', exit_code })
    expect(await worker.get(name)).toMatchObject({ box_id: 'original-box', status: 'stopped', exit_code })
  })
  it.each(['0', 1.5, Number.MAX_SAFE_INTEGER + 1])('rejects an invalid observed exit code %s', async (exit_code) => {
    await create()
    Object.assign(box!, { status: 'stopped', exit_code })
    await expect(worker.get(name)).rejects.toThrow('Invalid original CI Box exit code')
  })
  it('rejects another platform organization or actor before using the API', () => {
    expect(() => service.bind({ ...scope, organization: 'another' }, lease, async () => {})).toThrow('does not match')
    expect(() => service.bind({ ...scope, actor: 'another' }, lease, async () => {})).toThrow('does not match')
  })
  it('does not send a create after admission is revoked', async () => {
    allowed = false
    await expect(worker.create(launch())).rejects.toThrow('revoked')
    expect(posts()).toHaveLength(0)
  })
  it('checks the lease after an asynchronous principal request before mutation', async () => {
    await advance({ box: { phase: 'requested', id: null }, effect: { id: randomUUID(), kind: 'box-create' } })
    let entered!: () => void, resume!: () => void
    const started = new Promise<void>((resolve) => {
        entered = resolve
      }),
      wait = new Promise<void>((resolve) => {
        resume = resolve
      })
    meGate = { entered, wait }
    const pending = worker.create(launch())
    await started
    await db.transaction(namespace, async (tx) => {
      const row = (await tx.get('@owner', true))!,
        payload = row.payload as { epoch: number }
      await tx.put(
        { ...row, version: randomUUID(), payload: { ...(row.payload as object), epoch: payload.epoch + 1 } },
        row.version,
      )
    })
    resume()
    await expect(pending).rejects.toThrow('lease')
    expect(posts()).toHaveLength(0)
  })
  it('keeps a requested creation reserved when its original ID disappears from public inventory', async () => {
    await advance({ box: { phase: 'requested', id: null }, effect: { id: randomUUID(), kind: 'box-create' } })
    const original = await worker.create(launch())
    expect((await state.read(['box-rest/' + name]))[0].payload).toMatchObject({ box: original.box_id })
    notFound = true
    await expect(worker.get(name)).rejects.not.toBeInstanceOf(ConfirmedWorkerAbsent)
    expect(await journal.used(scope.organization)).toBe(1)
    expect(posts()).toHaveLength(1)
  })
  it.each(['still-listed', 'list-denied', 'principal-changed'])(
    'does not treat one 404 as absence: %s',
    async (kind) => {
      await create()
      notFound = true
      if (kind === 'still-listed') listOriginal = true
      if (kind === 'list-denied') listDenied = true
      if (kind === 'principal-changed')
        afterList = () => {
          principal.sub = 'different'
        }
      await expect(worker.get(name)).rejects.not.toBeInstanceOf(ConfirmedWorkerAbsent)
    },
  )
  it.each([
    'complete',
    'missing-items',
    'invalid-id',
    'duplicate-id',
    'repeated-token',
    'invalid-token',
    'too-many-pages',
  ])('validates the complete paginated inventory before confirming absence: %s', async (scenario) => {
    await create()
    notFound = true
    const previous = global.fetch
    let page = 0
    global.fetch = jest.fn(async (input, options) => {
      const url = new URL(String(input))
      if (url.pathname !== '/v1/tenant-a/boxes' || options?.method !== 'GET') return previous(input, options)
      page++
      if (page === 2) expect(url.searchParams.get('pageToken')).toBe('page-1')
      const payload =
        scenario === 'missing-items'
          ? {}
          : scenario === 'invalid-id'
            ? { boxes: [{ box_id: 1 }] }
            : {
                boxes: scenario === 'duplicate-id' ? [{ box_id: 'other-box' }, { box_id: 'other-box' }] : [],
                ...(scenario === 'invalid-token'
                  ? { next_page_token: 42 }
                  : scenario === 'complete' && page === 2
                    ? {}
                    : { next_page_token: scenario === 'repeated-token' ? 'page-1' : 'page-' + page }),
              }
      return new Response(JSON.stringify(payload))
    }) as typeof fetch
    if (scenario === 'complete') {
      await expect(worker.get(name)).rejects.toBeInstanceOf(ConfirmedWorkerAbsent)
      expect(page).toBe(2)
    } else await expect(worker.get(name)).rejects.not.toBeInstanceOf(ConfirmedWorkerAbsent)
  })
  it.each(['invalid-name', 'missing-allocation', 'closing'])(
    'rejects worker admission outside its original active allocation: %s',
    async (scenario) => {
      if (scenario === 'closing') await advance({ closing: true })
      const proposed =
        scenario === 'invalid-name'
          ? 'foreign-worker'
          : scenario === 'missing-allocation'
            ? 'ci-jit-' + '0'.repeat(32)
            : name
      await expect(worker.create({ ...launch(), name: proposed })).rejects.toThrow()
      expect(calls.filter((call) => call.method === 'POST')).toHaveLength(0)
    },
  )
  it('confirms absence through the original principal and a complete inventory', async () => {
    await create()
    notFound = true
    await expect(worker.get(name)).rejects.toBeInstanceOf(ConfirmedWorkerAbsent)
    expect(calls.some((call) => call.path === '/v1/tenant-a/boxes' && call.method === 'GET')).toBe(true)
  })
  it('rejects a renamed/replaced resource rather than using its returned identity', async () => {
    await create()
    box!.box_id = 'replacement'
    await expect(worker.get(name)).rejects.toThrow('identity or state changed')
  })
  it('requires a stopped original Box and separate cleanup intents before deletion', async () => {
    await create()
    await expect(worker.remove(name)).rejects.toThrow('must stop')
    await advance({ closing: true, effect: { id: randomUUID(), kind: 'box-stop' } })
    await worker.stop(name)
    await advance({ effect: { id: randomUUID(), kind: 'box-remove' } })
    await worker.remove(name)
    await expect(worker.get(name)).rejects.toBeInstanceOf(ConfirmedWorkerAbsent)
  })
  it('uploads content then ready as fixed private archives without persisting the JIT', async () => {
    await prepareDelivery()
    await worker.deliverJit(name, 'c2VjcmV0')
    const uploads = calls.filter((call) => call.method === 'PUT'),
      headers = uploads.map((call) => new Header(Buffer.from(call.body as Uint8Array)))
    expect(headers.map((header) => header.path)).toEqual(['.boxlite-jitconfig', '.boxlite-jitconfig.ready'])
    expect(headers.every((header) => header.mode === 0o600)).toBe(true)
    expect(
      Buffer.from(uploads[0].body as Uint8Array)
        .subarray(512, 520)
        .toString(),
    ).toBe('c2VjcmV0')
    expect(JSON.stringify(await state.recover(lease))).not.toContain('c2VjcmV0')
  })
  it('never publishes ready after a failed content upload', async () => {
    await prepareDelivery()
    uploadFailed = true
    await expect(worker.deliverJit(name, 'c2VjcmV0')).rejects.toThrow('request failed')
    expect(calls.filter((call) => call.method === 'PUT')).toHaveLength(1)
  })
  it('rechecks admission before publishing ready', async () => {
    await prepareDelivery()
    afterUpload = () => {
      allowed = false
    }
    await expect(worker.deliverJit(name, 'c2VjcmV0')).rejects.toThrow('revoked')
    expect(calls.filter((call) => call.method === 'PUT')).toHaveLength(1)
  })
  it('keeps get read-only even when a known Box is configured', async () => {
    await create()
    box!.status = 'configured'
    const count = calls.filter((call) => call.method === 'POST').length
    expect((await worker.get(name)).status).toBe('starting')
    expect(calls.filter((call) => call.method === 'POST')).toHaveLength(count)
  })
  it('blocks mutation if the permanent backend identity record disappears', async () => {
    const [root] = await state.read(['backend/boxlite'])
    await state.commit(lease, [{ key: root.key, expected: root.version }])
    await expect(worker.create(launch())).rejects.toThrow('identity unavailable')
    expect(posts()).toHaveLength(0)
  })
  it('keeps an opaque provider subject intact through principal, scope and allocation', async () => {
    const actor = 'provider|Case-Sensitive-Account'
    principal.sub = actor
    const local = new ListenerState(db, 'opaque:' + randomUUID()),
      gateway = await BoxLiteWorkers.connect(local, 'https://box.test', 'private-box-api-key'),
      owner = (await local.acquire('opaque-owner', 300000))!,
      ledger = new ExecutionJournal(local),
      definition = { ...scope, actor }
    const target = await ledger.define(owner, definition),
      reserved = (await ledger.reserve(owner, target, null, testCapacity({ account: 1, tenant: 1 }), {
        labels: ['boxlite'],
        scaleSet: 9,
      }))!
    await ledger.advance(owner, reserved.record.key, reserved.record.version, {
      box: { phase: 'requested', id: null },
      effect: { id: randomUUID(), kind: 'box-create' },
    })
    const result = await gateway
      .bind(definition, owner, async () => {})
      .create({ ...launch(), name: reserved.value.name })
    expect(result.box_id).toBe('original-box')
    expect(gateway.http.principal.sub).toBe(actor)
    expect((await ledger.scope(owner, target)).scope.actor).toBe(actor)
  })
  it('refuses a changed REST ledger ID at the actual stop boundary', async () => {
    await create()
    await advance({ closing: true, effect: { id: randomUUID(), kind: 'box-stop' } })
    const [ledger] = await state.read(['box-rest/' + name])
    await state.commit(lease, [
      { key: ledger.key, expected: ledger.version, payload: { ...(ledger.payload as object), box: 'foreign-box' } },
    ])
    const delegate = global.fetch
    let foreignStops = 0
    global.fetch = jest.fn(async (input, options) => {
      if (new URL(String(input)).pathname === '/v1/tenant-a/boxes/foreign-box/stop') {
        foreignStops++
        return new Response(null, { status: 204 })
      }
      return delegate(input, options)
    }) as typeof fetch
    let failure: unknown
    try {
      await worker.stop(name)
    } catch (error) {
      failure = error
    }
    expect(foreignStops).toBe(0)
    expect(failure).toBeDefined()
  })
  it('keeps an HTTP 408 mutation outcome uncertain when the server has created a Box', async () => {
    createHttpStatus = 408
    await advance({ box: { phase: 'requested', id: null }, effect: { id: randomUUID(), kind: 'box-create' } })
    let outcome: unknown
    try {
      await worker.create(launch())
    } catch (error) {
      outcome = error
    }
    expect(outcome).toBeInstanceOf(BoxLiteRequestError)
    expect(outcome).toMatchObject({ status: 408, uncertain: true })
    expect(box?.name).toBe(name)
    expect((await inspectJournal(state, lease)).allocations.size).toBe(1)
    await expect(worker.get(name)).rejects.toThrow('not durably known')
    expect(posts()).toHaveLength(1)
  })
})