Skip to content

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

13.2 KB
Raw Blame
#!/usr/bin/env node
import { writeFile } from 'node:fs/promises'

/*
 * `npm run mbuild publish -- --tag <sha> --stage dev`
 * `npm run mbuild promote -- --tag <sha> --from dev --to prod`
 * `npm run mbuild verify  -- --tag <sha> --stage dev`
 *
 * Credentials are the ambient ones: the caller has already federated a role
 * through OIDC, and asking for them again here would be a second source of
 * truth about who is publishing. The account is read once and used for both
 * registries, because a promotion between accounts would need a role for each
 * and nothing here would know which.
 *
 * Where a stage lives comes from mstage, which is the one file that declares it.
 * mbuild's own config says what to build and which repository receives it, and
 * deliberately does not repeat the region.
 */

import { loadConfig as loadStageConfig, type StageConfig } from 'mstage/config'
import { deploymentArtifacts, loadArtifactConfig, loadBuildConfig, onlyArtifact, registryFor, stageIn, type BuildConfig } from '../src/config.ts'
import { assertTag, ghcrRegistryFor, releaseImageDigests, releaseTagFor, resolveRegistry } from '../src/address.ts'
import { assertPromotable, coordinatesOf, type Coordinates } from '../src/coordinates.ts'
import {
  AuditFailedError,
  NotPublishedError,
  promote,
  publish,
  ScanRefusedError,
  verifyPublished,
} from '../src/publish.ts'
import { run } from '../src/run.ts'

/** Every unsuccessful dependency audit stops publication without automatic retries. */
const AUDIT_FAILED_EXIT = 65

/**
 * The exit code a scan refusal reports.
 *
 * A caller retries a publish because a push and a token endpoint fail
 * transiently. The scan gate does not: its answer is about the image's own
 * contents and a second ask returns it again. A distinct code is what lets the
 * shell in `.github/workflows/mbuild.yml` stop rather than spend two more
 * attempts re-reading the same findings.
 *
 * 78 is `EX_CONFIG` from `sysexits.h` — "something was wrong in the input", as
 * opposed to a failure of this program. Any code outside 1-2 would do; a named
 * one from a standard beats a number chosen here.
 */
const SCAN_REFUSED_EXIT = 78

/**
 * The exit code "this stage does not hold it" reports.
 *
 * `verify` fails for two reasons a shell has to tell apart: the registry
 * answered and the artifact is not there, or the registry could not be read at
 * all. A gate that reads both as absence — mbuild-release asks one before it
 * publishes a version — takes a denied read for a free slot and loses the
 * refusal it exists for: `publish` asks again, skips every artifact it finds,
 * and the run reports a publish of bytes it never wrote.
 *
 * 66 is `EX_NOINPUT` from `sysexits.h`, "an input did not exist", which is the
 * question `verify` answers.
 */
const NOT_PUBLISHED_EXIT = 66

const USAGE = [
  'usage: npm run mbuild publish -- --tag <commit-sha> --stage <stage> [--artifact <name>] [--version v<X.Y.Z>]',
  '       npm run mbuild promote -- --tag <commit-sha> --from <stage> --to <stage> [--artifact <name>] [--version v<X.Y.Z>]',
  '       npm run mbuild verify -- --tag <commit-sha> --stage <stage> [--artifact <name>] [--version v<X.Y.Z>]',
  '       npm run mbuild inspect -- --stage <stage>',
  '       npm run mbuild publish|verify -- --tag <sha> --ghcr <owner/repository> --version v<X.Y.Z>',
  '       npm run mbuild import-release -- --tag <sha> --ghcr <owner/repository> --stage <stage> --version v<X.Y.Z>',
  '',
  '--artifact narrows the command to one declared artifact. Absent means every',
  'one, which is what a deploy asks about.',
  '',
  '--version addresses the release build cut from that commit — tagged',
  '`v<X.Y.Z>-<commit-sha>` — rather than the commit build tagged `<commit-sha>`.',
  'They are different bytes at different addresses, and a stage that admits only',
  'released images reads the difference off the tag.',
].join('\n')

const option = (argv: string[], name: string): string | undefined => {
  const inline = argv.find((argument) => argument.startsWith(`--${name}=`))
  if (inline) return inline.slice(name.length + 3)
  const index = argv.indexOf(`--${name}`)
  return index >= 0 ? argv[index + 1] : undefined
}

const required = (argv: string[], name: string): string => {
  const value = option(argv, name)
  if (!value) throw new Error(`--${name} is required.\n${USAGE}`)
  return value
}

/**
 * What `--artifact` selects: one declared artifact, or every one.
 *
 * Absent leaves the whole set, which is what a deploy asks about — "does this
 * stage hold this commit" is a question about all of them. Named, it narrows
 * to that one, which is what lets a workflow give each artifact its own job.
 */
const narrowed = (config: BuildConfig, argv: string[], deployStage?: string): BuildConfig => {
  const artifact = option(argv, 'artifact')
  if (artifact !== undefined) return onlyArtifact(config, artifact)
  return deployStage ? deploymentArtifacts(config, deployStage) : config
}

/**
 * The tag a command addresses: the commit build, or the release build cut from
 * that commit at a version.
 *
 * `--version` rather than letting a caller pass `v1.2.3-<sha>` itself, for the
 * reason every other part of an address is composed in `mbuild/address`: a
 * caller that concatenates its own is a second place the convention lives, and
 * the first typo in it publishes bytes nothing will look for.
 */
const tagOf = (argv: string[]): string => {
  const sha = required(argv, 'tag')
  const version = option(argv, 'version')
  return version === undefined ? assertTag(sha) : releaseTagFor({ version, sha })
}

const accountId = async (): Promise<string> => {
  const identity = await run('aws', ['sts', 'get-caller-identity', '--query', 'Account', '--output', 'text'])
  if (identity.code !== 0) throw new Error(`Could not resolve the publishing account: ${identity.stderr.trim()}`)
  return identity.stdout.trim()
}

/** mstage declares where every stage lives; this reads that rather than a copy. */
const stageOf = (stage: string): StageConfig => {
  const stages = loadStageConfig().stages
  if (!Object.hasOwn(stages, stage)) {
    throw new Error(`mstage.config.json declares no stage "${stage}". Declared: ${Object.keys(stages).join(', ')}`)
  }
  return stages[stage]!
}

const regionOf = (stage: string): string => {
  const { region } = stageOf(stage)
  if (!region) throw new Error(`mstage.config.json gives stage "${stage}" no region`)
  return region
}

/**
 * What a stage publishes to, before anything has been federated.
 *
 * A caller that has to choose a cloud login cannot choose it until it knows
 * which cloud, and reading that from the config in shell would mean a second
 * parser for a file mbuild already owns. Deliberately identity-free: it names
 * the kind and the region, never the account or the project, because those are
 * exactly what the login it is choosing will establish.
 *
 * Printed as `key=value` lines, which is what a GitHub step reads into its
 * outputs without a transformation nobody would review.
 */
export const inspectStage = ({ config, stage, region }: { config: BuildConfig; stage: string; region: string }) => {
  const declared = registryFor(config, stage)
  return {
    kind: declared.kind,
    region,
    repository: declared.repository,
    artifacts: Object.keys(config.artifacts).join(','),
  }
}

/*
 * Progress goes where the echoed commands go, so the two stay in order: one
 * stream, read as it is written. stdout is left for what the run produced —
 * the `artifact=address` lines a caller can read.
 */
const log = (line: string): void => void process.stderr.write(`${line}\n`)

/** The bin's half of it: which stage, and where to ask for each half. */
const coordinates = (config: BuildConfig, stage: string): Promise<Coordinates> =>
  coordinatesOf({ stage, kind: registryFor(config, stage).kind, project: stageOf(stage).project, accountId })

const main = async (): Promise<number> => {
  const [command, ...argv] = process.argv.slice(2)
  const ghcr = option(argv, 'ghcr')
  const verifyForStage = command === 'verify' && argv.some((arg) => arg === '--stage' || arg.startsWith('--stage='))
  const config = ghcr !== undefined && command !== 'import-release' && !verifyForStage
    ? loadArtifactConfig() : loadBuildConfig()

  if (ghcr !== undefined) {
    if (!['publish', 'verify', 'import-release'].includes(command ?? '')) throw new Error('--ghcr requires publish, verify or import-release')
    if (!option(argv, 'version') || !/^[0-9a-f]{40}$/.test(required(argv, 'tag'))) throw new Error('--ghcr requires --version and a full commit SHA')
    const registry = ghcrRegistryFor(ghcr)
    const tag = tagOf(argv)
    if (command === 'import-release') {
      const stage = required(argv, 'stage')
      const selected = narrowed(config, argv, stage)
      const target = resolveRegistry({ config, stage, region: regionOf(stage), ...(await coordinates(config, stage)) })
      const pins = process.env.BOXLITE_RELEASE_DIGESTS
      const digests = pins ? releaseImageDigests(pins, tag) : undefined
      for (const outcome of await promote({ config: selected, tag, digests, from: { stage: 'ghcr', registry }, to: { stage, registry: target }, run, log })) {
        console.log(`${outcome.artifact}=${outcome.address}`)
      }
    } else {
      const stage = verifyForStage ? required(argv, 'stage') : undefined
      if (stage !== undefined) stageIn(config, stage)
      const options = { config: narrowed(config, argv, stage), stage: 'ghcr', registry, tag, run, log }
      const outcomes = command === 'publish'
        ? await publish({ ...options, replace: argv.includes('--replace') })
        : await verifyPublished(options)
      for (const outcome of outcomes) console.log(`${outcome.artifact}=${outcome.address}`)
      const output = option(argv, 'output')
      if (output && command === 'publish') await writeFile(output, JSON.stringify(outcomes) + '\n')
    }
    return 0
  }
  if (command === 'import-release') throw new Error('import-release requires --ghcr <owner/repository>')

  if (command === 'inspect') {
    const stage = required(argv, 'stage')
    for (const [key, value] of Object.entries(inspectStage({ config, stage, region: regionOf(stage) }))) {
      console.log(`${key}=${value}`)
    }
    return 0
  }

  if (command === 'publish') {
    const tag = tagOf(argv)
    const stage = required(argv, 'stage')
    const registry = resolveRegistry({
      config,
      stage,
      region: regionOf(stage),
      ...(await coordinates(config, stage)),
    })
    // The registry is a property of the stage, so it is resolved from the whole
    // config; only what gets built is narrowed.
    for (const outcome of await publish({ config: narrowed(config, argv), stage, registry, tag, run, log })) {
      console.log(`${outcome.artifact}=${outcome.address}`)
    }
    return 0
  }

  /*
   * Asked by a deploy before it applies anything. It prints the same
   * `artifact=address` lines a publish does, because a caller that wants to
   * know where the images are should not have to read a different shape
   * depending on whether this run put them there.
   */
  if (command === 'verify') {
    const tag = tagOf(argv)
    const stage = required(argv, 'stage')
    const registry = resolveRegistry({
      config,
      stage,
      region: regionOf(stage),
      ...(await coordinates(config, stage)),
    })
    for (const { artifact, address } of await verifyPublished({ config: narrowed(config, argv, stage), stage, registry, tag, run })) {
      console.log(`${artifact}=${address}`)
    }
    return 0
  }

  if (command === 'promote') {
    const tag = tagOf(argv)
    const fromStage = required(argv, 'from')
    const toStage = required(argv, 'to')
    assertPromotable({
      from: { stage: fromStage, kind: registryFor(config, fromStage).kind },
      to: { stage: toStage, kind: registryFor(config, toStage).kind },
    })
    // Resolved per stage, not once from the source. On Artifact Registry the
    // project is part of the address, and two stages may live in two projects —
    // reusing the source's would push the promoted image at the wrong one while
    // reporting the right name.
    const outcomes = await promote({
      config: narrowed(config, argv, toStage),
      tag,
      from: {
        stage: fromStage,
        registry: resolveRegistry({
          config,
          stage: fromStage,
          region: regionOf(fromStage),
          ...(await coordinates(config, fromStage)),
        }),
      },
      to: {
        stage: toStage,
        registry: resolveRegistry({
          config,
          stage: toStage,
          region: regionOf(toStage),
          ...(await coordinates(config, toStage)),
        }),
      },
      run,
      log,
    })
    for (const outcome of outcomes) console.log(`${outcome.artifact}=${outcome.address}`)
    return 0
  }

  console.error(command ? `Unknown command "${command}".\n${USAGE}` : USAGE)
  return 1
}

/** Everything a caller branches on. Every other failure is a plain 1. */
const exitCodeFor = (error: unknown): number => {
  if (error instanceof AuditFailedError) return AUDIT_FAILED_EXIT
  if (error instanceof ScanRefusedError) return SCAN_REFUSED_EXIT
  if (error instanceof NotPublishedError) return NOT_PUBLISHED_EXIT
  return 1
}

try {
  process.exitCode = await main()
} catch (error) {
  console.error(error instanceof Error ? error.message : String(error))
  process.exitCode = exitCodeFor(error)
}