Skip to content

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

11.2 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 BoxLite AI

import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { dirname, join, resolve } from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
import { runInNewContext } from 'node:vm'
import { load as loadYaml } from 'js-yaml'

const root = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
const workflow = (name = 'test.yml'): any => loadYaml(readFileSync(join(root, '.github/workflows', name), 'utf8'))
const picomatch = createRequire(import.meta.url)('picomatch') as (patterns: string[]) => (path: string) => boolean
const sdkSuites = ['rust', 'python', 'node', 'go']

function evaluate(expression: string, context: any): any {
  return runInNewContext(expression.replace(/^\$\{\{\s*|\s*\}\}$/g, '')
    .replace(/\.([a-zA-Z_][\w]*-[\w-]+)/g, '["$1"]'), context, { timeout: 1000 })
}

function context(event: string, draft = false, selected = true) {
  const github = { event_name: event, event: { pull_request: { draft } }, ref: 'refs/pull/42/merge' }
  const filter = Object.fromEntries([...sdkSuites, 'api', 'setup', 'infra'].map((suite) => [suite, String(selected)]))
  const spec = workflow().jobs.changes.outputs
  const outputs = Object.fromEntries([...sdkSuites, 'api', 'setup'].map((suite) => [suite,
    String(evaluate(spec[suite], { github, steps: { filter: { outputs: filter } } }))]))
  outputs['sdk-tests-enabled'] = String(evaluate(spec['sdk-tests-enabled'] ?? 'true', { github }))
  outputs.infra = String(selected)
  return { github, cancelled: () => false, needs: { changes: { result: 'success', outputs } } }
}

test('joining a native stack starts the required Test workflow', () => {
  const types = workflow().on.pull_request.types ?? ['opened', 'synchronize', 'reopened']
  assert.ok(types.includes('stacked'), 'stacked must start Test when an existing PR joins a native stack')
})

test('PR lifecycle triggers include becoming ready and returning to draft', () => {
  const types = workflow().on.pull_request.types ?? ['opened', 'synchronize', 'reopened']
  for (const action of ['opened', 'synchronize', 'reopened', 'ready_for_review', 'converted_to_draft']) {
    assert.ok(types.includes(action), `${action} must recalculate draft eligibility without another push`)
  }
})

for (const [event, draft, expected] of [
  ['pull_request', true, false], ['pull_request', false, true],
  ['push', false, true], ['merge_group', false, true],
  ['schedule', false, true], ['workflow_dispatch', false, true],
] as const) {
  test(`SDK jobs retain selection on ${event}, draft=${draft}`, () => {
    const jobs = workflow().jobs
    for (const suite of sdkSuites) {
      assert.equal(evaluate(jobs[suite].if, context(event, draft)), expected, suite)
      if (event !== 'schedule' && event !== 'workflow_dispatch') {
        assert.equal(evaluate(jobs[suite].if, context(event, draft, false)), false, `${suite}: unchanged files`)
      }
    }
  })
}

test('Go and Rust selection follows the artifacts each suite uses', () => {
  const jobs = workflow().jobs
  const ctx = context('pull_request')
  ctx.needs.changes.outputs.rust = 'false'
  const native = Object.entries<any>(jobs).filter(([id]) => id.startsWith('build-test-') || id === 'go' || id.startsWith('go-'))
  for (const [id, job] of native) {
    assert.equal(evaluate(job.if, ctx), true, id)
    assert.equal(evaluate(job.if, context('pull_request', true)), false, id)
  }
  ctx.needs.changes.outputs.rust = 'true'
  ctx.needs.changes.outputs.go = 'false'
  for (const [id, job] of native) {
    assert.equal(evaluate(job.if, ctx), ['build-test-guest', 'build-test-runtime'].includes(id), id)
  }
})

test('a failed native producer blocks only tests that need its artifacts', () => {
  const jobs = workflow().jobs
  const jobId = (name: string, target: string) => {
    const match = Object.keys(jobs).find(id =>
      jobs[id].name?.replace('${{ matrix.platform.target }}', target) === `${name} (${target})`)
    assert.ok(match, `${name} (${target})`)
    return match
  }
  const waitsFor = (id: string, failed: string): boolean =>
    id === failed || [jobs[id].needs ?? []].flat().some(parent => waitsFor(parent, failed))
  const x64 = 'linux-x64-gnu'
  const linuxArm = 'linux-arm64-gnu'
  const macArm = 'darwin-arm64'
  const targets = [x64, linuxArm, macArm]
  for (const [producer, target, blockedGo] of [
    ['Build Linux guest', x64, [x64]],
    ['Build Linux guest', linuxArm, [linuxArm, macArm]],
    ['Build native test inputs', x64, [x64]],
    ['Go Tests', linuxArm, [linuxArm]],
    ['Go Tests', macArm, [macArm]],
  ] as const) {
    const failed = jobId(producer, target)
    assert.deepEqual(targets.filter(t => waitsFor(jobId('Go Tests', t), failed)), blockedGo, failed)
    assert.equal(waitsFor('rust', failed), false, failed)
    assert.equal(waitsFor('rust-copy-vm', failed), target === x64, failed)
    assert.equal(waitsFor('serve-rest-e2e', failed), target === x64, failed)
    assert.ok(waitsFor('test-conclusion', failed), failed)
  }
})

test('returning to draft cancels the same PR run instead of leaving the SDK matrix active', () => {
  const concurrency = workflow().concurrency
  const draft = context('pull_request', true)
  const ready = context('pull_request', false)
  const group = (ctx: any) => concurrency.group.replace(/\$\{\{\s*(.*?)\s*\}\}/g,
    (_match: string, expression: string) => String(evaluate(expression, ctx)))
  assert.equal(group(draft), group(ready))
  assert.equal(evaluate(concurrency['cancel-in-progress'], draft), true)
})

test('drafts retain formatting, lint and API checks', () => {
  const ctx = context('pull_request', true)
  Object.assign(ctx.needs.changes.outputs, { c: 'true', quality: 'true' })
  for (const job of ['rustfmt', 'clippy', 'python', 'node', 'c', 'go']) {
    assert.equal(evaluate(workflow('lint.yml').jobs[job].if, ctx), true, job)
  }
  assert.equal(evaluate(workflow().jobs.api.if, ctx), true)
})

test('workflow and infrastructure changes run hosted regressions even on drafts', () => {
  const spec = workflow()
  const infra = spec.jobs.infra
  assert.ok(infra, 'lightweight CI needs the infrastructure regression suite')
  assert.equal(evaluate(infra.if, context('pull_request', true)), true)
  assert.equal(evaluate(infra.if, context('pull_request', true, false)), false)
  assert.ok(infra.steps.some((step: any) => step.run === 'make coverage:infra'))
  assert.ok(!infra.steps.some((step: any) => step.uses === './.github/actions/setup-infra'),
    'regressions need no Pulumi CLI, stage configuration, or deployment setup')
  const filter = spec.jobs.changes.steps.find((step: any) => step.uses?.startsWith('dorny/paths-filter'))
  const matches = picomatch((loadYaml(filter.with.filters) as any).infra)
  for (const path of ['apps/infra/deployment/draft-ci.test.ts', '.github/workflows/test.yml', '.github/actions/setup-go/action.yml', '.github/ci-config.json', 'Makefile', 'make/test.mk', 'make/coverage.mk', 'make/changes.mk']) {
    assert.equal(matches(path), true, path)
  }
  assert.ok(infra.steps.some((step: any) => step.run === 'make test:unit:scripts'))
  for (const path of ['scripts/build/download-archive.sh', 'scripts/build/build-libseccomp.sh', 'scripts/build/retry-fetch.sh',
    'scripts/build/install-apk.sh', 'scripts/setup/setup-common.sh', 'apps/proxy/Dockerfile', 'scripts/util.sh']) {
    assert.equal(matches(path), true, path)
  }
  for (const path of ['docs/README.md', '.github/workflows/README.md', 'sdks/go/options.go']) {
    assert.equal(matches(path), false, path)
  }
})

test('deferring SDK coverage never substitutes a no-coverage-changes upload', () => {
  const ctx = context('pull_request', true)
  ctx.needs.changes.outputs.api = 'false'
  for (const suite of sdkSuites) assert.equal(ctx.needs.changes.outputs[suite], 'true', suite)
  assert.equal(evaluate(workflow().jobs['coverage-empty'].if, ctx), false)
})

test('the required conclusion propagates infrastructure regression failures', () => {
  const conclusion = workflow().jobs['test-conclusion']
  assert.ok(conclusion.needs.includes('infra'), 'hosted regression failures must block the required conclusion')
  for (const result of ['success', 'skipped', 'failure', 'cancelled']) {
    const needs = Object.fromEntries(conclusion.needs.map((name: string) => [name, { result: name === 'infra' ? result : 'skipped' }]))
    const script = conclusion.steps[0].run.replaceAll('${{ toJSON(needs) }}', JSON.stringify(needs))
    const run = spawnSync('bash', ['-eo', 'pipefail', '-c', script], { encoding: 'utf8', timeout: 10_000 })
    assert.equal(run.error, undefined)
    assert.equal(run.status === 0, result === 'success' || result === 'skipped', run.stderr)
  }
})

test('release Rust runs on macOS even without a Rust path change', () => {
  const jobs = workflow().jobs
  const ctx = context('merge_group', false, false)
  const outputs = ctx.needs.changes.outputs
  outputs['is-release'] = 'true'
  assert.equal(evaluate(jobs['rust-macos'].if, ctx), true)
  assert.equal(evaluate(jobs.rust.if, ctx), false)
  assert.equal(evaluate(jobs['rust-copy-vm'].if, ctx), false)
  outputs.rust = 'true'
  assert.equal(evaluate(jobs.rust.if, ctx), true)
  outputs.go = 'true'
  assert.equal(evaluate(jobs['go-darwin-arm64'].if, ctx), true)
  outputs['is-release'] = 'false'
  assert.equal(evaluate(jobs['rust-macos'].if, ctx), false)
  assert.equal(evaluate(jobs['go-darwin-arm64'].if, ctx), false)
  assert.equal(evaluate(jobs['go-linux-arm64'].if, ctx), true)
})

test('queue conclusion requires successful macOS jobs for the selected release suites', () => {
  const job = workflow().jobs['test-conclusion']
  const ctx = context('merge_group')
  assert.equal(evaluate(job.if, { ...ctx, cancelled: () => true }), true)
  const gate = job.steps.find((s: any) => s.env?.TEST_JOBS)
  assert.equal(evaluate(gate.if, ctx), true)
  assert.equal(gate.env.TEST_JOBS, '${{ toJSON(needs) }}')
  const results = Object.fromEntries(job.needs.map((id: string) => [id, { result: 'success' }]))
  const mac = JSON.stringify([{ target: 'darwin-arm64' }])
  const sdk = JSON.stringify([{ platform: { target: 'darwin-arm64' } }])
  const plan: Record<string, string> = { ...ctx.needs.changes.outputs, 'is-release': 'true', 'darwin-arm64': mac,
    'python-test-matrix': sdk, 'node-test-matrix': sdk }
  results.changes.outputs = plan
  const passes = () => spawnSync('bash', ['-ec', gate.run], {
    env: { ...process.env, TEST_JOBS: JSON.stringify(results) },
  }).status === 0
  assert.equal(passes(), true)
  for (const id of ['rust-macos', 'python', 'node', 'go-darwin-arm64']) {
    for (const result of ['skipped', 'cancelled', 'failure']) {
      results[id].result = result
      assert.equal(passes(), false, id + ' ' + result)
    }
    results[id].result = 'success'
  }
  plan['node-test-matrix'] = '[]'
  assert.equal(passes(), false, 'Linux-only SDK success cannot qualify a release')
  plan.node = 'false'
  results.node.result = 'skipped'
  assert.equal(passes(), true, 'unselected SDK may skip')
  plan['is-release'] = ''
  assert.equal(passes(), false, 'unknown queue classification cannot pass')
  plan['is-release'] = 'false'
  results['rust-macos'].result = 'skipped'
  assert.equal(passes(), true)
})