Skip to content

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

42.1 KB
Raw Blame
import assert from 'node:assert/strict'
import { execFileSync, spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import test from 'node:test'
import { data, Evaluator, Lexer, Parser } from '@actions/expressions'
import { load } from 'js-yaml'
import { selectRelease } from './release-selection.mjs'

const readWorkflow = (name) =>
  load(readFileSync(new URL('../../../.github/workflows/' + name + '.yml', import.meta.url), 'utf8'))
const workspace = fileURLToPath(new URL('../../../', import.meta.url))
const release = readWorkflow('mbuild-release')
const rollout = readWorkflow('mdeploy-all')

test('release deployment is a native dependency in the publisher run', () => {
  const calls = Object.values(release.jobs).filter((job) => job.uses === './.github/workflows/mdeploy-all.yml')
  assert.deepEqual(
    calls.map((job) => job.with.stage).sort(),
    ['dev', 'prod'],
    'release dispatches deployment outside its workflow run',
  )
  assert.ok(release.jobs.dev.needs.includes('publish-runner'))
  assert.ok(release.jobs.prod.needs.includes('dev'))
  assert.equal(rollout.jobs.e2e.uses, './.github/workflows/e2e-cloud.yml')
  assert.ok(rollout.jobs.e2e.needs.includes('plan'))
  assert.equal(rollout.jobs.report, undefined, 'successful acceptance must not allocate a report runner')
})

test('each component can reach the draft before dev acceptance; the manifest waits for all uploads', () => {
  const components = { runtime: ['package-runtime'], wheels: ['build-wheels', 'build-wheels-other'], node: ['package-node'], c: ['build-c', 'build-c-other'], runner: ['build-runner-binary'] }
  for (const [component, producer] of Object.entries(components)) {
    const id = 'draft-' + component
    const job = release.jobs[id]
    assert.ok(job, 'Missing early draft upload for ' + component)
    assert.deepEqual(job.needs, ['resolve', ...producer])
    assert.ok(release.jobs.distribution.needs.includes(id))
    assert.ok(!release.jobs.dev.needs.includes(id))
  }
  assert.ok(release.jobs.distribution.steps.some(step => step.run?.includes('release-candidate.mjs draft-manifest')))
  assert.ok(release.jobs.attach.needs.includes('dev'))
  assert.ok(release.jobs.finalize.needs.includes('attach'))
})

test('release dev approval uses only the release webhook', () => {
  const inputs = { stage: 'dev', apply: true, release_sha: 'a'.repeat(40) }
  const notices = rollout.jobs.resolve.steps.filter((s) => s.run?.endsWith('release-pipeline.mjs approval'))
  const selected = notices.filter((s) => new Function('inputs', 'return ' + s.if)(inputs))
  assert.deepEqual(
    selected.map((s) => s.env.SLACK_WEBHOOK_URL),
    ['$' + '{{ secrets.SLACK_WEBHOOK_URL }}'],
  )
})

const expression = (value) => value.replace(/^\$\{\{\s*|\s*\}\}$/g, '')

test('deploy-infra selectable-source builds receive read-only Actions cache access', () => {
  const manual = readWorkflow('deploy-infra')
  for (const id of ['build-c', 'build-runner']) {
    const job = manual.jobs[id]
    assert.equal(job['cache-mode'] ?? manual['cache-mode'] ?? 'write', 'read', 'deploy-infra / ' + id)
  }
})

test('mbuild selectable-source builds receive read-only Actions cache access', () => {
  const caller = release.jobs['standalone-build'] ?? release.jobs['build-c']
  assert.equal(caller['cache-mode'] ?? release['cache-mode'] ?? 'write', 'read', 'standalone source')
  assert.equal(release.jobs.resolve.outputs.sha, '${{ steps.ref.outputs.sha }}', 'release uses the tag verified on main')
  assert.equal(caller.with.ref, '${{ needs.resolve.outputs.source_sha }}')
  assert.equal(release.jobs.resolve.outputs.source_sha, '${{ steps.source.outputs.sha }}')
  for (const [id, job] of Object.entries(release.jobs)) {
    if (job.with?.build_plan !== '${{ needs.resolve.outputs.build_plan }}') continue
    assert.equal(job.with.ref, '${{ needs.resolve.outputs.sha }}', id)
    assert.equal(job['cache-mode'] ?? release['cache-mode'] ?? 'write', 'write', id)
  }
})

test('release caller routes the pinned C SDK build to its qualified runner', () => {
  const sha = 'a'.repeat(40)
  const callee = readWorkflow('build-c').jobs.build
  const platforms = JSON.parse(readFileSync(new URL('../../../.github/ci-config.json', import.meta.url))).platforms
  function evaluate(value, context) {
    const tokens = new Lexer(expression(value)).lex().tokens
    const ast = new Parser(tokens, Object.keys(context), []).parse()
    return new Evaluator(ast, JSON.parse(JSON.stringify(context), data.reviver)).evaluate().value
  }
  for (const [command, buildOnly, source, linuxX64] of [
    ['publish', false, '', 'boxlite-4vcpu-16gbmem-64gbdisk'],
    ['publish', true, '', 'ubuntu-latest'],
    ['publish-c', true, 'topic', 'ubuntu-latest'],
    ['publish-c', false, '', 'ubuntu-latest'],
    ['publish-runner', false, '', 'ubuntu-latest'],
  ]) {
    const { mode } = selectRelease(command, buildOnly, source)
    const standalone = mode === 'build'
    const caller = standalone ? readWorkflow('release-source-build').jobs['build-c'] : release.jobs['build-c']
    const context = standalone
      ? { inputs: { ref: sha, linux_x64_only: command === 'publish-runner' } }
      : { inputs: { command }, needs: { resolve: { outputs: { sha, mode } } } }
    const inputs = Object.fromEntries(Object.entries(caller.with).map(([key, value]) => [key, evaluate(value, context)]))
    assert.equal(inputs.ref, sha, 'runner selection must preserve the resolved source commit')
    for (const { os, target } of platforms) {
      const actual = evaluate(callee['runs-on'], { inputs, matrix: { os } })
      assert.equal(actual, target === 'linux-x64-gnu' ? linuxX64 : os, command + ' ' + mode + ' ' + target)
    }
  }
})

test('only a full retry can restore, while fresh and selected jobs build and upload', () => {
  const action = load(readFileSync(new URL('../../../.github/actions/release-build-cache/action.yml', import.meta.url)))
  assert.equal(action.runs.steps.find(step => step.id === 'select').if, "inputs.mode == 'restore'")
  assert.equal(action.runs.steps.find(step => step.id === 'restore').if, "steps.select.outputs.key != ''")
  const producers = [
    ...[['runtime','build'],['node','build'],['c','build'],['wheels','build_wheels'],['runner-binary','build']].map(
      ([file, id]) => readWorkflow('build-' + file).jobs[id]),
    release.jobs.publish, release.jobs['publish-runner'],
  ]
  for (const producer of producers) {
    const cache = producer.steps.find(step => step.id === 'cache')
    const save = producer.steps.find(step => step.id === 'saved')
    assert.equal(cache.with.unit, save.with.unit)
    assert.equal(cache.with.dependency, save.with.dependency)
    assert.match(cache.if, /build_plan != ''/)
    assert.match(save.if, /steps.cache.outputs.hit != 'true'/)
    for (const step of producer.steps.filter(step => step.uses?.startsWith('actions/upload-artifact@'))) {
      const platform = step.with.name === 'node-sdk-dist' ? "matrix.target == 'linux-x64-gnu'" : undefined
      assert.equal(step.if, platform, 'publish every applicable artifact on both fresh builds and cache hits')
    }
    assert.ok(producer.steps.some(step => step.name?.startsWith('Build cache receipt ') && step.if))
  }
})

test('standalone and release applies choose exactly one channel, including an unset release webhook', () => {
  const job = rollout.jobs.result
  const steps = job.steps.filter((step) => step.run?.endsWith('release-pipeline.mjs result'))
  for (const step of steps) {
    assert.match(
      expression(step.env.SLACK_WEBHOOK_URL),
      /^secrets\.(SLACK_WEBHOOK_URL|SLACK_DEV_DEPLOYMENT_WEBHOOK_URL)$/,
      'each result step must read one named secret',
    )
  }
  const channel = (inputs, secrets) => {
    const selected = steps.filter((step) => new Function('inputs', 'return ' + expression(step.if))(inputs))
    assert.equal(selected.length, 1)
    return new Function('secrets', 'return ' + expression(selected[0].env.SLACK_WEBHOOK_URL))(secrets)
  }
  const secrets = { SLACK_WEBHOOK_URL: 'release', SLACK_DEV_DEPLOYMENT_WEBHOOK_URL: 'dev' }
  for (const [stage, sha, expected] of [
    ['dev', '', 'dev'],
    ['stage', '', 'dev'],
    ['prod', '', 'release'],
    ['dev', 'sha', 'release'],
    ['prod', 'sha', 'release'],
  ]) {
    assert.equal(channel({ stage, release_sha: sha }, secrets), expected)
  }
  assert.equal(channel({ stage: 'dev', release_sha: 'sha' }, { ...secrets, SLACK_WEBHOOK_URL: '' }), '')
  assert.match(rollout.jobs.result.if, /inputs\.apply/)
  assert.equal(release.jobs.dev.secrets.SLACK_DEV_DEPLOYMENT_WEBHOOK_URL, undefined)
  const outcome = new Function('needs', 'return ' + expression(job.env.DEPLOY_RESULT))
  for (const [version, plan, deploy, expected] of [
    ['v1.2.3', 'success', 'skipped', 'success'],
    ['', 'success', 'failure', 'failure'],
    ['', 'success', 'success', 'success'],
    ['v1.2.3', 'failure', 'skipped', 'failure'],
  ]) {
    assert.equal(
      outcome({
        resolve: { result: 'success', outputs: { version } },
        plan: { result: plan },
        deploy: { result: deploy },
      }),
      expected,
    )
  }
})

test('release admission checks caller, tag, reviewers and deployment attempt before production', (t) => {
  const dir = mkdtempSync(join(tmpdir(), 'release-call-'))
  t.after(() => rmSync(dir, { recursive: true, force: true }))
  writeFileSync(join(dir, 'gh'), '#!/bin/sh\nprintf "%s\\n" "$REVIEWERS"\nexit "${GH_EXIT:-0}"\n', { mode: 0o755 })
  const guard = rollout.jobs.resolve.steps.find((step) => step.name === 'Validate release caller and published commit')
  const repo = 'boxlite-ai/boxlite'
  const base = {
    PATH: dir + ':' + process.env.PATH,
    GITHUB_REPOSITORY: repo,
    GITHUB_REF: 'refs/heads/main',
    GITHUB_WORKFLOW_REF: repo + '/.github/workflows/mbuild-release.yml@refs/heads/main',
    RESOLVED: 'a'.repeat(40),
    RELEASE_SHA: 'a'.repeat(40),
    VERSION: 'v1.2.3',
    STAGE: 'prod',
    ACCEPTED_ATTEMPT: '2',
    GITHUB_RUN_ATTEMPT: '2',
    REVIEWERS: JSON.stringify({ protection_rules: [{ type: 'required_reviewers', reviewers: [{ type: 'User' }] }] }),
  }
  const run = (script, extra) => spawnSync('bash', ['-c', script], { env: { ...base, ...extra } }).status
  assert.equal(run(guard.run, {}), 0)
  for (const overrides of [
    { GITHUB_WORKFLOW_REF: 'unexpected' },
    { RESOLVED: 'b'.repeat(40) },
    { VERSION: '' },
    { STAGE: 'stage' },
    { REVIEWERS: '{"protection_rules":[]}' },
    { GH_EXIT: '1' },
  ])
    assert.notEqual(run(guard.run, overrides), 0)
  assert.equal(run(guard.run, { STAGE: 'dev', ACCEPTED_ATTEMPT: '', GH_EXIT: '1' }), 0)
  const cloud = readWorkflow('e2e-cloud')
  const e2eGuard = cloud.jobs.e2e.steps.find((step) => step.env?.DEPLOYMENT_ATTEMPT)
  for (const [attempt, sha, expected] of [
    ['2', base.RELEASE_SHA, 0],
    ['1', base.RELEASE_SHA, 1],
    ['2', 'b'.repeat(40), 1],
  ]) {
    assert.equal(
      run(e2eGuard.run, {
        DEPLOYMENT_ATTEMPT: attempt,
        REVIEWERS: sha,
        RELEASE_TAG: base.VERSION,
        GITHUB_OUTPUT: join(dir, 'outputs'),
      }),
      expected,
    )
  }
  const checkout = cloud.jobs.e2e.steps.find(
    (step) => step.name === 'Checkout release SDK sources for subdomain clients',
  )
  assert.equal(
    checkout.env?.RELEASE_SDK_SHA,
    '${{ steps.release_commit.outputs.sha }}',
    'release SDK checkout must use the verified commit',
  )
  const outputs = join(dir, 'standalone-outputs')
  const standalone = { DEPLOYMENT_ATTEMPT: '', RELEASE_SHA: '', RELEASE_TAG: base.VERSION, GITHUB_OUTPUT: outputs }
  assert.notEqual(run(e2eGuard.run, { ...standalone, REVIEWERS: base.VERSION }), 0)
  assert.equal(run(e2eGuard.run, { ...standalone, REVIEWERS: base.RELEASE_SHA }), 0)
  assert.equal(readFileSync(outputs, 'utf8'), 'sha=' + base.RELEASE_SHA + '\n')
})

test('prod may retry a previous attempt only with the exact dev acceptance receipt', (t) => {
  const dir = mkdtempSync(join(tmpdir(), 'prod-retry-'))
  t.after(() => rmSync(dir, { recursive: true, force: true }))
  writeFileSync(
    join(dir, 'gh'),
    '#!/bin/bash\nset -eu\nmkdir -p "${@: -1}"\ncp "$RECEIPT" "${@: -1}/acceptance.json"\n',
    { mode: 0o755 },
  )
  const sha = 'a'.repeat(40),
    digest = 'sha256:' + 'b'.repeat(64)
  const accepted = { status: 'passed', run: 44, attempt: 1, candidate: 77, digest, sha, tag: 'v1.2.3' }
  const env = {
    ...process.env,
    PATH: dir + ':' + process.env.PATH,
    RUNNER_TEMP: dir,
    RECEIPT: join(dir, 'receipt'),
    GITHUB_RUN_ATTEMPT: '2',
    GITHUB_RUN_ID: '44',
    GITHUB_REPOSITORY: 'boxlite-ai/boxlite',
    E2E_WAIVED: 'false',
    PINS: JSON.stringify({ images: { api: digest }, runner: { manifest: digest, archive: digest } }),
    ACCEPTED_ATTEMPT: '1',
    CANDIDATE: '77',
    DIGEST: digest,
    TAG: accepted.tag,
    SHA: sha,
  }
  for (const job of [rollout.jobs.plan, rollout.jobs.resolve]) {
    const guard = job.steps.find((step) => step.name === 'Verify dev acceptance for the production candidate')
    for (const [changed, expected] of [
      [{}, 0],
      [{ candidate: 78 }, 1],
      [{ digest: 'sha256:' + 'c'.repeat(64) }, 1],
      [{ sha: 'd'.repeat(40) }, 1],
      [{ run: 45 }, 1],
      [{ attempt: 3 }, 1],
      [{ tag: 'v1.2.4' }, 1],
    ]) {
      writeFileSync(env.RECEIPT, JSON.stringify({ ...accepted, ...changed }))
      const result = spawnSync('bash', ['-c', guard.run], { env, encoding: 'utf8' })
      assert.equal(result.status === 0, expected === 0, 'receipt ' + JSON.stringify(changed) + ' ' + result.stderr)
    }
    const waived = { ...accepted, ...JSON.parse(env.PINS), status: 'waived', approval: { reviewer: 'operator', reason: 'known failure', evidence_id: '34' } }
    for (const [changes, allowed] of [[{}, true], [{ status: 'passed' }, false], [{ approval: {} }, false], [{ images: {} }, false], [{ runner: {} }, false]]) {
      writeFileSync(env.RECEIPT, JSON.stringify({ ...waived, ...changes }))
      const result = spawnSync('bash', ['-c', guard.run], { env: { ...env, E2E_WAIVED: 'true' } })
      assert.equal(result.status === 0, allowed, 'waived receipt ' + JSON.stringify(changes))
    }
  }
})

test('npm preflights all packages and publishes in order while new versions await indexing', (t) => {
  const dir = mkdtempSync(join(tmpdir(), 'boxlite-npm-publication-'))
  t.after(() => rmSync(dir, { recursive: true, force: true }))
  const tag = 'v1.2.3'
  const platform = '@boxlite-ai/[email protected]'
  const main = '@boxlite-ai/[email protected]'
  const record = join(dir, 'published')
  mkdirSync(join(dir, 'package'))
  writeFileSync(record, '')
  for (const id of [platform, main]) {
    const name = id.slice(0, id.lastIndexOf('@'))
    const file = name.slice(1).replace('/', '-') + '-1.2.3.tgz'
    writeFileSync(join(dir, 'package', 'package.json'), JSON.stringify({ name, version: '1.2.3' }))
    execFileSync('tar', ['-czf', file, 'package/package.json'], { cwd: dir })
  }
  writeFileSync(join(dir, 'npm'), [
    '#!/bin/bash',
    'set -euo pipefail',
    'case "$1" in',
    '  view)',
    '    if [[ -f "$RUNNER_TEMP/lookup-failure" ]]; then echo "npm error code E401" >&2; exit 1; fi',
    '    if [[ ! -f "$RUNNER_TEMP/${2##*/}.visible" ]]; then echo "npm error code E404" >&2; exit 1; fi',
    '    cat "$RUNNER_TEMP/${2##*/}.visible" ;;',
    '  publish)',
    "    id=$(tar -xOzf \"$2\" package/package.json | jq -r '.name + \"@\" + .version')",
    '    if [[ "${FAIL_PUBLISH:-}" == "$id" ]]; then exit 3; fi',
    '    echo "$id" >> "$RUNNER_TEMP/published" ;;',
    '  *) exit 2 ;;',
    'esac',
  ].join('\n'), { mode: 0o755 })
  const script = release.jobs.npm.steps.find(step => step.name === 'Publish platform packages before the main package').run
  const publish = (extra = {}) => spawnSync('bash', ['-ec', script], {
    cwd: dir, encoding: 'utf8',
    env: { ...process.env, PATH: dir + ':' + process.env.PATH, RELEASE_ASSET_DIR: dir, RUNNER_TEMP: dir, GITHUB_WORKSPACE: workspace, GITHUB_STEP_SUMMARY: join(dir, 'summary'), TAG: tag, ...extra },
  })
  const lookupFailure = join(dir, 'lookup-failure')
  writeFileSync(lookupFailure, '')
  assert.notEqual(publish().status, 0)
  assert.equal(readFileSync(record, 'utf8'), '', 'an unauthorized lookup must stop publication')
  rmSync(lookupFailure)
  assert.equal(publish({ FAIL_PUBLISH: platform }).status, 3)
  assert.equal(readFileSync(record, 'utf8'), '', 'a platform publish failure must stop the main publish')
  const first = publish()
  assert.equal(first.status, 0, first.stderr)
  assert.deepEqual(readFileSync(record, 'utf8').trim().split('\n'), [platform, main])

  writeFileSync(record, '')
  const summary = join(dir, 'summary')
  writeFileSync(summary, '')
  const integrity = name => 'sha512-' + createHash('sha512').update(readFileSync(join(dir, name))).digest('base64')
  const existing = (name, sri) => writeFileSync(join(dir, name + '@1.2.3.visible'), JSON.stringify({ version: '1.2.3', 'dist.integrity': sri }))
  existing('boxlite-linux-x64-gnu', integrity('boxlite-ai-boxlite-linux-x64-gnu-1.2.3.tgz'))
  assert.equal(publish().status, 0)
  assert.equal(readFileSync(record, 'utf8').trim(), main)
  writeFileSync(record, '')
  assert.equal(readFileSync(summary, 'utf8'), '', 'identical bytes are silent')
  const other = 'sha512-' + createHash('sha512').update('other').digest('base64')
  existing('boxlite', other)
  assert.equal(publish().status, 0)
  assert.equal(readFileSync(record, 'utf8'), '', 'published versions must be skipped')
  assert.ok(readFileSync(summary, 'utf8').includes(other), 'report both digests for an existing, different tarball')
  assert.ok(readFileSync(summary, 'utf8').includes(integrity('boxlite-ai-boxlite-1.2.3.tgz')))
  existing('boxlite', null)
  assert.equal(publish().status, 0)
  assert.match(readFileSync(summary, 'utf8'), /could not compare/i)
  assert.equal(readFileSync(record, 'utf8'), '')
})

function mockRegistry(dir) {
  writeFileSync(join(dir, 'curl'), [
    '#!/bin/bash', 'set -eu',
    'while [[ "$1" == --* ]]; do',
    '  case "$1" in --output) out=$2; shift 2 ;; --max-time|--retry|--user-agent|--write-out) shift 2 ;; *) shift ;; esac',
    'done',
    '[[ "$1" == "$EXPECTED_URL" ]]',
    'cat "$RUNNER_TEMP/response" > "$out"',
    'printf %s "$HTTP"',
  ].join('\n'), { mode: 0o755 })
}

test('PyPI selects missing wheel filenames and reports only differing or unavailable checksums', t => {
  const dir = mkdtempSync(join(tmpdir(), 'boxlite-pypi-'))
  t.after(() => rmSync(dir, { recursive: true, force: true }))
  const steps = release.jobs.pypi.steps
  const select = steps.find(step => step.name === 'Select accepted wheels')
  const upload = steps.at(-1)
  assert.equal(upload.uses, 'pypa/gh-action-pypi-publish@release/v1')
  assert.equal(upload.with['skip-existing'], true)
  const names = ['a.whl', 'b.whl', 'c.whl', 'd.whl']
  for (const name of names) writeFileSync(join(dir, name), name)
  const summary = join(dir, 'summary')
  writeFileSync(summary, '')
  const sum = text => createHash('sha256').update(text).digest('hex')
  const urls = names.slice(0, 3).map((filename, i) => ({ filename, digests: { sha256: [sum(filename), sum('other'), null][i] } }))
  mockRegistry(dir)
  const run = (http, files) => {
    rmSync(join(dir, 'dist'), { recursive: true, force: true })
    writeFileSync(join(dir, 'response'), JSON.stringify({ urls: files }))
    return spawnSync('bash', ['-ec', select.run], { cwd: dir, encoding: 'utf8',
      env: { ...process.env, PATH: dir + ':' + process.env.PATH, GITHUB_WORKSPACE: workspace, RUNNER_TEMP: dir, RELEASE_ASSET_DIR: dir,
        GITHUB_OUTPUT: join(dir, 'output'), GITHUB_STEP_SUMMARY: summary, TAG: 'v1.2.3', HTTP: http, EXPECTED_URL: 'https://pypi.org/pypi/boxlite/1.2.3/json' } })
  }
  const mixed = run('200', urls)
  assert.equal(mixed.status, 0, mixed.stderr)
  assert.deepEqual(readdirSync(join(dir, 'dist')), ['d.whl'])
  assert.match(readFileSync(summary, 'utf8'), /b\.whl/)
  assert.match(readFileSync(summary, 'utf8'), /c\.whl.*could not compare/i)
  assert.doesNotMatch(readFileSync(summary, 'utf8'), /a\.whl/)
  assert.equal(run('404', []).status, 0)
  assert.deepEqual(readdirSync(join(dir, 'dist')).sort(), names)
  assert.equal(run('200', [...urls, { filename: 'd.whl', digests: { sha256: sum('d.whl') } }]).status, 0)
  assert.match(readFileSync(join(dir, 'output'), 'utf8').trim(), /has_missing=false$/)
  assert.match(upload.if, /steps\.wheels\.outputs\.has_missing == 'true'/)
  assert.notEqual(run('503', []).status, 0, 'unavailable inventory is not an empty inventory')
})

test('build-only never enters deployment, checks, or reporting; failed E2E cannot stamp acceptance', () => {
  for (const id of ['distribution', 'dev', 'prod']) assert.match(release.jobs[id].if, /needs\.resolve\.outputs\.mode == 'release'/)
  assert.match(release.jobs.report.if, /!inputs\['build-only'\]/)
  assert.equal(rollout.concurrency.group, 'mdeploy-all-${{ inputs.stage }}')
  assert.notEqual(release.concurrency.group, rollout.concurrency.group)
  const outputs = rollout.on.workflow_call.outputs
  const stamp = new Function('jobs', 'return ' + expression(outputs.accepted_attempt.value))
  for (const result of ['failure', 'cancelled', 'skipped', 'success']) {
    assert.equal(
      stamp({
        plan: { result: 'success', outputs: { deployment_attempt: '2' } },
        e2e: { outputs: { release_result: result } },
      }),
      result === 'success' ? '2' : '',
    )
  }
  assert.equal(outputs.e2e_result.value, '${{ jobs.e2e.outputs.release_result }}')
  const cloud = readWorkflow('e2e-cloud')
  assert.equal(cloud.on.workflow_call.outputs.release_result.value, '${{ jobs.e2e.outputs.release_result }}')
  assert.equal(cloud.jobs.e2e.outputs.release_result, '${{ steps.acceptance.outputs.result }}')
  const summary = cloud.jobs.e2e.steps.at(-1)
  assert.equal(summary.id, 'acceptance')
  assert.equal(summary.if, 'always() && inputs.deployment_attempt')
  assert.equal(summary.env.E2E_RESULT, "${{ job.status == 'success' && steps.verdict.outputs.result || job.status }}")
  assert.match(release.jobs.report.if, /contains\(needs\.\*\.result, 'failure'\)/)
  assert.match(release.jobs.report.if, /contains\(needs\.\*\.result, 'cancelled'\)/)
  for (const job of ['dev','package-runtime','package-node','attach','finalize','pypi','npm','publish_crates']) assert.ok(release.jobs.report.needs.includes(job), 'Missing failure reporting for ' + job)
  assert.match(release.jobs.prod.if, /needs\.dev\.outputs\.accepted_attempt != ''/)
})

test('only a prod approval after dev acceptance carries the E2E success', () => {
  const notice = rollout.jobs.resolve.steps.find((step) => step.name === 'Notify release reviewers')
  assert.ok(notice.env.ACCEPTED_TAG, 'prod approval must include the accepted tag')
  const accepted = new Function('inputs', 'return ' + expression(notice.env.ACCEPTED_TAG))
  for (const [stage, attempt, expected] of [
    ['dev', '', ''],
    ['prod', '', ''],
    ['prod', '2', 'v1.2.3'],
  ]) {
    assert.equal(accepted({ stage, accepted_attempt: attempt, ref: 'v1.2.3' }), expected)
  }
})

test('the cloud suite cannot write the default branch cache', () => {
  const cloud = readWorkflow('e2e-cloud')
  assert.ok(
    ['read', 'none'].includes(cloud.jobs.e2e['cache-mode'] || cloud['cache-mode']),
    'E2E needs a read-only cache',
  )
})

test('release SDK worktree uses the verified commit even when the remote has advanced', (t) => {
  const dir = mkdtempSync(join(tmpdir(), 'cloud-sdk-'))
  t.after(() => rmSync(dir, { recursive: true, force: true }))
  const git = (...args) =>
    execFileSync('git', args, { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim()
  git('init', '-q', 'source')
  const commit = (text) =>
    git(
      '-C',
      'source',
      '-c',
      'user.name=Test',
      '-c',
      '[email protected]',
      '-c',
      'commit.gpgsign=false',
      '-c',
      'core.hooksPath=/dev/null',
      'commit',
      '-q',
      '--allow-empty',
      '-m',
      text,
    )
  commit('published')
  const sha = git('-C', 'source', 'rev-parse', 'HEAD')
  commit('later change')
  git('init', '-q', 'suite')
  const step = readWorkflow('e2e-cloud').jobs.e2e.steps.find(
    (s) => s.name === 'Checkout release SDK sources for subdomain clients',
  )
  assert.ok(step.run, 'the suite should share its Git object store with the release SDK worktree')
  const run = (ref) =>
    spawnSync('bash', ['-c', step.run], {
      cwd: join(dir, 'suite'),
      encoding: 'utf8',
      env: {
        ...process.env,
        RELEASE_SDK_SHA: ref,
        GIT_CONFIG_COUNT: '1',
        GIT_CONFIG_KEY_0: 'url.file://' + join(dir, 'source') + '.insteadOf',
        GIT_CONFIG_VALUE_0: 'https://github.com/boxlite-ai/boxlite.git',
      },
    })
  const missing = run('0'.repeat(40))
  assert.notEqual(missing.status, 0)
  const result = run(sha)
  assert.equal(result.status, 0, result.stderr)
  assert.equal(git('-C', 'suite/target/e2e-release', 'rev-parse', 'HEAD'), sha)
  const common = (path) => git('-C', path, 'rev-parse', '--path-format=absolute', '--git-common-dir')
  assert.equal(common('suite/target/e2e-release'), common('suite'))
})

test('component repairs snapshot the public Release and package publishers stay in the entry workflow', () => {
  const commands = release.on.workflow_dispatch.inputs.command.options
  assert.deepEqual(commands.filter(name => name.startsWith('repair-')), ['repair-runtime', 'repair-wheels', 'repair-node', 'repair-c', 'repair-go'])
  assert.equal(release.on.workflow_dispatch.inputs['candidate-id'], undefined)
  const recovery = release.jobs['accepted-candidate']
  assert.equal(recovery.concurrency.group, release.jobs.attach.concurrency.group)
  assert.match(recovery.steps.find(step => step.id === 'repair').run, /release-candidate.mjs repair/)
  const attach = release.jobs.attach
  assert.ok(attach.needs.includes('accepted-candidate'))
  for (const [job, command] of [['npm','repair-node'],['pypi','repair-wheels']]) {
    const publisher=release.jobs[job]
    assert.ok(publisher.needs.includes('attach'))
    assert.equal(publisher.permissions['id-token'],'write')
    assert.ok(publisher.if.includes(command))
    const input=publisher.steps.find((step)=>step.uses==='./.github/actions/release-candidate').with
    assert.equal(input.run,'${{ needs.attach.outputs.run }}')
    assert.equal(input.id,'${{ needs.attach.outputs.candidate }}')
    assert.equal(input.digest,'${{ needs.attach.outputs.digest }}')
  }
  assert.ok(release.jobs.publish_crates.needs.includes('finalize'))
  assert.ok(release.jobs.finalize.if.includes("inputs.command == 'publish'"))
})

test('completed builds unlock dev and dev acceptance independently unlocks prod and publication', () => {
  const jobs = release.jobs
  assert.deepEqual(jobs.dev.needs, ['resolve', 'publish', 'publish-runner', 'build-runtime', 'build-c', 'build-wheels', 'build-node'], 'dev requires all client and registry producers')
  assert.equal(jobs.check, undefined)
  const prepare = rollout.jobs.resolve
  const validate = prepare.steps.findIndex((step) => step.run?.includes('release-candidate.mjs deployment'))
  const upload = prepare.steps.findIndex((step) => step.with?.name?.startsWith('deployment-candidate-'))
  const approve = prepare.steps.findIndex((step) => step.name === 'Notify release reviewers')
  const download = prepare.steps.findIndex((step) => step.with?.pattern === 'ghcr-*')
  assert.ok(download >= 0 && download < validate && validate < upload && upload < approve)
  for (const index of [download, validate, upload]) {
    const stageCandidate = new Function('inputs', 'return ' + prepare.steps[index].if)
    assert.ok(stageCandidate({ stage: 'dev', release_sha: 'release-commit' }))
    assert.ok(!stageCandidate({ stage: 'prod', release_sha: 'release-commit' }))
    assert.ok(!stageCandidate({ stage: 'dev' }))
  }
  for (const key of ['candidate_id', 'candidate_digest', 'registry_digests']) {
    assert.equal(rollout.on.workflow_call.outputs[key].value, '$' + '{{ jobs.resolve.outputs.' + key + ' }}')
    assert.equal(jobs.prod.with[key], '$' + '{{ needs.dev.outputs.' + key + ' }}')
  }
  for (const key of ['candidate_id', 'candidate_digest']) {
    assert.equal(rollout.jobs.e2e.with[key], '$' + '{{ needs.resolve.outputs.' + key + ' }}')
  }
  assert.equal(jobs.dev.with.release_images, '$' + '{{ needs.resolve.outputs.artifacts }}')
  assert.equal(prepare.steps[validate].env.IMAGES, '$' + '{{ inputs.release_images }}')
  assert.deepEqual(jobs.prod.needs, ['resolve', 'dev', 'e2e-override'], 'prod can start as soon as dev passes or the failed candidate receives a waiver')
  assert.ok(jobs.attach.needs.includes('dev'))
  assert.ok(jobs.attach.needs.includes('distribution'))
  assert.ok(jobs.attach.needs.includes('build-go'))
  assert.ok(!jobs.attach.needs.includes('prod'))
  assert.ok(jobs.publish_crates.needs.includes('finalize'))
})

test('crates.io publishes missing crates and only reports differences or unavailable comparisons for existing versions', t => {
  const dir = mkdtempSync(join(tmpdir(), 'boxlite-crates-publish-'))
  t.after(() => rmSync(dir, { recursive: true, force: true }))
  const summary = join(dir, 'summary')
  writeFileSync(summary, '')
  mockRegistry(dir)
  writeFileSync(join(dir, 'cargo'), [
    '#!/bin/bash', 'set -eu', 'echo "$1" >> "$RUNNER_TEMP/calls"',
    'if [[ "$1" == package ]]; then',
    '  [[ "$PACK" == ok ]] || exit 3',
    '  mkdir -p "$CARGO_TARGET_DIR/package"',
    '  printf bytes > "$CARGO_TARGET_DIR/package/$3-1.2.3.crate"',
    'elif [[ "$PUSH" == duplicate ]]; then echo "error: crate [email protected] already exists on crates.io index" >&2; exit 101',
    'else exit "$PUSH"; fi',
  ].join('\n'), { mode: 0o755 })
  const tier = release.jobs.publish_crates.steps.find(step => step.name === 'Publish boxlite (Tier 2)')
  symlinkSync(workspace, join(dir, '.release-ci'), 'dir')
  const digest = bytes => createHash('sha256').update(bytes).digest('hex')
  function run(http, checksum, { pack = 'ok', push = '0' } = {}) {
    writeFileSync(join(dir, 'calls'), '')
    writeFileSync(join(dir, 'response'), JSON.stringify({ version: { checksum } }))
    const result = spawnSync('bash', ['-ec', tier.run], { cwd: dir, encoding: 'utf8',
      env: { ...process.env, PATH: dir + ':' + process.env.PATH, RELEASE_TAG: 'v1.2.3', RUNNER_TEMP: dir, GITHUB_WORKSPACE: dir,
        GITHUB_STEP_SUMMARY: summary, HTTP: http, EXPECTED_URL: 'https://crates.io/api/v1/crates/boxlite/1.2.3', PACK: pack, PUSH: push } })
    return { status: result.status, calls: readFileSync(join(dir, 'calls'), 'utf8').trim(), stderr: result.stderr }
  }
  assert.equal(run('200', digest('bytes')).calls, 'package')
  assert.equal(readFileSync(summary, 'utf8'), '')
  assert.equal(run('200', digest('different')).status, 0)
  assert.ok(readFileSync(summary, 'utf8').includes(digest('different')))
  assert.ok(readFileSync(summary, 'utf8').includes(digest('bytes')))
  assert.equal(run('200', digest('bytes'), { pack: 'fail' }).status, 0)
  assert.match(readFileSync(summary, 'utf8'), /could not compare/i)
  assert.equal(run('404', null).calls, 'publish')
  assert.notEqual(run('404', null, { push: '7' }).status, 0)
  assert.equal(run('404', null, { push: 'duplicate' }).status, 0)
  assert.notEqual(run('503', null).status, 0)
})

test('Go tag stays unpublished until every C SDK can be downloaded anonymously for this public release', (t) => {
  const dir = mkdtempSync(join(tmpdir(), 'go-public-c-'))
  t.after(() => rmSync(dir, { recursive: true, force: true }))
  const root = new URL('../../../', import.meta.url)
  const tag = 'v1.2.3'
  const goRef = 'refs/tags/sdks/go/' + tag
  const git = (...args) => execFileSync('git', args, { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim()
  git('init', '--bare', 'origin.git')
  git('init')
  git('-c', 'user.name=Fixture', '-c', '[email protected]', '-c', 'commit.gpgSign=false', 'commit', '--allow-empty', '-m', 'source')
  const sha = git('rev-parse', 'HEAD')
  git('remote', 'add', 'origin', join(dir, 'origin.git'))
  git('push', 'origin', sha + ':refs/tags/' + tag)
  git('-c', 'user.name=Fixture', '-c', '[email protected]', '-c', 'commit.gpgSign=false', 'commit', '--allow-empty', '-m', 'different')
  const other = git('rev-parse', 'HEAD')
  git('push', 'origin', other + ':refs/heads/other')
  for (const path of ['apps/infra/scripts/release-candidate.mjs', '.github/ci-config.json']) {
    mkdirSync(dirname(join(dir, path)), { recursive: true })
    copyFileSync(new URL(path, root), join(dir, path))
  }

  const targets = JSON.parse(readFileSync(new URL('.github/ci-config.json', root))).platforms
  const assets = targets.map(({ target }) => {
    const name = 'boxlite-c-' + tag + '-' + target + '.tar.gz'
    return { name, size: name.length, state: 'uploaded', digest: 'sha256:' + createHash('sha256').update(name).digest('hex') }
  })
  writeFileSync(join(dir, 'gh'), [
    '#!/bin/sh',
    'case "$*" in',
    '  "api repos/boxlite-ai/boxlite/releases/123") cat "$FIXTURE/release.json" ;;',
    '  *"/releases/123/assets?per_page=100") cat "$FIXTURE/assets.json" ;;',
    '  *) exit 2 ;;',
    'esac',
  ].join('\n'), { mode: 0o755 })
  writeFileSync(join(dir, 'public-fetch.mjs'), `
    import { execFileSync } from 'node:child_process'
    globalThis.fetch = async (url, options) => {
      const request = new Request(url, options)
      const base = 'https://github.com/boxlite-ai/boxlite/releases/download/v1.2.3/'
      if (!request.url.startsWith(base) || request.method !== 'GET' || request.headers.has('authorization')) throw Error('unexpected request')
      const name = request.url.slice(base.length)
      if (process.env.MOVE_PRODUCT_TAG && name === process.env.LAST_ARCHIVE) {
        const ref = 'refs/tags/' + process.env.RELEASE_TAG
        const update = process.env.MOVE_PRODUCT_TAG === 'delete' ? ['-d', ref] : [ref, process.env.MOVE_PRODUCT_TAG]
        execFileSync('git', ['--git-dir=origin.git', 'update-ref', ...update])
      }
      if (name === process.env.UNAVAILABLE) return new Response(null, { status: 404 })
      return new Response(name === process.env.CORRUPT ? 'wrong bytes' : name)
    }
  `)
  const steps = release.jobs['tag-go-module'].steps.filter(step => step.run).map(step => step.run)
  function publish({ draft = false, files = assets, ...extra } = {}) {
    writeFileSync(join(dir, 'release.json'), JSON.stringify({ tag_name: tag, draft }))
    writeFileSync(join(dir, 'assets.json'), JSON.stringify([files]))
    return spawnSync('bash', ['-ec', steps.join('\n')], { cwd: dir, encoding: 'utf8',
      env: { ...process.env, FIXTURE: dir, PATH: dir + ':' + process.env.PATH, GITHUB_REPOSITORY: 'boxlite-ai/boxlite',
        GITHUB_STEP_SUMMARY: join(dir, 'summary'), TAG: tag, RELEASE_TAG: tag, RELEASE_ID: '123', C_SHA: sha, NODE_OPTIONS: '--import=' + join(dir, 'public-fetch.mjs'), ...extra },
    })
  }
  for (const [reason, options] of [
    ['draft', { draft: true }], ['missing asset', { files: assets.slice(1) }],
    ['anonymous 404', { UNAVAILABLE: assets.at(-1).name }], ['wrong bytes', { CORRUPT: assets[0].name }],
  ]) {
    const result = publish(options)
    assert.equal(git('ls-remote', '--refs', 'origin', goRef), '', 'Go tag was pushed for ' + reason)
    assert.notEqual(result.status, 0, reason)
  }
  for (const target of [other, 'delete']) {
    const result = publish({ MOVE_PRODUCT_TAG: target, LAST_ARCHIVE: assets.at(-1).name })
    assert.equal(git('ls-remote', '--refs', 'origin', 'refs/tags/' + tag).split('\t')[0], target === 'delete' ? '' : other)
    assert.equal(git('ls-remote', '--refs', 'origin', goRef), '', 'a product tag changed during download must block the Go tag')
    assert.notEqual(result.status, 0)
    git('push', '--force', 'origin', sha + ':refs/tags/' + tag)
  }
  for (let attempt = 0; attempt < 2; attempt++) {
    const result = publish(attempt === 0 ? {} : { UNAVAILABLE: assets[0].name })
    assert.equal(result.status, 0, result.stderr)
    assert.equal(git('ls-remote', '--refs', 'origin', goRef), sha + '\t' + goRef)
  }
  git('push', '--force', 'origin', other + ':' + goRef)
  const skipped = publish()
  assert.equal(skipped.status, 0, skipped.stderr)
  assert.ok(readFileSync(join(dir, 'summary'), 'utf8').includes(other))
  assert.ok(readFileSync(join(dir, 'summary'), 'utf8').includes(sha))
  assert.equal(git('ls-remote', '--refs', 'origin', goRef), other + '\t' + goRef)
})

test('publication gates accept a skipped optional ancestor and require successful direct prerequisites', () => {
  for (const [id, prerequisites, commands] of [
    ['npm', ['attach'], ['publish', 'publish-node', 'repair-node']],
    ['pypi', ['attach'], ['publish', 'publish-wheels', 'repair-wheels']],
    ['tag-go-module', ['finalize'], ['publish', 'publish-go', 'repair-go']],
    ['finalize', ['npm', 'pypi', 'attach'], ['publish']],
    ['publish_crates', ['finalize'], ['publish', 'publish-runtime', 'repair-runtime']],
  ]) {
    const condition = expression(release.jobs[id].if)
    const evaluate = new Function('github', 'inputs', 'needs', 'cancelled', 'contains', 'fromJSON',
      'return ' + condition.replace(/needs\.([\w]+-[\w-]+)/g, "needs['$1']"))
    const needs = Object.fromEntries(release.jobs[id].needs.map((name) => [name, { result: 'success' }]))
    needs.resolve.outputs = { public_release: 'true' }
    const selected = (command, cancelled = false, ref = 'refs/heads/main') => {
      // GitHub implicitly adds success() when the condition omits a status function.
      if (!/\b(success|failure|always|cancelled)\(/.test(condition)) return false
      return evaluate({ ref }, { command }, needs, () => cancelled, (a, b) => a.includes(b), JSON.parse)
    }
    for (const command of release.on.workflow_dispatch.inputs.command.options) {
      assert.equal(selected(command), commands.includes(command), id + ' on ' + command)
    }
    for (const name of prerequisites) {
      needs[name] ??= { result: 'success' }
      for (const result of ['skipped', 'failure', 'cancelled']) {
        needs[name].result = result
        assert.equal(selected('publish'), false, id + ' after ' + name + ' ' + result)
      }
      needs[name].result = 'success'
    }
    assert.equal(selected('publish', true), false)
    assert.equal(selected('publish', false, 'refs/heads/topic'), false)
  }
})

test('single components select their producers and bypass rollout, including with skipped sibling jobs', () => {
  for (const [component, group] of Object.entries({ runtime: 'runtime-distribution', wheels: 'wheels-', node: 'node-packages', c: 'c-sdk-', go: '', runner: 'runner-linux-amd64' })) {
    const command = 'publish-' + component
    for (const buildOnly of [true, false]) {
      const selection = selectRelease(command, buildOnly, '')
      assert.equal(selection.group, group)
      const needs = Object.fromEntries(Object.keys(release.jobs).map(id => [id, { result: 'skipped', outputs: {} }]))
      needs.resolve = { result: 'success', outputs: { ...selection, builds: JSON.stringify(selection.builds) } }
      const allows = (id, jobs = release.jobs, inputs = { command, 'build-only': buildOnly }, state = needs) => {
        const job = jobs[id]
        const deps = [job.needs || []].flat()
        const condition = expression(job.if).replaceAll('needs.*.result', 'results').replace(/needs\.([\w]+-[\w-]+)/g, "needs['$1']")
        const statuses = deps.map(dep => state[dep].result)
        if (!condition.includes('cancelled()') && statuses.some(result => result !== 'success')) return false
        const evaluate = new Function('needs','results','inputs','github','contains','fromJSON','cancelled','return ' + condition)
        return Boolean(evaluate(state, statuses, inputs, { ref: 'refs/heads/main' }, (a,b) => a.includes(b), JSON.parse, () => false))
      }
      const enabled = []
      assert.equal(allows('standalone-build'), buildOnly)
      if (buildOnly) {
        const caller = release.jobs['standalone-build']
        assert.equal(caller.with.builds, '${{ needs.resolve.outputs.builds }}')
        const nested = readWorkflow(caller.uses.split('/').pop().replace('.yml', ''))
        assert.deepEqual(Object.keys(nested.on), ['workflow_call'])
        const inner = Object.fromEntries(Object.keys(nested.jobs).map(id => [id, { result: 'skipped' }]))
        for (const [id, job] of Object.entries(nested.jobs)) {
          assert.equal(job.uses, release.jobs[id].uses)
          if (!allows(id, nested.jobs, needs.resolve.outputs, inner)) continue
          enabled.push(id)
          inner[id].result = 'success'
        }
      }
      for (const id of ['build-runtime','build-wheels','build-node','build-c','build-go','build-runner-binary','publish','publish-runner','distribution','accepted-candidate','dev','attach','npm','pypi','prod','finalize','tag-go-module','publish_crates']) {
        if (allows(id)) { enabled.push(id); needs[id].result = 'success' }
      }
      const expected = ['go','runner'].includes(component) ? ['build-c'] : []
      expected.push(component === 'runner' ? 'build-runner-binary' : 'build-' + component)
      if (!buildOnly) {
        if (component === 'runner') expected.push('publish-runner')
        if (group) expected.push('distribution','attach')
        if (component === 'node') expected.push('npm')
        if (component === 'wheels') expected.push('pypi')
        if (component === 'go') expected.push('tag-go-module')
      }
      assert.deepEqual(enabled, expected, command + ' build-only=' + buildOnly)
      if (!buildOnly && group) {
        needs[selection.producer].result = 'failure'
        assert.equal(allows('distribution'), false, 'failed ' + component + ' must block publication')
      }
      if (!buildOnly && component === 'runtime') {
        needs.resolve.outputs.public_release = 'true'
        assert.equal(allows('publish_crates'), true)
      }
    }
  }
  assert.throws(() => selectRelease('publish-c', false, 'feature'))
  assert.equal(selectRelease('repair-node', false, '').mode, 'repair')
  assert.throws(() => selectRelease('repair-node', true, ''))
})

test('the installer and its smoke test use the release source checkout', () => {
  const steps = readWorkflow('package-runtime').jobs.package.steps
  const smoke = steps.find(step => step.env?.BOXLITE_INSTALL_TEMPLATE)
  const script = smoke.run.match(/bash ([^ ]*scripts\/release\/test_install\.sh)/)[1]
  const checkout = steps.filter(step => step.uses?.startsWith('actions/checkout@'))
    .find(step => script.startsWith((step.with.path ? step.with.path + '/' : '') + 'scripts/'))
  assert.equal(checkout.with.ref, steps.find(step => step.uses?.startsWith('actions/checkout@')).with.ref)
})