Files
fleet/scripts/ci/package-rollout-gate.mjs
CatoandClaude b4d818bd48 fix(rollout-gate): measure a canary at the commit it has live, not its branch tip (#529)
The gate asks whether a canary runs a package version and passed its checks.
It measured the canary's branch tip and required that exact commit to be
deployed. OrangeCat's live receipt names its workspace packages by commit
tarball, so it matched only while the tip itself was live; its main moves
every few minutes against a fifteen-minute deploy, so the window rarely
opened, and anything canaried there (paykit, writingkit) was held: paykit
0.3.0 held bitbaum/loki#1652 through every sweep of 2026-11-12/13 while
OrangeCat ran it.

deployedCanaryCommit picks the commit of the newest successful deploy run;
the receipt must still match it (commit, lockfile hash, artifacts) and its
checks must be green. With no successful deploy on record the tip is
measured, as before. The four copies of the canary read are one function.

Run against bitbaum/loki#1652 on live data: before, exit 1 (receipt does
not match); after, exit 0.


Claude-Session: https://claude.ai/code/session_019MDtmtUQb9BM11ycpApwGq

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-13 06:57:37 +01:00

955 lines
35 KiB
JavaScript

import { createHash } from "node:crypto";
import { receiptMatches, workspaceSourceArtifact, workspaceSourcePath } from "./release-receipt-contract.mjs";
import { everyRunForSha, runsForShaPath } from "./runs-for-sha.mjs";
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { resolve } from "node:path";
const policy = JSON.parse(
readFileSync(
new URL("../../registers/package-rollouts.json", import.meta.url),
"utf8",
),
);
const registry = JSON.parse(
readFileSync(
new URL("../../registers/packages.json", import.meta.url),
"utf8",
),
);
const known = new Set(registry.packages.map((p) => p.name));
export function dependencyIdentity(name, spec) {
if (typeof spec === "string" && spec.startsWith("npm:")) {
const target = spec.slice(4),
split = target.lastIndexOf("@");
if (split > target.indexOf("/")) return target.slice(0, split);
}
if (typeof spec === "string") {
const git =
/^(?:github:|git\+https:\/\/github\.com\/)([\w.-]+\/[\w.-]+?)(?:\.git)?#/.exec(
spec,
);
if (git)
return (
registry.packages.find(
(entry) => entry.repo === `https://github.com/${git[1]}`,
)?.name ?? name
);
}
return name;
}
/**
* The one definition of a first-party package. The release receipt
* (release-receipt.mjs) attests exactly these, and this gate expects exactly
* these: when the two lists differed (limitkit and bip-kit are rollout
* packages but not in packages.json), every canary that used them carried a
* receipt the gate could never match, and every floor raise held.
*/
export const isSharedPackage = (name) =>
known.has(name) || name.startsWith("@bitbaum/") || Boolean(policy.packages[name]);
const shared = isSharedPackage;
export const isLocalPathSpec = (spec) =>
typeof spec === "string" && /^(?:file|link):/.test(spec);
export function lockedDependencies(manifest, lock, importer = ".") {
const deps = {
...manifest.dependencies,
...manifest.devDependencies,
...manifest.optionalDependencies,
};
const result = {};
// Callers select the importer explicitly; peer contexts do not change artifact identity.
const importers =
lock.match(/^importers:[^\n]*\n([\s\S]*?)(?=^\S|(?![\s\S]))/m)?.[1] ?? "";
const escapedImporter = importer.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const root =
importers.match(
new RegExp(
`^ (?:${escapedImporter}|["']${escapedImporter}["']):[^\\n]*\\n([\\s\\S]*?)(?=^ \\S|^\\S|(?![\\s\\S]))`,
"m",
),
)?.[1] ?? "";
for (const [name, spec] of Object.entries(deps)) {
// A path into this repo (an example installing the package it sits in,
// `file:../..`) is local source, not a published artifact: there is
// nothing to canary, and gating it held a package's own rename PR.
if (isLocalPathSpec(spec)) continue;
const identity = dependencyIdentity(name, spec);
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const version = root.match(
new RegExp(
`^ ['"]?${escaped}['"]?:\\s*\\n\\s+specifier:.*\\n\\s+version: (.+)$`,
"m",
),
)?.[1];
if (!version && shared(identity))
throw new Error(`Missing locked artifact for ${name}`);
let artifact = version?.replace(/^['"]|['"]$/g, "").split("(")[0] ?? spec;
// pnpm prefixes aliased npm AND Git resolutions with the target identity.
if (artifact.startsWith(`${identity}@`))
artifact = artifact.slice(identity.length + 1);
if (result[identity] && result[identity] !== artifact && shared(identity))
throw new Error(`Conflicting locked artifacts for ${identity}`);
result[identity] = artifact;
}
return result;
}
export function lockedNpmDependencies(manifest, lock, importer = ".") {
const deps = {
...manifest.dependencies,
...manifest.devDependencies,
...manifest.optionalDependencies,
};
if (![2, 3].includes(lock.lockfileVersion) || !lock.packages)
throw new Error("Unsupported npm lockfile: artifact evidence is missing");
const prefix = importer === "." ? "" : importer.replace(/\/$/, "") + "/";
const result = {};
for (const [name, spec] of Object.entries(deps)) {
if (isLocalPathSpec(spec)) continue;
const identity = dependencyIdentity(name, spec);
const entry =
lock.packages[`${prefix}node_modules/${name}`] ??
lock.packages[`node_modules/${name}`];
const artifact =
entry?.resolved && /git|codeload/.test(entry.resolved)
? entry.resolved
: entry?.version;
if (!artifact && shared(identity))
throw new Error(`Missing locked artifact for ${name}`);
if (result[identity] && result[identity] !== artifact && shared(identity))
throw new Error(`Conflicting locked artifacts for ${identity}`);
result[identity] = artifact ?? "unresolved";
}
return result;
}
export function nestedSharedArtifacts(lock) {
const section =
lock.match(/^importers:[^\n]*\n([\s\S]*?)(?=^\S|(?![\s\S]))/m)?.[1] ?? "";
const entries = [];
for (const importer of section.matchAll(
/^ (.+):[^\n]*\n([\s\S]*?)(?=^ \S|^\S|(?![\s\S]))/gm,
)) {
if (importer[1].replace(/['"]/g, "") === ".") continue;
for (const dependency of importer[2].matchAll(
/^ ['"]?([^'"\n]+?)['"]?:\s*\n\s+specifier:.*\n\s+version: (.+)$/gm,
)) {
const name = dependency[1];
if (
known.has(name) ||
name.startsWith("@bitbaum/") ||
policy.packages[name]
)
entries.push([
importer[1],
name,
dependency[2].replace(/^['"]|['"]$/g, "").split("(")[0],
]);
}
}
return entries.sort((a, b) =>
JSON.stringify(a).localeCompare(JSON.stringify(b)),
);
}
export function nestedSharedUpdates(beforeLock, afterLock) {
const before = new Map(
nestedSharedArtifacts(beforeLock).map(([importer, name, version]) => [
`${importer}\0${name}`,
version,
]),
);
return nestedSharedArtifacts(afterLock).filter(
([importer, name, version]) => before.get(`${importer}\0${name}`) !== version,
);
}
export function nestedSharedChange(files, readManifest) {
const sharedSpecs = (manifest) =>
Object.fromEntries(
Object.entries({
...manifest?.dependencies,
...manifest?.devDependencies,
})
.map(([name, spec]) => [dependencyIdentity(name, spec), spec])
.filter(([name]) => shared(name))
.sort(([a], [b]) => a.localeCompare(b)),
);
for (const { filename } of files) {
if (!filename.includes("/")) continue;
const isManifest = filename.endsWith("/package.json");
const isLock = /\/(?:pnpm-lock\.yaml|package-lock\.json|yarn\.lock)$/.test(
filename,
);
if (!isManifest && !isLock) continue;
const path = isManifest
? filename
: filename.slice(0, filename.lastIndexOf("/")) + "/package.json";
const beforeManifest = readManifest(path, "base");
const afterManifest = readManifest(path, "head");
// A deleted workspace package is retired, not a nested consumer whose
// shared dependency update needs importer-specific rollout evidence.
if (!afterManifest) continue;
const before = sharedSpecs(beforeManifest),
after = sharedSpecs(afterManifest);
if (isLock && Object.keys(after).length)
return true;
if (isManifest && JSON.stringify(before) !== JSON.stringify(after))
return true;
}
return false;
}
export async function assessRollout({
repo,
before,
after,
readCanary,
candidateChecks,
candidateSourceChanged = false,
candidatePullRequest,
requiredChecks = ["ci.yml", "browser-smoke.yml"],
settings = policy,
now = Date.now(),
}) {
const findings = [];
for (const [name, version] of Object.entries(after)) {
if (
before[name] === version ||
!(
known.has(name) ||
name.startsWith("@bitbaum/") ||
settings.packages?.[name]
)
)
continue;
if (settings.blocked?.[name]?.includes(version)) {
findings.push(`${name}@${version}: release is blocked`);
continue;
}
const config = settings.packages?.[name];
if (!config) {
findings.push(
`${name}: no designated canary; configure one before automatic promotion`,
);
continue;
}
const canaries = [config, ...(config.additionalCanaries ?? [])];
const candidateConfig = canaries.find((entry) => entry.canary === repo) ?? config;
const candidateRequired = settings.consumerChecks?.[repo] ?? (candidateSourceChanged
? (candidateConfig.candidateChecks ?? requiredChecks)
: (candidateConfig.candidateDependencyChecks ?? candidateConfig.candidateChecks ?? requiredChecks));
if (!candidateRequired.every((check) => candidateChecks.includes(check))) {
findings.push(
`${name}: consumer needs successful ${candidateRequired.join(" and ")} workflows on this commit`,
);
continue;
}
if (canaries.some((entry) => entry.canary === repo)) {
if (
Number.isInteger(candidatePullRequest) && candidatePullRequest > 0 &&
(candidateConfig.canaryAdmission === "verified-candidate" ||
candidateConfig.bootstrapPr === candidatePullRequest)
)
continue;
findings.push(
candidateConfig.canaryAdmission === "verified-candidate"
? `${name}: canary consumer needs a real candidate pull request`
: `${name}: canary consumer must use its configured bootstrap PR${candidateConfig.bootstrapPr ? ` #${candidateConfig.bootstrapPr}` : ""}`,
);
continue;
}
// Every integration class must qualify before downstream promotion.
for (const representative of canaries) {
const canary = await readCanary(representative.canary, representative, name);
if (
!canary ||
canary.dependencies[name] !== version ||
!canary.healthy ||
!(representative.canaryChecks ?? ["ci.yml", "browser-smoke.yml"]).every((check) =>
canary.checks?.includes(check),
) ||
now - Date.parse(canary.deployedAt) < settings.soakHours * 3600000 ||
!Number.isFinite(Date.parse(canary.deployedAt))
) {
findings.push(
`${name}@${version}: wait for ${representative.canary} to deploy this artifact${settings.soakHours ? ", pass CI/browser checks and soak for " + settings.soakHours + "h" : " and pass CI/browser checks"}`,
);
}
}
}
return findings;
}
export function hasConsumerSourceChanges(files, prefix = "") {
const normalizedPrefix = prefix ? `${prefix.replace(/\/$/, "")}/` : "";
return files.some(({ filename }) => {
if (normalizedPrefix && !filename.startsWith(normalizedPrefix)) return false;
const relative = normalizedPrefix
? filename.slice(normalizedPrefix.length)
: filename;
if (!relative) return false;
if (
/(^|\/)(?:package\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|package-lock\.json|npm-shrinkwrap\.json|package-plan\.json)$/.test(relative) ||
relative.startsWith(".github/workflows/") ||
relative.startsWith("docs/") ||
/(?:^|\/)README(?:\.[^/]*)?$/i.test(relative) ||
/\.mdx?$/i.test(relative)
)
return false;
return true;
});
}
// A pnpm lockfile is several MB in the bigger apps. execFileSync's default
// 1 MB buffer then dies with ENOBUFS, and the contents API's JSON form leaves
// `content` empty above 1 MB, so either way the gate saw "evidence
// unavailable" and held every green floor-raise PR in those apps for days.
const GH_MAX_BUFFER = 256 * 1024 * 1024;
function gh(args) {
return execFileSync("gh", args, {
encoding: "utf8",
maxBuffer: GH_MAX_BUFFER,
stdio: ["ignore", "pipe", "pipe"],
});
}
function api(path) {
return JSON.parse(gh(["api", path]));
}
function content(repo, path, ref) {
try {
return gh([
"api",
`repos/${repo}/contents/${path}?ref=${encodeURIComponent(ref)}`,
"-H",
"Accept: application/vnd.github.raw",
]);
} catch (error) {
if (String(error.stderr).includes("404")) return null;
throw error;
}
}
function depsAt(repo, ref) {
const manifest = content(repo, "package.json", ref);
if (!manifest) return {};
const parsed = JSON.parse(manifest);
const dependencies = {
...parsed.dependencies,
...parsed.devDependencies,
...parsed.optionalDependencies,
};
const names = Object.keys(dependencies);
if (!names.some((n) => shared(dependencyIdentity(n, dependencies[n]))))
return {};
const lock = content(repo, "pnpm-lock.yaml", ref);
if (lock) return lockedDependencies(parsed, lock);
const npm = content(repo, "package-lock.json", ref);
if (npm) return lockedNpmDependencies(parsed, JSON.parse(npm));
throw new Error(
`${repo}: supported lockfile required for artifact-specific rollout evidence`,
);
}
function workspaceDepsAt(repo, ref, importer) {
const rawManifest = content(repo, `${importer}/package.json`, ref);
if (!rawManifest) return {};
const parsed = JSON.parse(rawManifest);
const dependencies = {
...parsed.dependencies,
...parsed.devDependencies,
...parsed.optionalDependencies,
};
if (
!Object.entries(dependencies).some(([name, spec]) =>
shared(dependencyIdentity(name, spec)),
)
)
return {};
const lock = content(repo, "pnpm-lock.yaml", ref);
if (lock) return lockedDependencies(parsed, lock, importer);
const npm = content(repo, "package-lock.json", ref);
if (npm) return lockedNpmDependencies(parsed, JSON.parse(npm), importer);
throw new Error(
`${repo}/${importer}: supported lockfile required for artifact-specific rollout evidence`,
);
}
function standaloneDepsAt(repo, ref, project) {
const rawManifest = content(repo, `${project}/package.json`, ref);
if (!rawManifest) return {};
const parsed = JSON.parse(rawManifest);
const lock =
content(repo, `${project}/pnpm-lock.yaml`, ref) ??
content(repo, `${project}/package-lock.json`, ref);
if (!lock) {
const dependencies = {
...parsed.dependencies,
...parsed.devDependencies,
...parsed.optionalDependencies,
};
if (
Object.entries(dependencies).some(([name, spec]) =>
shared(dependencyIdentity(name, spec)),
)
)
throw new Error(
`${repo}/${project}: standalone shared dependencies require a committed lockfile`,
);
return {};
}
if (content(repo, `${project}/pnpm-lock.yaml`, ref))
return lockedDependencies(parsed, lock);
return lockedNpmDependencies(parsed, JSON.parse(lock));
}
function rootHasImporter(lock, importer) {
const section =
lock.match(/^importers:[^\n]*\n([\s\S]*?)(?=^\S|(?![\s\S]))/m)?.[1] ?? "";
const escaped = importer.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return new RegExp(`^ (?:${escaped}|['"]${escaped}['"]):`, "m").test(section);
}
function canaryDepsAt(repo, ref, config) {
const importer = config.canaryImporter;
if (!importer) return depsAt(repo, ref);
if (
typeof importer !== "string" ||
importer.startsWith("/") ||
importer.split("/").some((part) => !part || part === "." || part === "..") ||
importer.includes("\\")
)
throw new Error(`${repo}: invalid canary importer path`);
return workspaceDepsAt(repo, ref, importer);
}
function receiptDepsAt(repo, ref, config) {
const projects = config.receiptProjects ?? [
config.receiptProject ?? config.canaryImporter ?? ".",
];
if (!Array.isArray(projects) || projects.length === 0)
throw new Error(`${repo}: invalid receipt projects`);
return Object.assign(
{},
...projects.map((project) => {
const deps =
project === "."
? depsAt(repo, ref)
: workspaceDepsAt(repo, ref, project);
const manifest = JSON.parse(
content(
repo,
project === "." ? "package.json" : `${project}/package.json`,
ref,
),
);
const specs = {
...manifest.dependencies,
...manifest.devDependencies,
...manifest.optionalDependencies,
};
for (const [name, artifact] of Object.entries(deps)) {
if (!shared(name) || !artifact.startsWith("link:")) continue;
const spec = Object.entries(specs).find(
([key, value]) => dependencyIdentity(key, value) === name,
)?.[1];
if (typeof spec !== "string" || !spec.startsWith("workspace:"))
throw new Error(
`${name}: workspace source requires a workspace dependency`,
);
const link = artifact.slice(5),
path = workspaceSourcePath(project, link);
const local = JSON.parse(
content(repo, `${path}/package.json`, ref),
);
deps[name] = workspaceSourceArtifact({
repo,
commit: ref,
importer: project,
link,
name,
local: { ...local, path },
});
}
return deps;
}),
);
}
export function successfulWorkflows(runs) {
const seen = new Set(),
passed = [];
for (const run of runs) {
if (!["push", "pull_request", "workflow_dispatch"].includes(run.event))
continue;
const path = run.path?.split("/").at(-1);
if (seen.has(path)) continue;
seen.add(path);
if (run.conclusion === "success") passed.push(path);
}
return passed;
}
/** A named browser job can certify an existing combined CI workflow. */
export function successfulConsumerChecks(runs, requirements, sha, readJobs) {
const exactRuns = runs.filter((run) => run.head_sha === sha);
const passed = successfulWorkflows(exactRuns);
const jobsByRun = new Map();
for (const requirement of requirements) {
const separator = requirement.indexOf("#");
if (separator < 0) continue;
const workflow = requirement.slice(0, separator);
const jobName = requirement.slice(separator + 1);
if (!workflow || !jobName)
throw new Error("Invalid named consumer job requirement");
if (!passed.includes(workflow)) continue;
const run = exactRuns.find(
(run) =>
["push", "pull_request", "workflow_dispatch"].includes(run.event) &&
run.path?.split("/").at(-1) === workflow,
);
if (!run || run.status !== "completed" || run.conclusion !== "success")
continue;
if (!jobsByRun.has(run.id)) jobsByRun.set(run.id, readJobs(run));
const matches = jobsByRun.get(run.id).filter((job) => job.name === jobName);
if (
matches.length &&
matches.every(
(job) => job.status === "completed" && job.conclusion === "success",
)
)
passed.push(requirement);
}
return passed;
}
function greenWorkflows(repo, sha) {
// Every page: a long-lived tip buries its own CI under sweep dispatches.
const runs = everyRunForSha((page) => api(runsForShaPath(repo, sha, page)));
return successfulConsumerChecks(
runs,
policy.consumerChecks?.[repo] ?? [],
sha,
(run) => {
const response = api(
`repos/${repo}/actions/runs/${run.id}/jobs?filter=latest&per_page=100`,
);
if (
!Array.isArray(response.jobs) ||
response.total_count > response.jobs.length
)
throw new Error(`${repo}: incomplete consumer job evidence`);
return response.jobs;
},
);
}
/**
* Files a canary's own CI skips by `paths-ignore` (docs, Markdown, LICENSE).
* A commit that changes only these cannot change what was built, tested or
* deployed, so it does not erase the evidence of the commit before it.
*/
export function isDocsOnlyChange(files) {
return (
Array.isArray(files) &&
files.length > 0 &&
files.every(({ filename }) =>
/\.mdx?$/i.test(filename) ||
filename.startsWith("docs/") ||
/(?:^|\/)(?:LICENSE|CHANGELOG|README)(?:\.[^/]*)?$/i.test(filename) ||
filename.startsWith(".vscode/"),
)
);
}
/**
* Green checks for a canary tip. When the tip is a docs-only commit, its CI
* never ran (paths-ignore), and reading checks off the tip alone held every
* downstream consumer of every package canaried there until some unrelated
* code change landed: kivvi's tip on 2026-11-06 was an AGENTS.md sync, and
* the gate held the whole fleet's chatkit 0.23.0 floor raise for four days.
* Walk back (at most `limit` commits) through docs-only commits only, and take
* a missing check from the nearest ancestor where it is green.
*/
export function canaryChecksWithDocsOnlyAncestors({
tip,
requiredChecks,
checksAt,
history,
filesBetween,
limit = 10,
}) {
const checks = new Set(checksAt(tip));
let missing = requiredChecks.filter((check) => !checks.has(check));
if (!missing.length) return [...checks];
const ancestors = (typeof history === "function" ? history() : history)
.filter((sha) => sha !== tip)
.slice(0, limit);
let newer = tip;
for (const sha of ancestors) {
if (!isDocsOnlyChange(filesBetween(sha, newer))) break;
const green = checksAt(sha);
for (const check of missing) if (green.includes(check)) checks.add(check);
missing = missing.filter((check) => !checks.has(check));
if (!missing.length) break;
newer = sha;
}
return [...checks];
}
function canaryTipChecks(canary, tip, requiredChecks) {
return canaryChecksWithDocsOnlyAncestors({
tip,
requiredChecks,
checksAt: (sha) => greenWorkflows(canary, sha),
history: () =>
api(`repos/${canary}/commits?sha=${tip}&per_page=11`).map(
(commit) => commit.sha,
),
filesBetween: (older, newer) =>
api(`repos/${canary}/compare/${older}...${newer}`).files ?? [],
});
}
/** Evidence is specific to the importer and receipt projects. */
export function canaryEvidenceKey(canary, config, requiredChecks) {
return JSON.stringify([canary, config.canaryImporter ?? null, config.receiptProject ?? null,
config.receiptProjects ?? null, requiredChecks]);
}
/** Shared by root and starter consumers: a green deploy cannot override a stale receipt. */
export async function canaryDeploymentEvidence({
canary,
tip,
dependencies,
deploy,
checks,
requiredChecks = ["ci.yml", "browser-smoke.yml"],
receiptUrl,
receiptProject = ".",
receiptProjects,
receiptDependencies = dependencies,
lock,
fetchImpl = fetch,
}) {
let receiptHealthy = true;
if (receiptUrl) {
const url = new URL(receiptUrl);
if (url.protocol !== "https:")
throw new Error("Deployment receipts require HTTPS");
url.searchParams.set("commit", tip);
const response = await fetchImpl(url, {
cache: "no-store",
signal: AbortSignal.timeout(10_000),
});
if (!response.ok)
throw new Error(
`${canary}: deployment receipt returned HTTP ${response.status}`,
);
const receipt = await response.json();
if (!lock) throw new Error(`${canary}: receipt lockfile is unavailable`);
receiptHealthy = receiptMatches(receipt, {
repo: canary,
commit: tip,
artifacts: Object.fromEntries(
Object.entries(receiptDependencies).filter(([name]) => shared(name)),
),
lockSha256: createHash("sha256").update(lock).digest("hex"),
project: receiptProject,
projects: receiptProjects,
});
if (!receiptHealthy)
console.error(
`${canary}: live receipt does not match the current commit and locked artifacts`,
);
}
return {
dependencies,
healthy:
receiptHealthy &&
deploy?.conclusion === "success" &&
deploy.head_sha === tip &&
requiredChecks.every((check) => checks.includes(check)),
checks,
deployedAt: deploy?.updated_at,
};
}
/**
* The canary commit the gate measures: the one its last successful deploy put
* live, not the branch tip. The question is "does the canary RUN this artifact
* and did that commit pass its checks"; the live receipt answers it for the
* deployed commit, and still has to match it. Measuring the tip held every
* consumer of a busy canary: OrangeCat's receipt names its workspace packages
* by commit tarball, so it matched only while the tip itself was live, and its
* main moves every few minutes against a fifteen-minute deploy (2026-11-13:
* paykit 0.3.0 held bitbaum/loki#1652 through every sweep of the night while
* OrangeCat ran it). With no successful deploy on record, the tip is measured.
*/
export function deployedCanaryCommit({ tip, deploys }) {
const live = (deploys ?? []).find(
(run) =>
run?.status === "completed" &&
run?.conclusion === "success" &&
/^[0-9a-f]{40}$/.test(run?.head_sha ?? ""),
);
return live
? { commit: live.head_sha, deploy: live }
: { commit: tip, deploy: deploys?.[0] };
}
async function readCanaryEvidence(canary, config, requiredChecks) {
const branch = api(`repos/${canary}`).default_branch;
const tip = api(`repos/${canary}/commits/${branch}`).sha;
const { commit, deploy } = deployedCanaryCommit({
tip,
deploys: api(
`repos/${canary}/actions/workflows/${encodeURIComponent(policy.deploymentWorkflows?.[canary] ?? "deploy.yml")}/runs?branch=${branch}&per_page=10`,
).workflow_runs,
});
return canaryDeploymentEvidence({
canary,
tip: commit,
dependencies: canaryDepsAt(canary, commit, config),
receiptDependencies: receiptDepsAt(canary, commit, config),
receiptProject: config.receiptProject ?? ".",
receiptProjects: config.receiptProjects,
deploy,
checks: canaryTipChecks(canary, commit, requiredChecks),
requiredChecks,
receiptUrl: policy.deploymentReceipts?.[canary],
lock:
content(canary, "pnpm-lock.yaml", commit) ??
content(canary, "package-lock.json", commit),
});
}
/**
* The commit the pull request's own change is measured from. `pr.base.sha` is
* the base branch as GitHub last recorded it, not where the branch forked: a
* branch that predates a dependency bump on the base would read as reverting
* it, and the gate would hold a PR that never touches a manifest. The merge
* base is the parent of exactly the diff a squash merge lands.
*/
export function pullRequestBaseline(pr, readCompare) {
const compare = readCompare(pr.base.sha, pr.head.sha);
const sha = compare?.merge_base_commit?.sha;
if (!/^[0-9a-f]{40}$/.test(sha ?? ""))
throw new Error("merge base of the pull request is unavailable");
return sha;
}
async function main() {
const [repo, number] = process.argv.slice(2);
const pullRequest = api(`repos/${repo}/pulls/${number}`);
const pr = {
...pullRequest,
base: {
...pullRequest.base,
sha: pullRequestBaseline(pullRequest, (base, head) =>
api(`repos/${repo}/compare/${base}...${head}?per_page=1`),
),
},
};
// Avoid requiring a Node lockfile from repositories with no root Node manifest.
const manifest = content(repo, "package.json", pr.head.sha);
// Package repositories publish artifacts; their downstream application consumers
// provide the deployment/canary evidence. Do not require a library to deploy a site.
if (manifest && known.has(JSON.parse(manifest).name)) return;
const files = [];
for (let page = 1; page <= 30; page++) {
const batch = api(
`repos/${repo}/pulls/${number}/files?per_page=100&page=${page}`,
);
files.push(...batch);
if (batch.length < 100) break;
if (page === 30)
throw new Error("Dependency scope exceeds the API file limit");
}
// The app starter is a supported consumer in its own right. Its CI runs a
// clean install, package verification, production build and auth journey.
// Keep all other nested consumers held until they have equivalent evidence.
const templateFiles = files.filter(({ filename }) =>
/^templates\/app\/(?:package\.json|pnpm-lock\.yaml)$/.test(filename),
);
if (templateFiles.length) {
const templateDeps = (sha) => {
const rawManifest = content(repo, "templates/app/package.json", sha);
if (!rawManifest) return {};
const templateManifest = JSON.parse(rawManifest);
const lock = content(repo, "templates/app/pnpm-lock.yaml", sha);
if (!lock)
throw new Error("templates/app requires a committed pnpm lockfile");
return lockedDependencies(templateManifest, lock);
};
const beforeTemplate = templateDeps(pr.base.sha);
const afterTemplate = templateDeps(pr.head.sha);
const changed = Object.keys(afterTemplate).some(
(name) =>
beforeTemplate[name] !== afterTemplate[name] &&
(known.has(name) ||
name.startsWith("@bitbaum/") ||
policy.packages[name]),
);
if (changed) {
const cache = new Map();
const findings = await assessRollout({
repo,
before: beforeTemplate,
after: afterTemplate,
candidateChecks: greenWorkflows(repo, pr.head.sha),
candidateSourceChanged: hasConsumerSourceChanges(files, "templates/app"),
candidatePullRequest: Number(number),
requiredChecks: ["ci.yml"],
readCanary: async (canary, config) => {
const requiredChecks = config.canaryChecks ?? ["ci.yml", "browser-smoke.yml"];
const cacheKey = canaryEvidenceKey(canary, config, requiredChecks);
if (cache.has(cacheKey)) return cache.get(cacheKey);
const result = await readCanaryEvidence(canary, config, requiredChecks);
cache.set(cacheKey, result);
return result;
},
});
if (findings.length) {
console.log(findings.join("\n"));
process.exitCode = 1;
}
}
}
if (!manifest) return;
// Workspace artifacts cannot silently escape the root-consumer gate.
const baseLock = content(repo, "pnpm-lock.yaml", pr.base.sha) ?? "";
const headLock = content(repo, "pnpm-lock.yaml", pr.head.sha) ?? "";
const rootImporters = new Set(
nestedSharedUpdates(baseLock, headLock).map(([importer]) => importer),
);
const standaloneProjects = new Set();
const canaryCache = new Map();
for (const { filename } of files) {
if (filename.startsWith("templates/app/")) continue;
const isManifest = filename.endsWith("/package.json");
const isLock = /\/(?:pnpm-lock\.yaml|package-lock\.json)$/.test(filename);
if (!isManifest && !isLock) continue;
const project = filename.slice(0, filename.lastIndexOf("/"));
if (!project) continue;
if (
content(repo, `${project}/pnpm-lock.yaml`, pr.base.sha) ||
content(repo, `${project}/package-lock.json`, pr.base.sha) ||
content(repo, `${project}/pnpm-lock.yaml`, pr.head.sha) ||
content(repo, `${project}/package-lock.json`, pr.head.sha)
) {
standaloneProjects.add(project);
} else if (
rootHasImporter(baseLock, project) ||
rootHasImporter(headLock, project)
) {
rootImporters.add(project);
} else if (isManifest) {
const beforeRaw = content(repo, filename, pr.base.sha);
const afterRaw = content(repo, filename, pr.head.sha);
const sharedEntries = (raw) => {
if (!raw) return [];
const parsed = JSON.parse(raw);
return Object.entries({
...parsed.dependencies,
...parsed.devDependencies,
...parsed.optionalDependencies,
}).filter(([name, spec]) => shared(dependencyIdentity(name, spec)));
};
if (
JSON.stringify(sharedEntries(beforeRaw)) !==
JSON.stringify(sharedEntries(afterRaw))
)
throw new Error(
`${project}: nested shared dependency update has no importer-specific lock evidence; automatic promotion is held`,
);
}
}
for (const importer of rootImporters) {
if (!content(repo, `${importer}/package.json`, pr.head.sha))
throw new Error(
`${importer}: nested shared lock update has no matching manifest; automatic promotion is held`,
);
const beforeNested = workspaceDepsAt(repo, pr.base.sha, importer);
const afterNested = workspaceDepsAt(repo, pr.head.sha, importer);
const changedNested = Object.keys(afterNested).some(
(name) =>
beforeNested[name] !== afterNested[name] &&
(known.has(name) || name.startsWith("@bitbaum/") || policy.packages[name]),
);
if (!changedNested) continue;
const findings = await assessRollout({
repo,
before: beforeNested,
after: afterNested,
candidateChecks: greenWorkflows(repo, pr.head.sha),
candidateSourceChanged: hasConsumerSourceChanges(files, importer),
candidatePullRequest: Number(number),
requiredChecks: ["ci.yml"],
readCanary: async (canary, config) => {
const requiredChecks = config.canaryChecks ?? ["ci.yml", "browser-smoke.yml"];
const cacheKey = canaryEvidenceKey(canary, config, requiredChecks);
if (canaryCache.has(cacheKey)) return canaryCache.get(cacheKey);
const result = await readCanaryEvidence(canary, config, requiredChecks);
canaryCache.set(cacheKey, result);
return result;
},
});
if (findings.length) {
console.log(findings.join("\n"));
process.exitCode = 1;
}
}
for (const project of standaloneProjects) {
const beforeNested = standaloneDepsAt(repo, pr.base.sha, project);
const afterNested = standaloneDepsAt(repo, pr.head.sha, project);
const changedNested = Object.keys(afterNested).some(
(name) =>
beforeNested[name] !== afterNested[name] &&
(known.has(name) || name.startsWith("@bitbaum/") || policy.packages[name]),
);
if (!changedNested) continue;
const findings = await assessRollout({
repo,
before: beforeNested,
after: afterNested,
candidateChecks: greenWorkflows(repo, pr.head.sha),
candidateSourceChanged: hasConsumerSourceChanges(files, project),
candidatePullRequest: Number(number),
requiredChecks: ["ci.yml"],
readCanary: async (canary, config) => {
const requiredChecks = config.canaryChecks ?? ["ci.yml", "browser-smoke.yml"];
const cacheKey = canaryEvidenceKey(canary, config, requiredChecks);
if (canaryCache.has(cacheKey)) return canaryCache.get(cacheKey);
const result = await readCanaryEvidence(canary, config, requiredChecks);
canaryCache.set(cacheKey, result);
return result;
},
});
if (findings.length) {
console.log(findings.join("\n"));
process.exitCode = 1;
}
}
const before = depsAt(repo, pr.base.sha),
after = depsAt(repo, pr.head.sha);
const changed = Object.keys(after).some(
(n) =>
before[n] !== after[n] &&
(known.has(n) || n.startsWith("@bitbaum/") || policy.packages[n]),
);
if (!changed) return;
const cache = new Map();
const findings = await assessRollout({
repo,
before,
after,
candidateChecks: greenWorkflows(repo, pr.head.sha),
candidateSourceChanged: hasConsumerSourceChanges(files),
candidatePullRequest: Number(number),
readCanary: async (canary, config) => {
const requiredChecks = config.canaryChecks ?? ["ci.yml", "browser-smoke.yml"];
const cacheKey = canaryEvidenceKey(canary, config, requiredChecks);
if (cache.has(cacheKey)) return cache.get(cacheKey);
const result = await readCanaryEvidence(canary, config, requiredChecks);
cache.set(cacheKey, result);
return result;
},
});
if (findings.length) {
console.log(findings.join("\n"));
process.exitCode = 1;
}
}
if (
process.argv[1] &&
resolve(process.argv[1]) === fileURLToPath(import.meta.url)
)
main().catch((error) => {
console.error(`Rollout evidence unavailable: ${error.message}`);
process.exitCode = 2;
});