The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { appendFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
import { linuxClients, verifyAcceptedDistribution, verifyCandidate } from './release-candidate.mjs'
const command = fileURLToPath(new URL('./release-candidate.mjs', import.meta.url))
const config = new URL('../../../.github/ci-config.json', import.meta.url)
const hash = (data) => 'sha256:' + createHash('sha256').update(data).digest('hex')
test('stage binds candidate files and GHCR pins to the tagged commit and producer run', async (t) => {
const dir = mkdtempSync(join(tmpdir(), 'candidate-stage-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
mkdirSync(join(dir, '.github'))
cpSync(config, join(dir, '.github/ci-config.json'))
const index = []
const version = '1.2.3',
tag = 'v' + version,
sha = 'a'.repeat(40)
function group(name, files) {
const path = join(dir, 'staged', name)
mkdirSync(path, { recursive: true })
writeFileSync(join(path, 'producer.json'), JSON.stringify({ run: 10, attempt: 1, sha }))
for (const [key, bytes] of Object.entries(files)) writeFileSync(join(path, key), bytes)
index.push({ id: index.length + 1, name, expired: false })
return path
}
const runtime = { 'install.sh': 'installer', 'install.sh.sha256': hash('installer'), SHA256SUMS: 'checksums' }
const packages = { ['boxlite-ai-boxlite-' + version + '.tgz']: 'main package' }
for (const { os, target, rust_target } of JSON.parse(readFileSync(config)).platforms) {
for (const base of ['boxlite-runtime-' + tag + '-' + target, 'boxlite-cli-' + tag + '-' + rust_target]) {
runtime[base + '.tar.gz'] = base
runtime[base + '.tar.gz.sha256'] = hash(base)
}
packages['boxlite-ai-boxlite-' + target + '-' + version + '.tgz'] = target
group('c-sdk-' + target, { ['boxlite-c-' + tag + '-' + target + '.tar.gz']: target })
const wheel = target === 'linux-x64-gnu' ? linuxClients(tag)['wheels-ubuntu-latest'][0] : 'boxlite-' + version + '-cp312-' + target + '.whl'
group('wheels-' + os, { [wheel]: os })
}
group('node-packages', packages)
const runtimeDir = group('runtime-distribution', runtime)
const archive = 'boxlite-runner-' + tag + '-linux-amd64.tar.gz'
group('runner-linux-amd64', { [archive]: 'runner', [archive + '.sha256']: hash('runner') })
const pins = { manifest: hash('manifest'), archive: hash('runner') }
group('ghcr-runner', { 'runner.json': JSON.stringify(pins) })
group('ghcr-api', { 'image.json': JSON.stringify([{ artifact: 'api', digest: hash('api') }]) })
writeFileSync(join(dir, 'index.json'), JSON.stringify([{ artifacts: index }]))
writeFileSync(
join(dir, 'gh'),
`#!/bin/sh
case "$*" in
*commits/refs%2Ftags%2F*) printf '{"sha":"%s"}\\n' "$SHA" ;;
*actions/runs/*/artifacts*) cat index.json ;;
*releases/7/assets*) jq -s '[.]' uploads.jsonl ;;
'api --method PATCH '*) touch public ;;
*releases/7) if test -f public; then printf '{"tag_name":"v1.2.3","draft":false}'; else printf '{"tag_name":"v1.2.3","draft":true}'; fi ;;
'api --method DELETE '*)
id=$(basename "$4")
jq -sc --argjson id "$id" '.[]|select(.id != $id)' uploads.jsonl > next
mv next uploads.jsonl
echo "delete $id" >>changes ;;
'release download '*) cp published-manifest.json "$9/$7" ;;
'release upload '*)
name=$(basename "$4")
if test "$name" = release-candidate.json; then cp "$4" published-manifest.json || exit 1; fi
digest=$(shasum -a 256 "$4" | cut -d' ' -f1)
if test "$7" = '--clobber'; then
jq -sc --arg name "$name" '.[]|select(.name != $name)' uploads.jsonl > next
mv next uploads.jsonl
fi
echo "upload $name" >>changes
id=$(wc -l <changes)
jq -nc --argjson id "$id" --arg name "$name" --arg digest "sha256:$digest" '{id:$id,name:$name,digest:$digest,state:"uploaded"}' >>uploads.jsonl ;;
*) exit 2 ;;
esac
`,
{ mode: 0o755 },
)
const stage = (output, mode = 'stage', extra = {}) =>
spawnSync(process.execPath, [command, mode], {
cwd: dir,
encoding: 'utf8',
env: {
...process.env,
PATH: dir + ':' + process.env.PATH,
GITHUB_REPOSITORY: 'boxlite-ai/boxlite',
GITHUB_RUN_ATTEMPT: '2',
GITHUB_RUN_ID: '10',
TAG: tag,
SHA: sha,
IMAGES: '["api"]',
RELEASE_ASSET_DIR: output,
...extra,
},
})
const early = stage('deploy', 'deployment')
assert.equal(early.status, 0, early.stderr)
const deploy = await verifyCandidate(join(dir, 'deploy'), { tag, sha, fingerprint: early.stdout.trim() })
assert.deepEqual(deploy.assets, {})
assert.deepEqual(deploy.runner, pins)
const result = stage('candidate')
assert.equal(result.status, 0, result.stderr)
const fingerprint = result.stdout.trim()
const receipt = await verifyCandidate(join(dir, 'candidate'), { tag, sha, fingerprint })
assert.deepEqual(receipt.runner, pins)
assert.deepEqual(receipt.images, { api: hash('api') })
assert.equal(receipt.producers['ghcr-api'].attempt, 1)
assert.equal(receipt.assets['install.sh.sha256'].group, 'runtime-distribution')
const runtimeNames = Object.keys(receipt.assets).filter(name => receipt.assets[name].group === 'runtime-distribution')
const conflict = { name: runtimeNames.at(-1), digest: hash('different release bytes'), state: 'uploaded' }
const existing = JSON.stringify(conflict) + '\n'
writeFileSync(join(dir, 'uploads.jsonl'), existing)
const fullAttach = stage('candidate', 'attach', { CANDIDATE_DIGEST: fingerprint, RELEASE_ID: '7' })
assert.notEqual(fullAttach.status, 0)
assert.match(fullAttach.stderr, /Release already holds different bytes/)
assert.equal(readFileSync(join(dir, 'uploads.jsonl'), 'utf8'), existing)
assert.equal(existsSync(join(dir, 'changes')), false)
for (let attempt = 0; attempt < 2; attempt++) {
const attached = stage('candidate', 'attach', { CANDIDATE_DIGEST: fingerprint, RELEASE_ID: '7', REPAIR_GROUP: 'runtime-distribution' })
assert.equal(attached.status, 0, attached.stderr)
const names = readFileSync(join(dir, 'uploads.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line).name)
assert.deepEqual(names.sort(), Object.keys(runtime).sort(), 'Each runtime file, including install.sh.sha256, uploads exactly once across retries')
}
const draft = (group, output) => stage(output, 'draft-component', { COMPONENT_GROUP: group, IMAGES: '[]', RELEASE_ID: '7' })
const seal = () => stage('candidate', 'draft-manifest', { CANDIDATE_DIGEST: fingerprint, RELEASE_ID: '7' })
const assets = () => readFileSync(join(dir, 'uploads.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line))
writeFileSync(join(dir, 'uploads.jsonl'), '')
const first = draft('runtime-distribution', 'early-runtime')
assert.equal(first.status, 0, first.stderr)
assert.deepEqual(assets().map(asset => asset.name).sort(), runtimeNames.sort())
assert.match(seal().stderr, /Draft asset missing or different/)
for (const [n, group] of ['wheels-', 'node-packages', 'c-sdk-', 'runner-linux-amd64'].entries()) {
const partial = draft(group, 'early-' + n)
assert.equal(partial.status, 0, partial.stderr)
}
// An older wheel was attached by a successful build but is absent from this candidate.
const staleWheel = 'boxlite-' + version + '-cp311-cp311-macosx_11_0_arm64.whl'
const obsolete = join(dir, 'staged/wheels-macos-15', staleWheel)
writeFileSync(obsolete, 'previous wheel')
const previousWheels = draft('wheels-', 'previous-wheels')
assert.equal(previousWheels.status, 0, previousWheels.stderr)
rmSync(obsolete)
const replaced = draft('wheels-', 'current-wheels')
assert.equal(replaced.status, 0, replaced.stderr)
const unrelated = { id: 501, name: 'maintainer-notes.pdf', state: 'uploaded', digest: hash('notes') }
appendFileSync(join(dir, 'uploads.jsonl'), JSON.stringify(unrelated) + '\n')
const extra = assets().find(asset => asset.name === staleWheel)
const setAssets = list => writeFileSync(join(dir, 'uploads.jsonl'), list.map(item => JSON.stringify(item)).join('\n') + '\n')
await t.test('seal names an obsolete managed attachment before writing the manifest', () => {
const changes = readFileSync(join(dir, 'changes'), 'utf8')
const rejected = seal()
assert.notEqual(rejected.status, 0, 'sealed a draft containing a stale wheel')
assert.ok(rejected.stderr.includes(staleWheel), rejected.stderr)
assert.equal(readFileSync(join(dir, 'changes'), 'utf8'), changes)
})
setAssets(assets().filter(asset => asset.name !== staleWheel && asset.name !== 'release-candidate.json'))
const sealed = seal()
assert.equal(sealed.status, 0, sealed.stderr)
assert.equal(assets().at(-1).name, 'release-candidate.json')
assert.ok(assets().some(asset => asset.name === unrelated.name))
await t.test('finalize checks the live assets again before making the draft public', () => {
appendFileSync(join(dir, 'uploads.jsonl'), JSON.stringify(extra) + '\n')
const final = stage('candidate', 'finalize', { CANDIDATE_DIGEST: fingerprint, RELEASE_ID: '7' })
assert.notEqual(final.status, 0, 'published a stale wheel added after sealing')
assert.ok(final.stderr.includes(staleWheel), final.stderr)
assert.equal(existsSync(join(dir, 'public')), false)
})
setAssets(assets().filter(asset => asset.name !== staleWheel))
const old = assets().at(-1)
writeFileSync(join(dir, 'public'), '')
const original = readFileSync(join(runtimeDir, 'install.sh'))
writeFileSync(join(runtimeDir, 'install.sh'), 'rebuilt installer')
assert.match(draft('runtime-distribution', 'public-refused').stderr, /Expected the matching draft release/)
assert.equal(assets().at(-1).id, old.id)
rmSync(join(dir, 'public'))
const updated = draft('runtime-distribution', 'replaced-draft')
assert.equal(updated.status, 0, updated.stderr)
assert.deepEqual(readFileSync(join(dir, 'changes'), 'utf8').trim().split('\n').slice(-2), ['delete ' + old.id, 'upload install.sh'])
assert.ok(!assets().some(asset => asset.name === 'release-candidate.json'))
assert.equal(assets().find(asset => asset.name === 'install.sh').digest, hash('rebuilt installer'))
assert.match(seal().stderr, /Draft asset missing or different: install.sh/)
writeFileSync(join(runtimeDir, 'install.sh'), original)
const e2e = join(dir, 'linux-clients')
const clients = {}
for (const [group, files] of Object.entries(linuxClients(tag))) {
const path = join(e2e, group)
mkdirSync(path, { recursive: true })
writeFileSync(join(path, 'producer.json'), JSON.stringify({ run: 10, attempt: 1, sha }))
for (const name of files) {
const bytes = readFileSync(join(dir, 'candidate', name))
writeFileSync(join(path, name), bytes)
clients[name] = hash(bytes)
}
}
const prepare = () => stage('deploy', 'clients', { CLIENT_ARTIFACT_DIR: e2e, CANDIDATE_DIGEST: early.stdout.trim() })
const prepared = prepare()
assert.equal(prepared.status, 0, prepared.stderr)
const tested = JSON.parse(readFileSync(join(dir, 'deploy', 'tested-clients.json')))
assert.deepEqual(tested, clients)
const full = receipt
const acceptance = { tag, sha, run: 10, clients: tested }
verifyAcceptedDistribution(full, acceptance, deploy)
const macWheel = 'boxlite-1.2.3-cp312-darwin-arm64.whl'
const macGroup = receipt.assets[macWheel].group
writeFileSync(join(dir, 'staged', macGroup, macWheel), 'rebuilt macOS wheel')
writeFileSync(join(dir, 'staged', macGroup, 'producer.json'), JSON.stringify({ run: 10, attempt: 2, sha }))
const rebuild = stage('rebuilt')
assert.equal(rebuild.status, 0, rebuild.stderr)
const changed = await verifyCandidate(join(dir, 'rebuilt'), { tag, sha, fingerprint: rebuild.stdout.trim() })
assert.notEqual(changed.assets[macWheel].digest, full.assets[macWheel].digest)
verifyAcceptedDistribution(changed, acceptance, deploy)
writeFileSync(join(dir, 'rebuilt', macWheel), 'changed after verification')
await assert.rejects(verifyCandidate(join(dir, 'rebuilt'), { tag, sha, fingerprint: rebuild.stdout.trim() }), /Changed release asset/)
const single = stage('wheels', 'component', { COMPONENT_GROUP: 'wheels-' })
assert.equal(single.status, 0, single.stderr)
const wheels = await verifyCandidate(join(dir, 'wheels'), { tag, sha, fingerprint: single.stdout.trim() })
assert.deepEqual(Object.keys(wheels.producers).sort(), index.map((entry) => entry.name).filter((name) => name.startsWith('wheels-')).sort())
assert.ok(Object.values(wheels.assets).every(({ group }) => group.startsWith('wheels-')))
assert.throws(() => verifyAcceptedDistribution(full, { ...acceptance, clients: {} }, deploy))
const file = Object.keys(tested)[0]
assert.throws(
() => verifyAcceptedDistribution(full, { ...acceptance, clients: { ...tested, [file]: hash('rebuilt') } }, deploy),
/differs from dev/,
)
assert.throws(() => verifyAcceptedDistribution(full, acceptance, { ...deploy, images: { api: hash('new image') } }))
writeFileSync(join(e2e, 'npm-linux-x64-gnu', 'producer.json'), JSON.stringify({ run: 11, attempt: 1, sha }))
assert.notEqual(prepare().status, 0)
for (const name of Object.keys(linuxClients(tag))) {
if (!index.some((item) => item.name === name)) index.push({ name, id: index.length + 1, expired: false })
}
writeFileSync(join(dir, 'index.json'), JSON.stringify([{ artifacts: index }]))
const ready = stage('unused', 'client-ids')
assert.equal(ready.status, 0, ready.stderr)
assert.deepEqual(
ready.stdout.trim().split(',').map(Number),
Object.keys(linuxClients(tag)).map((name) => index.find((item) => item.name === name).id),
)
const incomplete = index.filter(({ name }) => name !== 'npm-linux-x64-gnu')
writeFileSync(join(dir, 'index.json'), JSON.stringify([{ artifacts: incomplete }]))
assert.match(stage('unused', 'client-ids').stderr, /Missing Linux client artifact: npm-linux-x64-gnu/)
writeFileSync(join(dir, 'index.json'), JSON.stringify([{ artifacts: index }]))
writeFileSync(join(dir, 'candidate', archive), 'different')
await assert.rejects(verifyCandidate(join(dir, 'candidate'), { tag, sha, fingerprint }), /Changed release asset/)
writeFileSync(join(runtimeDir, 'producer.json'), JSON.stringify({ run: 99, attempt: 1, sha }))
assert.notEqual(stage('wrong-run').status, 0)
writeFileSync(join(runtimeDir, 'producer.json'), JSON.stringify({ run: 10, attempt: 1, sha }))
rmSync(join(runtimeDir, 'install.sh.sha256'))
assert.match(stage('missing-sidecar').stderr, /Missing install.sh.sha256/)
await t.test('republishing the Runner records its current archive, GHCR pin and fallback producers', () => {
// Publish over the original sealed manifest from run 10, then inspect what a repair would read.
setAssets([old])
cpSync(join(dir, 'candidate/release-candidate.json'), join(dir, 'published-manifest.json'))
writeFileSync(join(dir, 'public'), '')
const runnerGroup = 'runner-linux-amd64'
const runnerPins = { manifest: hash('replacement manifest'), archive: hash('replacement runner') }
writeFileSync(join(dir, 'staged', runnerGroup, archive), 'replacement runner')
writeFileSync(join(dir, 'staged', runnerGroup, archive + '.sha256'), runnerPins.archive)
writeFileSync(join(dir, 'staged/ghcr-runner/runner.json'), JSON.stringify(runnerPins))
const producers = { [runnerGroup]: 701, 'ghcr-runner': 702 }
for (const [name, id] of Object.entries(producers)) {
writeFileSync(join(dir, 'staged', name, 'producer.json'), JSON.stringify({ sha, run: 11, attempt: 1 }))
index.find(item => item.name === name).id = id
}
writeFileSync(join(dir, 'index.json'), JSON.stringify([{ artifacts: index }]))
const built = stage('replacement', 'component', { COMPONENT_GROUP: runnerGroup, IMAGES: '[]', GITHUB_RUN_ID: '11' })
assert.equal(built.status, 0, built.stderr)
const attached = stage('replacement', 'attach', { REPAIR_GROUP: runnerGroup, RELEASE_ID: '7', CANDIDATE_DIGEST: built.stdout.trim() })
assert.equal(attached.status, 0, attached.stderr)
const published = JSON.parse(readFileSync(join(dir, 'published-manifest.json')))
assert.deepEqual(published.runner, runnerPins)
assert.equal(published.assets[archive].digest, runnerPins.archive)
for (const [name, id] of Object.entries(producers))
assert.deepEqual(published.producers[name], { id, attempt: 1, run: 11 })
assert.equal(published.run, receipt.run)
assert.deepEqual(published.images, receipt.images)
assert.deepEqual(published.assets['install.sh'], receipt.assets['install.sh'])
const minimal = { tag, sha, runner: receipt.runner, images: receipt.images }
writeFileSync(join(dir, 'published-manifest.json'), JSON.stringify(minimal))
const backfilled = stage('replacement', 'attach', { REPAIR_GROUP: runnerGroup, RELEASE_ID: '7', CANDIDATE_DIGEST: built.stdout.trim() })
assert.equal(backfilled.status, 0, backfilled.stderr)
const updated = JSON.parse(readFileSync(join(dir, 'published-manifest.json')))
assert.deepEqual(updated.images, minimal.images)
assert.deepEqual(updated.runner, runnerPins)
assert.equal(updated.assets[archive].digest, runnerPins.archive)
assert.deepEqual(updated.producers[runnerGroup], published.producers[runnerGroup])
})
})