Skip to content

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

3.8 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 BoxLite AI
import assert from 'node:assert/strict'
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { appendFileSync } from 'node:fs'
import { pathToFileURL } from 'node:url'
import { cacheKey, validUnit } from '../../../.github/actions/release-build-cache/record.mjs'

export function buildKey(tag, sha, run) {
  assert.match(tag, /^v\d+\.\d+\.\d+$/)
  assert.match(sha, /^[0-9a-f]{40}$/)
  assert.match(String(run), /^[1-9]\d*$/)
  return createHash('sha256').update([tag, sha, run].join('@')).digest('base64url')
}

const hash = /^[0-9a-f]{64}$/
export function planBuilds({ key, attempt, jobs }) {
  // A subsequent failure or explicit rebuild supersedes the earlier output, even if its cache survives.
  const latest = new Map()
  const executions = new Set()
  for (const job of [...jobs].sort((a, b) => a.run_attempt - b.run_attempt)) {
    if (job.run_attempt >= attempt || job.conclusion === 'skipped') continue
    // Partial reruns can copy the entire execution timeline into a later attempt with a new check ID.
    if (job.started_at && job.completed_at && Array.isArray(job.steps)) {
      const timeline = job.steps.map(step => [step.number, step.name, step.status, step.conclusion, step.started_at, step.completed_at])
      const execution = JSON.stringify([job.name, job.started_at, job.completed_at, job.conclusion, timeline])
      if (executions.has(execution)) continue
      executions.add(execution)
    }
    const saved = job.steps?.find(step => step.name.startsWith('Build cache receipt ') && step.conclusion === 'success')
    const reused = job.steps?.some(step => step.name === 'Save release build cache' && step.conclusion === 'skipped')
    if (job.conclusion === 'success' && !saved && reused) continue
    latest.set(job.name, { job, saved })
  }
  const sources = {}
  for (const { job, saved } of latest.values()) {
    if (job.conclusion !== 'success' || !saved) continue
    // The receipt digest comes from the original job's GitHub timeline, outside the mutable cache service.
    const source = saved.name.slice('Build cache receipt '.length)
    let record
    try {
      record = JSON.parse(source)
    } catch {
      continue
    }
    if (!record || record.scope !== key || !validUnit(record.unit)) continue
    const { unit, attempt: origin, check, receipt, manifest } = record
    if (job.run_attempt !== origin || typeof check !== 'string' || !/^[1-9]\d*$/.test(check) || check !== job.check_run_url?.split('/').pop()) continue
    if (typeof receipt !== 'string' || !hash.test(receipt)) continue
    if (unit.startsWith('ghcr-') ? typeof manifest !== 'string' || !hash.test(manifest) : manifest !== '') continue
    sources[unit] = { key: cacheKey(source), receipt, manifest }
  }
  return { key, attempt, sources }
}

function pages(path, field) {
  const data = execFileSync('gh', ['api', '--paginate', '--slurp', 'repos/' + process.env.GITHUB_REPOSITORY + '/actions/' + path],
    { encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 })
  return JSON.parse(data).flatMap(page => page[field])
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const { TAG, SHA, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT, GITHUB_OUTPUT } = process.env
  const attempt = Number(GITHUB_RUN_ATTEMPT)
  assert.ok(Number.isSafeInteger(attempt) && attempt > 0)
  const key = buildKey(TAG, SHA, GITHUB_RUN_ID)
  let sources = {}
  if (attempt > 1) {
    try {
      const jobs = pages('runs/' + GITHUB_RUN_ID + '/jobs?filter=all&per_page=100', 'jobs')
      sources = planBuilds({ key, attempt, jobs }).sources
    } catch (error) {
      console.warn('Build cache lookup unavailable; rebuilding: ' + error.message)
    }
  }
  appendFileSync(GITHUB_OUTPUT, 'plan=' + JSON.stringify({ key, attempt, sources }) + '\n')
}