Skip to content

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

48.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 { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { createRequire } from 'node:module'
import test from 'node:test'
import { runInNewContext } from 'node:vm'
import { data, Evaluator, Lexer, Parser } from '@actions/expressions'
import { load as loadYaml } from 'js-yaml'
import { parse as parseToml } from 'smol-toml'

const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
// Use the glob engine used by paths-filter, including its extglob behavior.
const picomatch = createRequire(import.meta.url)('picomatch') as (pattern: string, options: { dot: boolean }) => (path: string) => boolean
const workflow = (name: string): any => loadYaml(readFileSync(join(REPO_ROOT, '.github/workflows', name), 'utf8'))
const matches = (pattern: string, path: string) => picomatch(pattern, { dot: true })(path)

function matrixRunner(selection: string, os: string, inputs = new data.Dictionary()) {
  const osEntry = { key: 'os', value: new data.StringData(os) }
  const context = new data.Dictionary(
    { key: 'matrix', value: new data.Dictionary(osEntry, { key: 'platform', value: new data.Dictionary(osEntry) }) },
    { key: 'inputs', value: inputs },
  )
  const expression = selection.replace(/^\$\{\{\s*|\s*\}\}$/g, '')
  const ast = new Parser(new Lexer(expression).lex().tokens, ['matrix', 'inputs'], []).parse()
  return new Evaluator(ast, context).evaluate().coerceString()
}

for (const [name, job, linuxRunner] of [
  ['lint.yml', 'clippy', 'boxlite-4vcpu-16gbmem-64gbdisk'],
  ['test.yml', 'guest_artifacts', 'boxlite-4vcpu-16gbmem-64gbdisk'],
  ['test.yml', 'python', 'boxlite'],
  ['test.yml', 'node', 'boxlite'],
  ['build-c.yml', 'build', 'boxlite-4vcpu-16gbmem-64gbdisk'],
  ['build-node.yml', 'build', 'boxlite-4vcpu-16gbmem-64gbdisk'],
  ['build-runtime.yml', 'build', 'boxlite-4vcpu-16gbmem-64gbdisk'],
  ['build-wheels.yml', 'build_wheels', 'boxlite-4vcpu-16gbmem-64gbdisk'],
  ['build-go.yml', 'test', 'boxlite-4vcpu-16gbmem-30gbdisk'],
  ['build-node.yml', 'test', 'boxlite-4vcpu-16gbmem-30gbdisk'],
] as const) {
  test(`${name}/${job} uses BoxLite for Linux x64 and native runners for other platforms`, () => {
    const { platforms } = JSON.parse(readFileSync(join(REPO_ROOT, '.github/ci-config.json'), 'utf8'))
    const selection = workflow(name).jobs[job]['runs-on']
    for (const { os, target } of platforms) {
      const expected = target === 'linux-x64-gnu' ? linuxRunner : os
      assert.equal(matrixRunner(selection, os), expected, os)
    }
  })
}

for (const [name, job, runner] of [
  ['build-go.yml', 'config', 'boxlite'],
  ['build-plugins.yml', 'build', 'boxlite'],
  ['api-client-drift.yml', 'check-generated-clients', 'boxlite-2vcpu-8gbmem-30gbdisk'],
  ['test.yml', 'dashboard', 'boxlite-2vcpu-8gbmem-30gbdisk'],
  ['test.yml', 'secret-server-postgres', 'boxlite-2vcpu-4gbmem-30gbdisk'],
  ['test.yml', 'nix', 'boxlite-4vcpu-16gbmem-64gbdisk'],
  ['test.yml', 'serve-rest-e2e', 'boxlite-4vcpu-16gbmem-64gbdisk'],
  ['build-box-images.yml', 'build', 'boxlite-4vcpu-16gbmem-64gbdisk'],
] as const) {
  test(`${name}/${job} requests its qualified BoxLite runner`, () => {
    assert.equal(workflow(name).jobs[job]['runs-on'], runner)
  })
}

for (const [name, job, downloads] of [
  ['test.yml', 'dashboard', '8'],
  ['api-client-drift.yml', 'check-generated-clients', '4'],
] as const) {
  test(`${name}/${job} bounds cold Yarn downloads for its worker`, () => {
    const install = workflow(name).jobs[job].steps.find((step: any) => step.run === 'yarn install --immutable')
    assert.equal(install?.env?.YARN_NETWORK_CONCURRENCY, downloads)
  })
}

for (const [name, job, matrix] of [
  ['release-box-images.yml', 'release', false],
  ['test.yml', 'api', false],
  ['test.yml', 'rust', true],
  ['test.yml', 'go', true],
] as const) {
  test(`${name}/${job} uses GitHub-hosted Ubuntu`, () => {
    const selection = workflow(name).jobs[job]['runs-on']
    assert.equal(matrix ? matrixRunner(selection, 'ubuntu-latest') : selection, 'ubuntu-latest')
  })
}

test('selected-commit and recovery C SDK builds can run independently of BoxLite', () => {
  const selection = workflow('build-c.yml').jobs.build['runs-on']
  for (const input of [
    { key: 'ref', value: new data.StringData('a'.repeat(40)) },
    { key: 'linux_x64_only', value: new data.BooleanData(true) },
  ]) {
    assert.equal(matrixRunner(selection, 'ubuntu-latest', new data.Dictionary(input)), 'ubuntu-latest')
  }
})

test('the C SDK worker installs its host tools before checking out a selected commit', () => {
  const steps = workflow('build-c.yml').jobs.build.steps
  const bootstrap = steps.findIndex((step: any) => step.if?.includes("runner.environment == 'self-hosted'"))
  const checkout = steps.findIndex((step: any) => step.uses?.startsWith('actions/checkout@'))
  assert.ok(bootstrap >= 0 && bootstrap < checkout, 'worker setup must precede the selected source')
  assert.match(steps[bootstrap].run, /apt-get install/)
})

for (const [file, job] of [
  ['build-node.yml', 'build'], ['build-node.yml', 'test'],
  ['build-runtime.yml', 'build'], ['build-wheels.yml', 'build_wheels'],
]) {
  test(`${file}/${job} loads worker setup from the workflow commit before checking out the build source`, () => {
    const steps = workflow(file).jobs[job].steps
    const setupIndex = steps.findIndex((step: any) => step.uses === './.github/actions/setup-boxlite-runner')
    const sourceIndex = steps.findIndex((step: any) => step.uses?.startsWith('actions/checkout@') && step.with?.ref?.includes('inputs.ref'))
    assert.ok(setupIndex >= 0 && setupIndex < sourceIndex, 'older source commits can lack the worker setup action')
    const tools = steps[setupIndex - 1]
    assert.match(tools.uses, /^actions\/checkout@/)
    assert.equal(tools.with.ref, '${{ github.sha }}')
    assert.equal(tools.if, steps[setupIndex].if)
  })
}

test('Linux x64 wheel packaging initializes the host Python used by cibuildwheel', () => {
  const steps = workflow('build-wheels.yml').jobs.build_wheels.steps
  const python = steps.findIndex((step: any) => step.uses?.startsWith('actions/setup-python@'))
  const build = steps.findIndex((step: any) => step.uses?.startsWith('pypa/cibuildwheel@'))
  assert.ok(python >= 0 && python < build, 'prepare the host interpreter before invoking cibuildwheel')
  const guard = new Parser(new Lexer(steps[python].if).lex().tokens, ['matrix', 'steps'], []).parse()
  for (const os of ['ubuntu-latest', 'ubuntu-24.04-arm', 'macos-15']) {
    for (const hit of ['true', '']) {
      const context = { matrix: { os }, steps: { cache: { outputs: { hit } } } }
      const actual = new Evaluator(guard, JSON.parse(JSON.stringify(context), data.reviver)).evaluate()
      assert.equal(actual.coerceString(), String(os === 'ubuntu-latest' && hit !== 'true'))
    }
  }
  assert.equal(steps[python].with['python-version'], '3.11 - 3.13')
})

test('CodeQL places every language on its qualified runner and retains its build mode', () => {
  const job = workflow('codeql.yml').jobs.analyze
  assert.equal(job['runs-on'], '${{ matrix.runner }}')
  assert.deepEqual(job.strategy.matrix.include, [
    { language: 'actions', 'build-mode': 'none', runner: 'boxlite' },
    { language: 'c-cpp', 'build-mode': 'none', runner: 'boxlite-2vcpu-4gbmem-30gbdisk' },
    { language: 'go', 'build-mode': 'autobuild', runner: 'boxlite-4vcpu-8gbmem-30gbdisk' },
    { language: 'javascript-typescript', 'build-mode': 'none', runner: 'boxlite-4vcpu-16gbmem-64gbdisk' },
    { language: 'python', 'build-mode': 'none', runner: 'boxlite' },
    { language: 'rust', 'build-mode': 'none', runner: 'boxlite-4vcpu-16gbmem-64gbdisk' },
  ])
})

function testSuites(paths: string[]) {
  const filter = workflow('test.yml').jobs.changes.steps.find((step: any) => step.uses?.startsWith('dorny/paths-filter'))
  const rules = loadYaml(filter.with.filters) as Record<string, string[]>
  return Object.keys(rules).filter((suite) => paths.some((path) => rules[suite].some((pattern) => matches(pattern, path))))
}

function acceptsFiles(name: string, event: string, files: string[]) {
  const trigger = workflow(name).on[event]
  if (trigger?.['paths-ignore'] && files.every((file) => trigger['paths-ignore'].some((pattern: string) => matches(pattern, file)))) return false
  if (!trigger?.paths) return true
  return files.some((file) => trigger.paths.reduce((included: boolean, pattern: string) => {
    const exclude = pattern.startsWith('!')
    return matches(exclude ? pattern.slice(1) : pattern, file) ? !exclude : included
  }, false))
}

for (const path of ['sdks/go/README.md', 'sdks/python/README.md', 'sdks/node/README.md', 'src/cli/README.md', 'apps/api/README.md', 'make/help.mk', 'make/clean.mk']) {
  test(`unrelated prose or Make utilities do not rebuild SDKs: ${path}`, () => {
    assert.deepEqual(testSuites([path]), [])
  })
}

test('SDK test documentation does not rebuild SDKs: sdks/python/tests/README.md', () => {
  assert.deepEqual(testSuites(['sdks/python/tests/README.md']), [])
})

test('changing only the Python packaging configuration selects the Python and infra suites', () => {
  assert.deepEqual(testSuites(['sdks/python/pyproject.toml']), ['python', 'infra'])
})

// The infra job runs the script tests on any tests/scripts change; that
// directory's prose still builds no SDK.
test('script test documentation selects only the infra suite: tests/scripts/README.md', () => {
  assert.deepEqual(testSuites(['tests/scripts/README.md']), ['infra'])
})

for (const [path, expected] of [
  ['sdks/go/options.go', ['rust', 'go']],
  ['sdks/go/integration/archive/checkpoint_test.go', ['rust', 'go']],
  ['apps/runner/cmd/runner/main.go', ['go']],
  ['apps/secret-server/internal/encryption/cipher.go', ['go', 'api']],
  ['apps/secret-server/internal/encryption/cipher_test.go', ['go']],
  ['apps/secret-server/go.mod', ['go', 'api']],
  ['apps/secret-server/tests/secret-list-api.sh', ['go', 'api']],
  ['sdks/python/boxlite/options.py', ['rust', 'python']],
  ['sdks/python/boxlite/sync_api/_ssh.py', ['rust', 'python']],
  ['sdks/python/tests/test_ssh_native_rest.py', ['rust', 'python']],
  ['scripts/test/coverage-bindings.sh', ['rust', 'infra']],
  ['tests/scripts/test_native_coverage.py', ['rust', 'infra']],
  ['sdks/node/lib/options.ts', ['node']],
  ['src/cli/src/main.rs', ['rust']],
  ['src/vmm/src/vm.rs', ['rust', 'vmm']],
  ['src/vmm/boot/kernel.lock', ['rust', 'vmm']],
  ['make/coverage.mk', ['rust', 'vmm', 'python', 'node', 'go', 'api', 'infra']],
  ['make/quality.mk', ['go']],
  ['.github/workflows/lint.yml', ['go', 'infra']],
  ['openapi/box.openapi.yaml', ['rust', 'api']],
  ['openapi/admin.openapi.yaml', ['rust', 'api']],
] as const) {
  test(`source and shared recipes retain their tests: ${path}`, () => {
    assert.deepEqual(testSuites(['docs/README.md', path]), [...expected])
  })
}

// Anything a suite filter selects on must also reach the workflow that runs
// the filter, or a push to main changes the suite's inputs and tests nothing.
for (const path of ['apps/runner/cmd/runner/main.go', 'apps/secret-server/internal/encryption/cipher.go', 'apps/secret-server/internal/encryption/cipher_test.go', 'apps/secret-server/go.mod', 'apps/go.work', 'apps/go.work.sum', 'openapi/box.openapi.yaml', 'openapi/admin.openapi.yaml']) {
  test(`a push that selects a suite reaches the Test workflow: ${path}`, () => {
    assert.equal(acceptsFiles('test.yml', 'push', [path]), true)
  })
}

test('Go coverage uploads the Secret Server report', () => {
  const upload = workflow('test.yml').jobs.go.steps.find((step: any) => step.uses?.startsWith('codecov/codecov-action'))
  assert.ok(upload.with.files.split(',').includes('target/coverage/secret-server.out'))
})

// The rust job runs the external coverage collector; its inputs must also
// reach the workflow on push, or a main-branch change tests nothing.
for (const path of ['scripts/test/coverage-bindings.sh', 'tests/scripts/test_native_coverage.py']) {
  test(`a push that selects the rust suite reaches the Test workflow: ${path}`, () => {
    assert.equal(acceptsFiles('test.yml', 'push', [path]), true)
  })
}

// The nix job rebuilds the CLI in the flake dev shell; it must follow every
// input of `make cli` there, including on push to main, and nothing else.
for (const path of ['flake.nix', 'flake.lock', 'src/deps/libkrun-sys/build.rs', 'src/shared/build.rs',
  'scripts/build/build-shim.sh', 'scripts/common.sh', 'scripts/setup/setup-common.sh', 'make/build.mk',
  'Cargo.lock', 'rust-toolchain.toml', '.github/actions/sccache/action.yml', '.github/actions/setup-boxlite-runner/action.yml']) {
  test(`a change to a dev shell build input runs the nix job: ${path}`, () => {
    assert.ok(testSuites([path]).includes('nix'))
    assert.equal(acceptsFiles('test.yml', 'push', [path]), true)
  })
}

for (const path of ['docs/README.md', 'make/help.mk', 'src/deps/libkrun-sys/README.md', 'sdks/go/options.go']) {
  test(`a change outside the dev shell build skips the nix job: ${path}`, () => {
    assert.ok(!testSuites([path]).includes('nix'))
  })
}

test('the nix job reports without blocking the required conclusion', () => {
  const jobs = workflow('test.yml').jobs
  assert.equal(jobs.nix.if, "needs.changes.outputs.nix == 'true'")
  assert.ok(!jobs['test-conclusion'].needs.includes('nix'), 'nix stays non-blocking until it proves stable')
  // The weekly run skips it: flake.lock pins its inputs. Dispatch still runs it.
  for (const [event, expected] of [['schedule', false], ['workflow_dispatch', true]] as const) {
    const selected = runInNewContext(jobs.changes.outputs.nix.replace(/^\$\{\{\s*|\s*\}\}$/g, ''), {
      github: { event_name: event }, steps: { filter: { outputs: {} } },
    }, { timeout: 1000 })
    assert.equal(selected, expected, event)
  }
})

for (const [name, events] of [
  ['codeql.yml', ['pull_request', 'push']],
  ['e2e-local.yml', ['pull_request_target', 'push']],
  ['api-client-drift.yml', ['pull_request']],
] as const) {
  for (const event of events) {
    test(`${name} skips documentation-only ${event} changes but keeps code changes`, () => {
      assert.equal(acceptsFiles(name, event, ['sdks/go/README.md', 'apps/api/README.md']), false)
      assert.equal(acceptsFiles(name, event, ['docs/README.md', 'apps/api/src/main.ts', 'sdks/go/options.go']), true)
    })
  }
}

test('Go vet and golangci-lint reuse the Linux coverage build', () => {
  const steps = workflow('test.yml').jobs.go.steps
  const buildAt = steps.findIndex((step: any) => step.run === 'make coverage:go')
  const vetAt = steps.findIndex((step: any) => step.run === 'make lint:go')
  const lintAt = steps.findIndex((step: any) => step.uses?.startsWith('golangci/golangci-lint-action'))
  assert.ok(buildAt >= 0 && vetAt > buildAt && lintAt > buildAt, 'Go analysis must reuse the native library produced by coverage')
  for (const index of [vetAt, lintAt]) assert.equal(steps[index].if, "matrix.platform.target == 'linux-x64-gnu'")
  assert.match(steps[lintAt].uses, /@[0-9a-f]{40}$/, 'Go analysis with OIDC access must use an immutable action revision')
  const formatting = workflow('lint.yml').jobs.go.steps
  assert.ok(formatting.some((step: any) => step.run === 'make fmt:check:go'))
  assert.ok(!formatting.some((step: any) => /dev:go|setup:build/.test(step.run ?? '')), 'formatting must not build the native runtime')
})

test('all six manual component builds are selected through mbuild-release', () => {
  const commands = workflow('mbuild-release.yml').on.workflow_dispatch.inputs.command.options
  for (const component of ['runtime', 'wheels', 'node', 'c', 'go', 'runner']) {
    const file = component === 'runner' ? 'build-runner-binary.yml' : 'build-' + component + '.yml'
    const triggers = workflow(file).on
    assert.deepEqual(Object.keys(triggers).sort(), component === 'runtime' ? ['schedule', 'workflow_call'] : ['workflow_call'], file)
    assert.ok(commands.includes('publish-' + component), component)
  }
})

for (const event of ['pull_request', 'push', 'merge_group', 'schedule', 'workflow_dispatch']) {
  test(`guest artifact qualification is scheduled or manual only: ${event}`, () => {
    const workflow: any = loadYaml(readFileSync(join(REPO_ROOT, '.github/workflows/test.yml'), 'utf8'))
    const expression = workflow.jobs.guest_artifacts.if.replace(/^\$\{\{\s*|\s*\}\}$/g, '')
    // This gate uses property access, string equality and boolean operators,
    // which have the same semantics here in Actions expressions and JavaScript.
    const shouldRun = runInNewContext(expression, {
      github: { event_name: event },
      needs: { changes: { outputs: { guest_artifacts: 'true' } } },
    }, { timeout: 1000 })
    assert.equal(shouldRun, event === 'schedule' || event === 'workflow_dispatch',
      `${event} must not start guest artifact builds unless explicitly scheduled or dispatched`)
    assert.ok(event in workflow.on, `the workflow must still accept ${event}`)
  })
}

for (const result of ['skipped', 'success', 'failure', 'cancelled']) {
  test(`Test conclusion handles guest artifact result: ${result}`, () => {
    const workflow: any = loadYaml(readFileSync(join(REPO_ROOT, '.github/workflows/test.yml'), 'utf8'))
    const conclusion = workflow.jobs['test-conclusion']
    assert.ok(conclusion.needs.includes('guest_artifacts'))
    const needs = Object.fromEntries(conclusion.needs.map((name: string) => [name, {
      result: name === 'guest_artifacts' ? result : 'success',
    }]))
    const script = conclusion.steps[0].run.replaceAll('${{ toJSON(needs) }}', JSON.stringify(needs))
    const execution = spawnSync('bash', ['-eo', 'pipefail', '-c', script], {
      encoding: 'utf8',
      timeout: 10_000,
    })
    assert.equal(execution.error, undefined)
    assert.equal(execution.status === 0, result === 'success' || result === 'skipped', execution.stderr)
  })
}

const coverageWorkflow: any = loadYaml(readFileSync(join(REPO_ROOT, '.github/workflows/test.yml'), 'utf8'))
const coverageSuites = ['rust', 'python', 'node', 'go', 'api', 'dashboard', 'plugins', 'infra']

for (const path of ['scripts/plugins/boxlite.py', 'scripts/plugins/.coveragerc',
  'tests/plugins/test_boxlite_package.py', 'plugins/boxlite/skills/boxlite-setup/SKILL.md',
  'plugins/boxlite-codex/plugin.json', 'make/plugins.mk', '.agents/plugins/marketplace.json']) {
  test(`plugin inputs select real coverage on PRs and main pushes: ${path}`, () => {
    assert.deepEqual(testSuites([path]), ['plugins'])
    assert.equal(acceptsFiles('test.yml', 'push', [path]), true)
  })
}

test('repository marketplace-only pushes reach plugin coverage workflow', () => {
  assert.equal(acceptsFiles('test.yml', 'push', ['.agents/plugins/marketplace.json']), true)
})

function checkCoverageJob(suite: string, command: string, report: string) {
  const jobs = coverageWorkflow.jobs
  const job = jobs[suite]
  assert.ok(job, `${suite} source changes need a real coverage job`)
  const evaluate = (expression: string, context: any) => runInNewContext(
    expression.replace(/^\$\{\{\s*|\s*\}\}$/g, ''), context, { timeout: 1000 })
  for (const event of ['pull_request', 'push', 'merge_group', 'schedule', 'workflow_dispatch']) {
    for (const selected of ['true', 'false']) {
      const github = { event_name: event, event: { pull_request: { draft: true } } }
      const output = String(evaluate(jobs.changes.outputs[suite], { github, steps: { filter: { outputs: { [suite]: selected } } } }))
      assert.equal(evaluate(job.if, { github, needs: { changes: { outputs: { [suite]: output } } } }),
        selected === 'true' || event === 'schedule' || event === 'workflow_dispatch')
    }
  }
  assert.ok(job.steps.some((step: any) => step.run === command))
  const upload = job.steps.find((step: any) => step.uses?.startsWith('codecov/codecov-action@'))
  assert.equal(upload?.with?.files, report)
  assert.equal(upload.with.flags, suite)
  assert.equal(upload.with.use_oidc, true)
  assert.equal(upload.with.disable_search, true)
  assert.equal(upload.with.fail_ci_if_error, true)
  assert.equal(upload.with.force, undefined)
  assert.equal(job.permissions['id-token'], 'write')
  const conclusion = jobs['test-conclusion']
  assert.ok(conclusion.needs.includes(suite))
  for (const result of ['success', 'skipped', 'failure', 'cancelled']) {
    const needs = Object.fromEntries(conclusion.needs.map((name: string) => [name, { result: name === suite ? result : 'success' }]))
    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)
  }
}

for (const [suite, command, report] of [
  ['plugins', 'make plugin:boxlite:coverage', 'target/coverage/plugins/coverage.xml'],
  ['infra', 'make coverage:infra', 'target/coverage/infra/lcov.info'],
]) {
  test(`${suite} coverage runs on drafts and propagates report/upload failures`, () => checkCoverageJob(suite, command, report))
}

function selectsEmptyCoverage(outputs: Record<string, string>, result = 'success', event = 'pull_request') {
  const job = coverageWorkflow.jobs['coverage-empty']
  assert.ok(job, 'intentionally skipped coverage must still publish a Codecov result')
  // This guard uses the common boolean/equality subset of Actions expressions.
  return runInNewContext(job.if.replace(/^\$\{\{\s*|\s*\}\}$/g, ''), {
    github: { event_name: event },
    needs: { changes: { result, outputs } },
  }, { timeout: 1000 })
}

test('documentation-only PRs and merge groups request a validated empty upload', () => {
  const outputs = Object.fromEntries(coverageSuites.map((suite) => [suite, 'false']))
  for (const event of ['pull_request', 'merge_group']) {
    assert.equal(selectsEmptyCoverage(outputs, 'success', event), true)
    assert.ok(Object.hasOwn(coverageWorkflow.on, event))
    assert.equal(coverageWorkflow.on[event]?.paths, undefined)
    assert.equal(coverageWorkflow.on[event]?.['paths-ignore'], undefined)
  }
  const job = coverageWorkflow.jobs['coverage-empty']
  assert.equal(job.needs, 'changes')
  assert.equal(job.permissions['id-token'], 'write')
  const upload = job.steps.find((step: any) => step.uses?.startsWith('codecov/codecov-action@'))
  assert.equal(upload?.with?.run_command, 'empty-upload')
  assert.equal(upload.with.force, undefined, 'Codecov must validate the changed files')
  assert.equal(upload.with.use_oidc, true)
  assert.equal(upload.with.fail_ci_if_error, true)
})

test('empty upload cannot replace a selected suite or failed change detection', () => {
  const outputs = Object.fromEntries(coverageSuites.map((suite) => [suite, 'false']))
  for (const suite of coverageSuites) {
    for (const value of ['true', '', 'unknown']) {
      assert.equal(selectsEmptyCoverage({ ...outputs, [suite]: value }), false, `${suite}=${value}`)
    }
    const missing = { ...outputs }
    delete missing[suite]
    assert.equal(selectsEmptyCoverage(missing), false, `missing ${suite}`)
  }
  for (const result of ['failure', 'cancelled', 'skipped']) {
    assert.equal(selectsEmptyCoverage(outputs, result), false, result)
  }
  for (const event of ['push', 'schedule', 'workflow_dispatch']) {
    assert.equal(selectsEmptyCoverage(outputs, 'success', event), false, event)
  }
})

test('the required conclusion fails when the empty upload fails', () => {
  const job = coverageWorkflow.jobs['test-conclusion']
  assert.ok(job.needs.includes('coverage-empty'), 'the required check must wait for the empty upload')
  for (const [result, succeeds] of [['success', true], ['skipped', true], ['failure', false], ['cancelled', false]] as const) {
    const needs = Object.fromEntries(job.needs.map((name: string) => [name, { result: name === 'coverage-empty' ? result : 'success' }]))
    const script = job.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, succeeds, `${result}: ${run.stderr}`)
  }
})

test('patch coverage requires 90 percent and a report while total stays informational', () => {
  const config: any = loadYaml(readFileSync(join(REPO_ROOT, 'codecov.yml'), 'utf8'))
  assert.equal(config.coverage.status.patch.default.target, '90%')
  assert.equal(config.coverage.status.patch.default.threshold, '0%')
  assert.equal(config.coverage.status.patch.default.if_not_found, 'failure')
  assert.equal(config.coverage.status.project.default.informational, true)
})

test('Linux x64 native SDK coverage installs Go and uploads its archive profile', () => {
  const steps = workflow('test.yml').jobs.rust.steps
  const goAt = steps.findIndex((step: any) => step.uses === './.github/actions/setup-go')
  const nativeAt = steps.findIndex((step: any) => step.run === 'make coverage:bindings:external')
  const uploadAt = steps.findIndex((step: any) => step.with?.files?.split(',').includes('target/coverage/go-checkpoint-native.out'))
  assert.ok(goAt >= 0 && goAt < nativeAt && nativeAt < uploadAt)
  for (const at of [goAt, nativeAt, uploadAt]) {
    for (const target of ['linux-x64-gnu', 'linux-arm64-gnu', 'darwin-arm64']) {
      const expression = steps[at].if.replace(/^\$\{\{\s*|\s*\}\}$/g, '')
      assert.equal(runInNewContext(expression, { matrix: { platform: { target } } }), target === 'linux-x64-gnu')
    }
    assert.equal(steps[at]['continue-on-error'], undefined)
  }
})

test('Linux x64 KVM hardware coverage joins unit profiles before upload', () => {
  const steps = workflow('test.yml').jobs.rust.steps
  const hardwareAt = steps.findIndex((step: any) => step.run === 'make coverage:vmm:kvm')
  const unitAt = steps.findIndex((step: any) => step.run === 'make coverage:lcov NEXTEST_PROFILE=ci')
  const uploadAt = steps.findIndex((step: any) => step.uses?.startsWith('codecov/codecov-action'))
  assert.ok(hardwareAt > unitAt && hardwareAt < uploadAt,
    'ignored KVM tests must contribute coverage after units and before upload')
  for (const target of ['linux-x64-gnu', 'linux-arm64-gnu', 'darwin-arm64']) {
    const expression = steps[hardwareAt].if.replace(/^\$\{\{\s*|\s*\}\}$/g, '')
    assert.equal(runInNewContext(expression, { matrix: { platform: { target } } }), target === 'linux-x64-gnu')
  }
  assert.equal(steps[hardwareAt]['continue-on-error'], undefined,
    'missing hardware or failed tests must fail CI')
})

test('Linux x64 builds the kernel and runs the boot tests only for vmm changes, before upload', () => {
  const steps = workflow('test.yml').jobs.rust.steps
  const kernelAt = steps.findIndex((step: any) => step.id === 'vmm-kernel')
  const bootAt = steps.findIndex((step: any) => step.run === 'make coverage:vmm:boot')
  const uploadAt = steps.findIndex((step: any) => step.uses?.startsWith('codecov/codecov-action'))
  assert.ok(kernelAt >= 0 && kernelAt < bootAt && bootAt < uploadAt,
    'the kernel must be restored before the boot tests, which must add coverage before upload')
  for (const at of [kernelAt, bootAt]) {
    for (const target of ['linux-x64-gnu', 'linux-arm64-gnu', 'darwin-arm64']) {
      for (const vmm of ['true', 'false']) {
        const expression = steps[at].if.replace(/^\$\{\{\s*|\s*\}\}$/g, '')
        const context = { matrix: { platform: { target } }, needs: { changes: { outputs: { vmm } } } }
        assert.equal(runInNewContext(expression, context), target === 'linux-x64-gnu' && vmm === 'true',
          `${steps[at].name} on ${target} with vmm=${vmm}`)
      }
    }
  }
  assert.equal(steps[bootAt]['continue-on-error'], undefined, 'failed boot tests must fail CI')
})

// tests/scripts drives these scripts through fakes; the infra job runs it.
for (const path of ['scripts/ci/gcp-e2e-vm.sh', 'scripts/test/coverage-bindings.sh', 'tests/scripts/test_gcp_e2e_vm.py']) {
  test(`a change to a script under tests/scripts runs those tests: ${path}`, () => {
    assert.ok(testSuites([path]).includes('infra'))
    assert.equal(acceptsFiles('test.yml', 'push', [path]), true)
  })
}

test('the infra job runs the script tests', () => {
  assert.ok(workflow('test.yml').jobs.infra.steps.some((step: any) => step.run === 'make test:unit:scripts'))
})

// The check below only guards the ignore list if editing that list runs it.
test('a change to codecov.yml selects the suite that checks codecov.yml', () => {
  assert.ok(testSuites(['codecov.yml']).includes('infra'))
})

// Codecov rejects the empty upload with "Testable files changed" when a changed
// file is not ignored, so every test source has to match an ignore glob. Select by
// any path carrying "test" or "spec" as a word: deliberately wider than the globs,
// so a suite named by a convention nobody has added yet fails here rather than on
// Codecov. That width is paid for by naming the production files that carry those
// words. picomatch approximates Codecov's matcher, which ships no library to
// test against.
test('every test source is ignored, so a test-only change still qualifies for the empty upload', () => {
  const production = [
    '.github/workflows/test.yml',                    // runs the suites, is not one
    'apps/api/src/cloud-app/engine/spec.ts',          // resolves an App deployment spec
    'apps/dashboard/src/components/apps/spec.tsx',    // renders the App spec editor
    'apps/libs/api-client-go/model_inbound_network_spec.go',   // generated client model
    'apps/libs/api-client-go/model_outbound_network_spec.go',  // generated client model
    'apps/libs/api-client/src/models/inbound-network-spec.ts', // generated client model
    'apps/libs/api-client/src/models/outbound-network-spec.ts', // generated client model
    'make/test.mk',                                  // the recipes it calls
    'scripts/setup/setup-test.sh',                   // installs test tooling
    'sdks/go/images_cgo_test_support_dev.go',        // dev-tag cgo bridge, shipped
    'sdks/go/info_cgo_test_support_dev.go',          // dev-tag cgo bridge, shipped
    'sdks/go/ssh_cgo_test_support_dev.go',           // dev-tag cgo bridge, shipped
    'src/boxlite/examples/disk_attachment_test.rs',  // an example, built as one
    'src/guest/src/container/spec.rs',               // the OCI runtime spec
  ]
  const ignore: string[] = (loadYaml(readFileSync(join(REPO_ROOT, 'codecov.yml'), 'utf8')) as any).ignore
  const tracked = spawnSync('git', ['ls-files'], { cwd: REPO_ROOT, encoding: 'utf8', maxBuffer: 64 << 20 })
  assert.equal(tracked.status, 0, tracked.stderr)
  const testSources = tracked.stdout.trim().split('\n')
    .filter((path) => /(^|[^a-z0-9])(test|spec)s?([^a-z0-9]|$)/i.test(path) && !production.includes(path))
  assert.ok(testSources.length > 100, `expected the repo's test sources, found ${testSources.length}`)
  const testable = testSources.filter((path) => !ignore.some((pattern) => matches(pattern, path)))
  assert.deepEqual(testable, [], 'these test sources would count as a testable change')
})

function cliUnitTests(runner: 'cargo' | 'nextest', exitCode = 0) {
  const directory = mkdtempSync(join(tmpdir(), 'boxlite-cli-unit-'))
  try {
    const log = join(directory, 'cargo.log')
    const binary = join(directory, 'boxlite')
    writeFileSync(binary, '#!/bin/sh\nexit 0\n', { mode: 0o755 })
    for (const tool of ['bash', 'jq', 'mktemp', 'rm']) {
      const found = spawnSync('/bin/sh', ['-c', 'command -v "$1"', 'sh', tool], { encoding: 'utf8' })
      assert.equal(found.status, 0, `${tool} is required for the real CLI build wrapper`)
      symlinkSync(found.stdout.trim(), join(directory, tool))
    }
    writeFileSync(join(directory, 'cargo'), `#!/bin/sh
if [ "$1" = build ]; then
  printf '%s\\n' "$CARGO_ARTIFACT"
  exit 0
fi
if [ "$CARGO_BIN_EXE_boxlite" != "$CARGO_TEST_BIN" ] || [ ! -x "$CARGO_BIN_EXE_boxlite" ]; then
  echo 'test runner did not receive the built CLI executable' >&2
  exit 98
fi
if [ "$1" = nextest ] && ! command -v cargo-nextest >/dev/null 2>&1; then
  echo 'error: no such command: nextest' >&2
  exit 101
fi
printf '%s\\n' "$@" > "$CARGO_LOG"
exit "$CARGO_STATUS"
`, { mode: 0o755 })
    if (runner === 'nextest') {
      writeFileSync(join(directory, 'cargo-nextest'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
    }
    // Isolate tool discovery so an installed nextest cannot hide the fallback.
    const result = spawnSync('/usr/bin/make', [
      '-f', join(REPO_ROOT, 'make/test.mk'), 'test:unit:cli',
      'NEXTEST_PROFILE=ci', `SCRIPT_DIR=${join(REPO_ROOT, 'scripts')}`,
    ], {
      cwd: REPO_ROOT,
      env: {
        ...process.env, PATH: directory, MAKEFLAGS: '', CARGO_LOG: log, CARGO_STATUS: String(exitCode),
        CARGO_BIN_EXE_boxlite: '', CARGO_TEST_BIN: binary,
        CARGO_ARTIFACT: JSON.stringify({
          reason: 'compiler-artifact', target: { name: 'boxlite', kind: ['bin'] },
          profile: { test: false }, executable: binary,
        }),
      },
      encoding: 'utf8',
      timeout: 10_000,
    })
    assert.equal(result.error, undefined)
    const args = existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n') : []
    return { result, args }
  } finally {
    rmSync(directory, { recursive: true, force: true })
  }
}

test('CLI unit tests fall back to Cargo without running VM integration binaries', () => {
  const { result, args } = cliUnitTests('cargo')
  assert.equal(result.status, 0, result.stderr)
  assert.deepEqual(args, ['test', '-p', 'boxlite-cli', '--bins', '--', '--test-threads=1', '::tests::'])
})

test('CLI unit tests use the requested nextest profile when installed', () => {
  const { result, args } = cliUnitTests('nextest')
  assert.equal(result.status, 0, result.stderr)
  assert.deepEqual(args, ['nextest', 'run', '-p', 'boxlite-cli', '--profile', 'ci', '-E', 'test(::tests::)'])
})

for (const runner of ['cargo', 'nextest'] as const) {
  test(`CLI unit tests propagate ${runner} failures`, () => {
    const { result, args } = cliUnitTests(runner, 17)
    assert.notEqual(result.status, 0)
    assert.ok(args.length > 0, 'the selected test runner must execute')
    assert.match(result.stderr, /Error 17/)
  })
}

function workflowConfig(fullMatrix: string) {
  const actionPath = join(REPO_ROOT, '.github/actions/ci-config')
  const action: any = loadYaml(readFileSync(join(actionPath, 'action.yml'), 'utf8'))
  const directory = mkdtempSync(join(tmpdir(), 'boxlite-ci-config-'))
  try {
    const output = join(directory, 'outputs')
    const result = spawnSync('bash', ['-eo', 'pipefail', '-c', action.runs.steps[0].run], {
      env: { ...process.env, GITHUB_ACTION_PATH: actionPath, GITHUB_OUTPUT: output, FULL_MATRIX: fullMatrix },
      encoding: 'utf8',
      timeout: 10_000,
    })
    const values = new Map(
      (existsSync(output) ? readFileSync(output, 'utf8').trim().split('\n') : []).map((line) => {
        const separator = line.indexOf('=')
        return [line.slice(0, separator), line.slice(separator + 1)]
      }),
    )
    return { result, values }
  } finally {
    rmSync(directory, { recursive: true, force: true })
  }
}

test('only ordinary queue entries remove macOS rows from the SDK matrices', t => {
  const changes = coverageWorkflow.jobs.changes
  const selection = changes.steps.find((step: any) => step.id === 'native')
  assert.equal(selection.env.IS_RELEASE, '${{ steps.release.outputs.is-release }}')
  const dir = mkdtempSync(join(tmpdir(), 'test-platforms-'))
  t.after(() => rmSync(dir, { recursive: true, force: true }))
  for (const [name, release, full] of [
    ['routine queue', 'false', 'false'], ['release queue', 'true', 'false'],
    ['PR or push', '', 'false'], ['weekly or manual', '', 'true'],
  ]) {
    const { values, result } = workflowConfig(full)
    assert.equal(result.status, 0, result.stderr)
    const output = join(dir, name)
    const run = spawnSync('bash', ['-ec', selection.run], { encoding: 'utf8', env: { ...process.env,
      GITHUB_OUTPUT: output, IS_RELEASE: release, PLATFORMS: values.get('platforms'),
      PYTHON_MATRIX: values.get('python-test-matrix'), NODE_MATRIX: values.get('node-test-matrix'),
    } })
    assert.equal(run.status, 0, run.stderr)
    const matrices = Object.fromEntries(readFileSync(output, 'utf8').trim().split('\n').map(row => row.split('=')))
    for (const sdk of ['python', 'node']) {
      const key = sdk + '-test-matrix'
      assert.equal(changes.outputs[key], `\${{ steps.native.outputs.${key} }}`)
      const configured = JSON.parse(values.get(key)!)
      const expected = release === 'false' ? configured.filter((r: any) => r.platform.target !== 'darwin-arm64') : configured
      assert.deepEqual(JSON.parse(matrices[key]), expected, name + ' ' + sdk)
    }
  }
})

for (const [sdk, compactCount, fullCount] of [['python', 6, 12], ['node', 5, 9]] as const) {
  test(`${sdk} PR matrix covers every version and platform without the full cross product`, () => {
    const { result, values } = workflowConfig('false')
    assert.equal(result.status, 0, result.stderr)
    const matrix = JSON.parse(values.get(`${sdk}-test-matrix`)!)
    const platforms = JSON.parse(values.get('platforms')!)
    const versions: string[] = JSON.parse(values.get(`${sdk}-versions`)!)
    assert.equal(matrix.length, compactCount)
    assert.deepEqual(new Set(matrix.map((entry: any) => entry.platform.target)), new Set(platforms.map((entry: any) => entry.target)))
    assert.deepEqual(matrix.filter((entry: any) => entry.platform.target === 'linux-x64-gnu').map((entry: any) => entry[`${sdk}-version`]), versions)
    assert.ok(matrix.filter((entry: any) => entry.platform.target !== 'linux-x64-gnu').every((entry: any) => entry[`${sdk}-version`] === versions.at(-1)))
  })

  test(`${sdk} full matrix retains every platform/version combination`, () => {
    const { result, values } = workflowConfig('true')
    assert.equal(result.status, 0, result.stderr)
    const matrix = JSON.parse(values.get(`${sdk}-test-matrix`)!)
    const platforms: Array<{ target: string }> = JSON.parse(values.get('platforms')!)
    const versions: string[] = JSON.parse(values.get(`${sdk}-versions`)!)
    assert.equal(matrix.length, fullCount)
    assert.deepEqual(
      new Set(matrix.map((entry: any) => `${entry.platform.target}/${entry[`${sdk}-version`]}`)),
      new Set(platforms.flatMap((platform) => versions.map((version) => `${platform.target}/${version}`))),
    )
  })
}

test('invalid matrix mode fails before exporting configuration', () => {
  const { result, values } = workflowConfig('typo')
  assert.equal(result.status, 1)
  assert.equal(values.size, 0)
  assert.match(result.stdout, /full-matrix must be true or false/)
})

function buildImages(selection?: string, cached = false) {
  const directory = mkdtempSync(join(tmpdir(), 'boxlite-image-selection-'))
  try {
    const log = join(directory, 'docker.log')
    writeFileSync(join(directory, 'docker'), '#!/bin/sh\nprintf "%s\\n" "$*" >> "$DOCKER_LOG"\n', { mode: 0o755 })
    const env = { ...process.env, PATH: `${directory}:${process.env.PATH}`, DOCKER_LOG: log, PUSH: '0', PLATFORMS: 'linux/amd64,linux/arm64', TAG: 'v0.0.0', IMAGES: selection,
      ACTIONS_RUNTIME_TOKEN: cached ? 'test-token' : '', ACTIONS_RESULTS_URL: cached ? 'https://cache.example/' : '' }
    const result = spawnSync('bash', [join(REPO_ROOT, 'apps/box-images/build.sh')], { env, encoding: 'utf8', timeout: 10_000 })
    const builds = existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n') : []
    return { result, builds }
  } finally {
    rmSync(directory, { recursive: true, force: true })
  }
}

test('image builds select a single changed flavor while preserving both architectures', () => {
  const { result, builds } = buildImages('python')
  assert.equal(result.status, 0, result.stderr)
  assert.equal(builds.length, 1)
  assert.match(builds[0], /python\.Dockerfile/)
  assert.match(builds[0], /--platform linux\/amd64,linux\/arm64/)
})

test('image builds default to every release flavor', () => {
  const { result, builds } = buildImages()
  assert.equal(result.status, 0, result.stderr)
  assert.equal(builds.length, 3)
  for (const image of ['base', 'python', 'node']) {
    assert.ok(builds.some((build) => build.includes(`/${image}.Dockerfile`)))
  }
})

test('CI image builds persist separate layer caches for each flavor', () => {
  const { result, builds } = buildImages('base,python,node', true)
  assert.equal(result.status, 0, result.stderr)
  for (const [index, flavor] of ['base', 'python', 'node'].entries()) {
    assert.match(builds[index], new RegExp(`--cache-from type=gha,version=2,scope=box-images-${flavor}`))
    assert.match(builds[index], new RegExp(`--cache-to type=gha,version=2,scope=box-images-${flavor},mode=max,ignore-error=true,timeout=3m`))
    assert.ok(!builds[index].includes('test-token'), 'cache credentials must stay out of command arguments')
  }
})

test('local image builds do not require GitHub cache credentials', () => {
  const { result, builds } = buildImages('base')
  assert.equal(result.status, 0, result.stderr)
  assert.ok(!builds[0].includes('--cache-'))
})

test('invalid image selections fail before any Docker invocation', () => {
  for (const selection of ['', 'python,', ',python', 'python,,node', 'python,../../unexpected']) {
    const { result, builds } = buildImages(selection)
    assert.equal(result.status, 1, selection)
    assert.deepEqual(builds, [], selection)
  }
})

test('Linux wheel containers receive the release workflow download retries', () => {
  const project = parseToml(readFileSync(join(REPO_ROOT, 'sdks/python/pyproject.toml'), 'utf8')) as any
  const pass = project.tool.cibuildwheel.linux['environment-pass'] as string[]
  for (const name of ['PIP_RETRIES', 'UV_HTTP_RETRIES']) {
    assert.equal(workflow('build-wheels.yml').env[name], '3')
    assert.ok(pass.includes(name), `wheel container must inherit ${name}`)
  }
})

for (const sharedCache of [true, false]) {
  for (const source of ['host', 'pip', 'unavailable'] as const) {
    test(`wheel cache setup: shared=${sharedCache}, source=${source}`, () => {
      const installSucceeds = source !== 'unavailable'
      const project = parseToml(readFileSync(join(REPO_ROOT, 'sdks/python/pyproject.toml'), 'utf8')) as any
      const config = project.tool.cibuildwheel
      const directory = mkdtempSync(join(tmpdir(), 'boxlite-wheel-cache-'))
      try {
        const bin = join(directory, 'bin')
        const pythonBin = join(directory, 'python-bin')
        const wrapper = join(directory, 'stable-bin/sccache')
        const cache = join(directory, 'container-cache')
        const host = join(directory, 'host')
        const hostCache = join(host, 'runner cache/sccache')
        const hostBinary = join(host, 'runner tools/sccache')
        const trace = join(directory, 'trace')
        for (const path of [bin, pythonBin, dirname(wrapper), hostCache, dirname(hostBinary), join(directory, 'scripts'), join(directory, 'home')]) {
          mkdirSync(path, { recursive: true })
        }
        writeFileSync(join(bin, 'pip'), `#!/bin/sh
printf 'pip %s\\n' "$*" >> "$TRACE"
[ "$INSTALL_SUCCEEDS" = true ] || exit 1
# PyPI publishes 0.16.0, but does not publish the host action's 0.17.0 release.
[ "$*" = 'install sccache==0.16.0' ] || exit 1
cat > "$PYTHON_BIN/sccache" <<'WRAPPER'
#!/bin/sh
printf 'installed-wrapper %s\\n' "$*" >> "$TRACE"
[ "$1" = --stop-server ] && exit 0
exec "$@"
WRAPPER
chmod +x "$PYTHON_BIN/sccache"
`, { mode: 0o755 })
        if (source === 'host') {
          writeFileSync(hostBinary, `#!/bin/sh
printf 'host-wrapper %s\\n' "$*" >> "$TRACE"
[ "$1" = --stop-server ] && exit 0
exec "$@"
`, { mode: 0o755 })
        }
        writeFileSync(join(bin, 'uname'), '#!/bin/sh\necho Linux\n', { mode: 0o755 })
        writeFileSync(join(directory, 'scripts/util.sh'), '#!/bin/sh\necho x86_64-unknown-linux-musl\n', { mode: 0o755 })
        writeFileSync(join(bin, 'make'), `#!/bin/sh
printf 'make %s\\nwrapper=%s\\ncache=%s\\n' "$*" "\${RUSTC_WRAPPER:-}" "\${SCCACHE_DIR:-}" >> "$TRACE"
if [ "$1" = runtime ]; then
  if [ -n "\${RUSTC_WRAPPER:-}" ]; then
    "$RUSTC_WRAPPER" /bin/echo compiler-invoked >> "$TRACE"
  else
    /bin/echo compiler-invoked >> "$TRACE"
  fi
fi
`, { mode: 0o755 })
        // Relocate fixed container paths only. Branches, commands and assertions use
        // the production TOML; no fixture may write to the host's /usr/local or /tmp cache.
        const relocate = (value: string) => value
          .replaceAll('/usr/local/bin/sccache', wrapper)
          .replaceAll('/tmp/boxlite-sccache', cache)
          .replaceAll('/host', host)
        const env = {
          ...Object.fromEntries(Object.entries<string>(config.linux.environment).map(([name, value]) => [name, relocate(value)])),
          PATH: `${bin}:${pythonBin}:${dirname(wrapper)}:/usr/bin:/bin`, HOME: join(directory, 'home'),
          TRACE: trace, PYTHON_BIN: pythonBin, INSTALL_SUCCEEDS: String(source === 'pip'),
          BOXLITE_HOST_SCCACHE_DIR: sharedCache ? '/runner cache/sccache' : '',
          BOXLITE_HOST_SCCACHE_BIN: source === 'host' ? '/runner tools/sccache' : '',
        }
        const result = spawnSync('bash', ['-e', '-c', relocate(config['before-all'].join('\n'))], {
          cwd: directory, env, encoding: 'utf8', timeout: 10_000,
        })
        assert.equal(result.status, 0, result.stderr)
        const calls = readFileSync(trace, 'utf8')
        assert.ok(calls.includes(`wrapper=${wrapper}\n`), 'runtime must use the stable wrapper from the wheel environment')
        assert.ok(calls.includes(`cache=${cache}\n`), 'runtime must use the configured disk cache')
        assert.match(calls, /compiler-invoked\n/, 'both installed and fallback wrappers must invoke the compiler')
        assert.equal(calls.includes('installed-wrapper /bin/echo'), source === 'pip', 'standalone wheels must install a published package')
        assert.equal(calls.includes('host-wrapper /bin/echo'), source === 'host', 'CI wheels must execute the verified host binary')
        assert.equal(lstatSync(wrapper).isSymbolicLink(), source === 'pip')
        if (source === 'host') {
          assert.ok(!calls.includes('pip '), 'the verified host binary needs no second installation')
          const build = workflow('build-wheels.yml').jobs.build_wheels.steps.find((step: any) => step.uses?.startsWith('pypa/cibuildwheel'))
          assert.equal(build.env.BOXLITE_HOST_SCCACHE_BIN, '${{ env.SCCACHE_PATH }}')
          assert.ok(config.linux['environment-pass'].includes('BOXLITE_HOST_SCCACHE_BIN'))
        }
        if (sharedCache) {
          assert.equal(realpathSync(cache), realpathSync(hostCache), 'the container must share the host cache, including paths with spaces')
        } else {
          assert.notEqual(lstatSync(cache, { throwIfNoEntry: false })?.isSymbolicLink(), true,
            'a local build must not create a host link, including a dangling one')
        }
        if (!installSucceeds) assert.match(result.stdout, /WARNING: sccache not available/)
        const stop = spawnSync('bash', ['-e', '-c', relocate(config.linux['before-test'] ?? '')], {
          cwd: directory, env, encoding: 'utf8', timeout: 10_000,
        })
        assert.equal(stop.status, 0, 'the pass-through fallback must tolerate server shutdown')
        if (installSucceeds) assert.match(readFileSync(trace, 'utf8'), source === 'host' ? /host-wrapper --stop-server\n$/ : /installed-wrapper --stop-server\n$/)
      } finally {
        rmSync(directory, { recursive: true, force: true })
      }
    })
  }
}

test('the wheel smoke check rejects a package with a missing native extension', () => {
  const project = readFileSync(join(REPO_ROOT, 'sdks/python/pyproject.toml'), 'utf8')
  const command = project.match(/^test-command = "(.*)"$/m)?.[1]
  assert.ok(command, 'cibuildwheel must verify the installed wheel')
  const directory = mkdtempSync(join(tmpdir(), 'boxlite-wheel-check-'))
  try {
    // Keep Python imports intact while omitting native extensions and caches.
    cpSync(join(REPO_ROOT, 'sdks/python/boxlite'), join(directory, 'boxlite'), {
      recursive: true,
      filter: (source) => lstatSync(source).isDirectory() || source.endsWith('.py'),
    })
    const result = spawnSync('bash', ['-c', command.replace(/^python /, 'python3 ')], {
      cwd: directory,
      env: { ...process.env, PYTHONPATH: directory },
      encoding: 'utf8',
      timeout: 10_000,
    })
    assert.equal(result.error, undefined)
    assert.notEqual(result.status, 0, 'wheel smoke check accepted a missing native extension')
    assert.match(result.stderr, /No module named 'boxlite\.boxlite'/)
  } finally {
    rmSync(directory, { recursive: true, force: true })
  }
})