From 6212575888375ced26dc8b164d6fa8c65303d43e Mon Sep 17 00:00:00 2001 From: Postil Maintainer Date: Sun, 18 Oct 2026 17:15:27 +0000 Subject: [PATCH] Add read-only calibration bootstrap verification --- .github/workflows/bench-live.yml | 64 +++++++- bench/src/verify-calibration.test.ts | 220 +++++++++++++++++++++++++++ bench/src/verify-calibration.ts | 144 ++++++++++++++++++ 3 files changed, 424 insertions(+), 4 deletions(-) create mode 100644 bench/src/verify-calibration.test.ts create mode 100644 bench/src/verify-calibration.ts diff --git a/.github/workflows/bench-live.yml b/.github/workflows/bench-live.yml index 1b59ae5..fbd6891 100644 --- a/.github/workflows/bench-live.yml +++ b/.github/workflows/bench-live.yml @@ -5,18 +5,27 @@ name: Bench (managed OpenRouter admission) on: workflow_dispatch: inputs: + mode: + description: Benchmark admission or calibration bootstrap + type: choice + options: [admission, calibration-bootstrap] + default: admission + required: true + candidate_sha: + description: Exact candidate commit for calibration bootstrap + required: false pairs: description: Exact generators::consensus::scorer+fallback profile - required: true + required: false upstream_provider: description: Exact ZDR provider identity serving every model in the profile - required: true + required: false upstream_provider_route: description: Exact ZDR endpoint route serving every model in the profile - required: true + required: false cost_cap_usd: description: Abort when projected qualification spend exceeds this amount - required: true + required: false default: "70" concurrency: @@ -24,7 +33,54 @@ concurrency: cancel-in-progress: false jobs: + validate-dispatch: + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + mode: ${{ steps.dispatch.outputs.mode }} + candidate_sha: ${{ steps.dispatch.outputs.candidate_sha }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: 1.3.14 + - name: Validate dispatch before credential-bearing jobs + id: dispatch + working-directory: bench + env: + POSTIL_DISPATCH_MODE: ${{ inputs.mode }} + POSTIL_DISPATCH_CANDIDATE_SHA: ${{ inputs.candidate_sha }} + POSTIL_DISPATCH_PAIRS: ${{ inputs.pairs }} + POSTIL_DISPATCH_UPSTREAM_PROVIDER: ${{ inputs.upstream_provider }} + POSTIL_DISPATCH_UPSTREAM_PROVIDER_ROUTE: ${{ inputs.upstream_provider_route }} + POSTIL_DISPATCH_COST_CAP_USD: ${{ inputs.cost_cap_usd }} + run: bun run src/verify-calibration.ts dispatch >> "$GITHUB_OUTPUT" + + calibration-bootstrap: + needs: validate-dispatch + if: needs.validate-dispatch.outputs.mode == 'calibration-bootstrap' + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: 1.3.14 + - name: Require established calibration execution authority + working-directory: bench + env: + CANDIDATE_SHA: ${{ needs.validate-dispatch.outputs.candidate_sha }} + run: bun run src/verify-calibration.ts bootstrap "$CANDIDATE_SHA" + bench-live: + needs: validate-dispatch + if: needs.validate-dispatch.outputs.mode == 'admission' runs-on: ubuntu-latest permissions: contents: read diff --git a/bench/src/verify-calibration.test.ts b/bench/src/verify-calibration.test.ts new file mode 100644 index 0000000..b013aa3 --- /dev/null +++ b/bench/src/verify-calibration.test.ts @@ -0,0 +1,220 @@ +import { afterEach, expect, test } from "bun:test"; +import { execFileSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { cp, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, resolve } from "node:path"; +import { evaluatorSourceSha256 } from "./live"; +import { calibrationMain, validateCalibrationDispatch, verifyLegacyCalibration } from "./verify-calibration"; + +const root = resolve(import.meta.dir, "../.."); +const temporary: string[] = []; +const candidate = randomBytes(20).toString("hex"); +const admission = { + POSTIL_DISPATCH_PAIRS: "provider/generator::provider/scorer", + POSTIL_DISPATCH_UPSTREAM_PROVIDER: "example-provider", + POSTIL_DISPATCH_UPSTREAM_PROVIDER_ROUTE: "example-provider/route", + POSTIL_DISPATCH_COST_CAP_USD: "70", +}; + +afterEach(async () => { + for (const directory of temporary.splice(0)) await rm(directory, { recursive: true, force: true }); +}); + +async function fixture() { + const directory = await mkdtemp(resolve(tmpdir(), "postil-calibration-verifier-")); + temporary.push(directory); + const paths: string[] = JSON.parse(await readFile(resolve(root, "bench/evaluator-contract-sources.json"), "utf8")); + for (const path of [...paths, "bench/baseline-us.json", "bench/baseline-us.attestation.json", "provisional-models-us.json"]) { + await mkdir(dirname(resolve(directory, path)), { recursive: true }); + await cp(resolve(root, path), resolve(directory, path)); + } + return directory; +} + +async function transport() { + const bundle = JSON.parse(await readFile(resolve(root, "bench/baseline-us.attestation.json"), "utf8")); + const statement = JSON.parse(Buffer.from(bundle.dsseEnvelope.payload, "base64").toString("utf8")); + const calls: string[][] = []; + const runGh = async (args: string[]) => { + calls.push(args); + if (args[0] === "api") return statement.predicate.buildDefinition.resolvedDependencies[0].digest.gitCommit; + // Injected CLI transport output tests the consumer, not cryptographic validity. + return JSON.stringify([{ verificationResult: { + statement, signature: { certificate: {} }, verifiedTimestamps: [{ type: "Tlog" }], + } }]); + }; + const runGit = async (args: string[]) => execFileSync("git", args, { cwd: root }); + return { runGh, runGit, calls, statement }; +} + +test("default admission retains all four effective required inputs without granting calibration authority", async () => { + expect(await calibrationMain(["dispatch"], admission)).toBe("mode=admission\n"); + for (const name of Object.keys(admission)) { + await expect(calibrationMain(["dispatch"], { ...admission, [name]: " " })).rejects.toThrow("Admission requires"); + } + expect(validateCalibrationDispatch({ POSTIL_DISPATCH_MODE: "calibration-bootstrap", POSTIL_DISPATCH_CANDIDATE_SHA: candidate })) + .toEqual({ mode: "calibration-bootstrap", candidateSha: candidate }); +}); + +test("malformed source, unknown mode and measurement arguments cannot be normalized into supported dispatch", async () => { + for (const sha of [undefined, "main", candidate.toUpperCase(), `${candidate}\n`, `${candidate};echo`, candidate.slice(1)]) { + expect(() => validateCalibrationDispatch({ POSTIL_DISPATCH_MODE: "calibration-bootstrap", POSTIL_DISPATCH_CANDIDATE_SHA: sha })).toThrow(); + } + expect(() => validateCalibrationDispatch({ ...admission, POSTIL_DISPATCH_MODE: "unknown" })).toThrow(); + for (const args of [ + ["legacy", "--concurrency", "6"], ["dispatch", "--bounded"], + ["bootstrap", candidate, "--concurrency", "6junk"], ["bootstrap", candidate, "--retries", "0"], + ["bootstrap", candidate, "--scorer-model", "provider/scorer"], ["legacy", "legacy"], + ]) await expect(calibrationMain(args, admission)).rejects.toThrow("additional arguments are unsupported"); +}); + +test("every bootstrap source and claimed capability remains refused before candidate or provider execution", async () => { + for (const ref of ["refs/heads/main", "refs/heads/candidate", "refs/tags/candidate"]) { + await expect(calibrationMain(["bootstrap", candidate], { + GITHUB_REF: ref, GITHUB_REPOSITORY: "example/fork", GITHUB_RUN_ATTEMPT: "2", + POSTIL_CREDENTIAL_ISOLATION: "verified", OPENROUTER_API_KEY: randomBytes(32).toString("base64"), + })).rejects.toThrow("credential isolation is UNKNOWN and no candidate is admitted"); + } +}); + +test("frozen historical evidence stays legacy-only and pins the actual signature verification policy", async () => { + const context = await transport(); + const result = await verifyLegacyCalibration(context); + expect(result).toMatchObject({ protocol: "legacy-v2", behaviorCompatibility: "UNKNOWN", observedRuntimeIdentity: "UNKNOWN", executionEnabled: false }); + expect(result.evaluatorSha256).toBe(await evaluatorSourceSha256()); + expect(result.workflowRunId).toBe("35951227818"); + expect(result).not.toHaveProperty("effectiveConcurrency"); + expect(result).not.toHaveProperty("behaviorSha256"); + const verification = context.calls[1]!; + const values = Object.fromEntries(verification.flatMap((value, index) => value.startsWith("--") ? [[value, verification[index + 1]]] : [])); + expect(values["--signer-workflow"]).toBe("postil-dev/postil-cli/.github/workflows/benchmark-calibration.yml"); + expect(values["--signer-digest"]).toBe(result.sourceSha); + expect(values["--source-digest"]).toBe(result.sourceSha); + expect(values["--source-ref"]).toBe("refs/heads/main"); + expect(values["--cert-oidc-issuer"]).toBe("https://token.actions.githubusercontent.com"); + expect(values["--predicate-type"]).toBe("https://slsa.dev/provenance/v1"); + expect(verification).toContain("--deny-self-hosted-runners"); +}); + +test("actual evaluator, effective-launch and workflow mutations invalidate legacy freshness", async () => { + const directory = await fixture(); + const context = await transport(); + for (const [path, before, after] of [ + ["bench/src/harness.ts", "export", "/* altered confidence acceptance */ export"], + ["bench/src/cohort-run.ts", '"--live",', '"--live", "--concurrency", "1",'], + [".github/workflows/benchmark-calibration.yml", "workflow_dispatch: {}", "workflow_dispatch: { inputs: { candidate_sha: { required: true } } }"], + ["bench/bun.lock", "zod", "changed-zod"], + ]) { + const file = resolve(directory, path); + const original = await readFile(file, "utf8"); + expect(original.includes(before)).toBe(true); + await writeFile(file, original.replace(before, after)); + await expect(verifyLegacyCalibration({ ...context, root: directory })).rejects.toThrow("evaluator is stale"); + await writeFile(file, original); + } + expect(context.calls).toHaveLength(0); +}); + +test("fake attestation, modified baseline and invented legacy parameters cannot enter the frozen adapter", async () => { + const directory = await fixture(); + const context = await transport(); + const baselinePath = resolve(directory, "bench/baseline-us.json"); + const baselineBytes = await readFile(baselinePath); + const baseline = JSON.parse(baselineBytes.toString()); + for (const update of [ + { schemaVersion: 3 }, { effectiveConcurrency: 6 }, + { corpus: { ...baseline.corpus, behaviorSha256: randomBytes(32).toString("hex") } }, + ]) { + await writeFile(baselinePath, JSON.stringify({ ...baseline, ...update })); + await expect(verifyLegacyCalibration({ ...context, root: directory })).rejects.toThrow("Unsupported legacy calibration artifact pair"); + } + await writeFile(baselinePath, baselineBytes); + await writeFile(resolve(directory, "bench/baseline-us.attestation.json"), JSON.stringify({ dsseEnvelope: { payload: "fabricated" } })); + await expect(verifyLegacyCalibration({ ...context, root: directory })).rejects.toThrow("Unsupported legacy calibration artifact pair"); + expect(context.calls).toHaveLength(0); +}); + +test("historical blob mutation, registry substitution, failed verification and wrong verified statement are refused", async () => { + const context = await transport(); + await expect(verifyLegacyCalibration({ ...context, runGit: async () => Buffer.from("substituted source") })).rejects.toThrow("Historical calibration source inventory"); + await expect(verifyLegacyCalibration({ ...context, runGh: async () => candidate })).rejects.toThrow("registry source mismatch"); + for (const response of ["[]", "[{}]", JSON.stringify([{ verificationResult: { statement: context.statement } }])]) { + await expect(verifyLegacyCalibration({ ...context, runGh: async args => args[0] === "api" ? context.statement.predicate.buildDefinition.resolvedDependencies[0].digest.gitCommit : response })) + .rejects.toThrow("exact cryptographically verified statement"); + } + const wrappedGh = async (args: string[]) => { + const response = await context.runGh(args); + if (args[0] === "api") return response; + const verified = JSON.parse(response); + verified[0].verificationResult.statement.predicate.runDetails.metadata.invocationId += "/wrong-attempt"; + return JSON.stringify(verified); + }; + await expect(verifyLegacyCalibration({ ...context, runGh: wrappedGh })).rejects.toThrow("exact cryptographically verified statement"); + await expect(verifyLegacyCalibration({ ...context, runGh: async args => { + if (args[0] === "api") return context.runGh(args); + throw new Error("verification failed"); + } })).rejects.toThrow("verification failed"); +}); + +test("manifest substitution and symlink subjects are rejected before external verification", async () => { + const directory = await fixture(); + const context = await transport(); + const file = resolve(directory, "bench/evaluator-contract-sources.json"); + await writeFile(file, JSON.stringify(["../outside-repository"])); + await expect(verifyLegacyCalibration({ ...context, root: directory })).rejects.toThrow("Unsupported legacy evaluator manifest"); + await rm(file); + await symlink(resolve(root, "bench/evaluator-contract-sources.json"), file); + await expect(verifyLegacyCalibration({ ...context, root: directory })).rejects.toThrow("regular file"); + expect(context.calls).toHaveLength(0); +}); + +test("profile drift cannot retain legacy acceptance", async () => { + const directory = await fixture(); + const context = await transport(); + const profilePath = resolve(directory, "provisional-models-us.json"); + const originalProfile = await readFile(profilePath); + await writeFile(profilePath, Buffer.concat([originalProfile, Buffer.from("\n")])); + await expect(verifyLegacyCalibration({ ...context, root: directory })).rejects.toThrow("screening profile"); +}); + +test("a source change during successful attestation transport cannot retain legacy acceptance", async () => { + const directory = await fixture(); + const context = await transport(); + const runGh = async (args: string[]) => { + const output = await context.runGh(args); + if (args[0] === "attestation") await writeFile(resolve(directory, "bench/src/cohort-run.ts"), "changed during verification"); + return output; + }; + await expect(verifyLegacyCalibration({ ...context, root: directory, runGh })).rejects.toThrow("changed during verification"); +}); + +test("parsed workflow isolates bootstrap from admission credentials and signing permissions", async () => { + const workflow = Bun.YAML.parse(await readFile(resolve(root, ".github/workflows/bench-live.yml"), "utf8")) as any; + expect(workflow.on.workflow_dispatch.inputs.mode.default).toBe("admission"); + for (const jobName of ["validate-dispatch", "calibration-bootstrap"]) { + const job = workflow.jobs[jobName]; + expect(job.permissions).toEqual({ contents: "read" }); + expect(job.env).toBeUndefined(); + expect(JSON.stringify(job)).not.toContain("secrets."); + expect(job.steps.filter((step: any) => step.uses?.startsWith("actions/checkout@")).every((step: any) => step.with["persist-credentials"] === false)).toBe(true); + expect(job.steps.every((step: any) => !step.uses?.startsWith("actions/cache@") && !step.uses?.startsWith("actions/attest@"))).toBe(true); + expect(job.steps.filter((step: any) => step.uses?.startsWith("oven-sh/setup-bun@"))[0].with["bun-version"]).toBe("1.3.14"); + } + expect(workflow.jobs["bench-live"].needs).toBe("validate-dispatch"); + expect(workflow.jobs["bench-live"].if).toBe("needs.validate-dispatch.outputs.mode == 'admission'"); + expect(workflow.jobs["calibration-bootstrap"].if).toBe("needs.validate-dispatch.outputs.mode == 'calibration-bootstrap'"); +}); + +test("actual bootstrap command exposes neither generated canaries nor a success artifact", async () => { + const canary = randomBytes(32).toString("base64"); + const child = Bun.spawn([process.execPath, "run", resolve(import.meta.dir, "verify-calibration.ts"), "bootstrap", candidate], { + env: { PATH: process.env.PATH, OPENROUTER_API_KEY: canary, ACTIONS_ID_TOKEN_REQUEST_TOKEN: canary }, + stdout: "pipe", stderr: "pipe", timeout: 10_000, + }); + const [exit, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(exit).toBe(1); + expect(stdout).toBe(""); + expect(stderr).toContain("credential isolation is UNKNOWN"); + expect(stderr.includes(canary)).toBe(false); +}); diff --git a/bench/src/verify-calibration.ts b/bench/src/verify-calibration.ts new file mode 100644 index 0000000..018673f --- /dev/null +++ b/bench/src/verify-calibration.ts @@ -0,0 +1,144 @@ +#!/usr/bin/env bun +// Read-only verification of the retained calibration; no calibration producer. +import { execFile as execFileCallback } from "node:child_process"; +import { createHash } from "node:crypto"; +import { lstat, readFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { promisify, isDeepStrictEqual } from "node:util"; + +const execFile = promisify(execFileCallback); +const REPOSITORY = "postil-dev/postil-cli"; +const SOURCE = "356ba691999c737551506039d2ad4bc26c6c1354"; +const PROFILE = "openai/gpt-5.6-luna"; +const BASELINE_SHA256 = "a287fadfd84ba072507c50042442fc82c97d37d92e9287f7c3fc25f0d71365a5"; +const BUNDLE_SHA256 = "dd51cdaeb46a9a2edafbaf4fc009e81d37a9c1ef3d19c0af270906344c3dc207"; +const MANIFEST_SHA256 = "f843f909cd89990ee749dc0d2aaf053a5d07ced70f2147843a34026b7df5067b"; +const EXECUTION_UNAVAILABLE = "Calibration execution is unavailable: credential isolation is UNKNOWN and no candidate is admitted"; +const DEFAULT_ROOT = resolve(import.meta.dir, "../.."); +const hash = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex"); + +export function validateCalibrationDispatch(input: Readonly>) { + const mode = input.POSTIL_DISPATCH_MODE || "admission"; + if (mode === "admission") { + for (const name of ["PAIRS", "UPSTREAM_PROVIDER", "UPSTREAM_PROVIDER_ROUTE", "COST_CAP_USD"]) { + if (!input[`POSTIL_DISPATCH_${name}`]?.trim()) throw new Error(`Admission requires ${name}`); + } + return { mode } as const; + } + if (mode !== "calibration-bootstrap") throw new Error("Unsupported benchmark dispatch mode"); + const candidateSha = input.POSTIL_DISPATCH_CANDIDATE_SHA; + if (candidateSha === undefined || !/^[0-9a-f]{40}$/u.test(candidateSha)) { + throw new Error("Calibration bootstrap requires an exact lowercase candidate commit SHA"); + } + return { mode, candidateSha } as const; +} + +async function regularBytes(path: string): Promise { + const metadata = await lstat(path); + if (!metadata.isFile() || metadata.isSymbolicLink()) throw new Error("Calibration input must be a regular file"); + return readFile(path); +} + +async function sourceDigest(paths: string[], read: (path: string) => Promise): Promise { + const bytes = await Promise.all(paths.map(read)); + const digest = createHash("sha256"); + paths.forEach((path, index) => digest.update(path).update("\0").update(bytes[index]!).update("\0")); + return digest.digest("hex"); +} + +export async function verifyLegacyCalibration(options: { + root?: string; + runGh?: (args: string[]) => Promise; + runGit?: (args: string[]) => Promise; +} = {}) { + const root = resolve(options.root ?? DEFAULT_ROOT); + const runGit = options.runGit ?? (async (args: string[]) => + (await execFile("git", args, { cwd: root, encoding: "buffer", timeout: 30_000, maxBuffer: 4 * 1024 * 1024 })).stdout); + const runGh = options.runGh ?? (async (args: string[]) => + (await execFile("gh", args, { cwd: root, timeout: 60_000, maxBuffer: 4 * 1024 * 1024 })).stdout); + const manifestPath = "bench/evaluator-contract-sources.json"; + const baselinePath = resolve(root, "bench/baseline-us.json"); + const bundlePath = resolve(root, "bench/baseline-us.attestation.json"); + const profilePath = resolve(root, "provisional-models-us.json"); + const [manifestBytes, baselineBytes, bundleBytes, profileBytes] = await Promise.all([ + regularBytes(resolve(root, manifestPath)), regularBytes(baselinePath), regularBytes(bundlePath), + regularBytes(profilePath), + ]); + // Freeze the adapter's case before parsing paths or accepting any extra fields. + if (hash(manifestBytes) !== MANIFEST_SHA256) throw new Error("Unsupported legacy evaluator manifest"); + if (hash(baselineBytes) !== BASELINE_SHA256 || hash(bundleBytes) !== BUNDLE_SHA256) { + throw new Error("Unsupported legacy calibration artifact pair"); + } + const baseline = JSON.parse(baselineBytes.toString("utf8")); + if (hash(profileBytes) !== baseline.profiles[PROFILE].screeningProfileSha256) { + throw new Error("Legacy calibration screening profile does not match its attested baseline"); + } + const paths: string[] = JSON.parse(manifestBytes.toString("utf8")); + const expectedDigest: string = baseline.corpus.evaluatorSha256; + if (await sourceDigest(paths, path => regularBytes(resolve(root, path))) !== expectedDigest) { + throw new Error("Legacy calibration evaluator is stale; changed evaluator sources require genuine new calibration"); + } + const historicalManifest = await runGit(["show", `${SOURCE}:${manifestPath}`]); + if (!historicalManifest.equals(manifestBytes) || + await sourceDigest(paths, path => runGit(["show", `${SOURCE}:${path}`])) !== expectedDigest) { + throw new Error("Historical calibration source inventory does not match the attested evaluator"); + } + const registry = await runGh(["api", `repos/${REPOSITORY}/git/ref/tags/postil-calibration-${SOURCE}`, "--jq", ".object.sha"]); + if (registry.trim() !== SOURCE) throw new Error("Historical calibration registry source mismatch"); + const verified = JSON.parse(await runGh([ + "attestation", "verify", baselinePath, "--bundle", bundlePath, + "--repo", REPOSITORY, + "--signer-workflow", `${REPOSITORY}/.github/workflows/benchmark-calibration.yml`, + "--signer-digest", SOURCE, "--source-digest", SOURCE, + "--source-ref", "refs/heads/main", "--cert-oidc-issuer", "https://token.actions.githubusercontent.com", + "--predicate-type", "https://slsa.dev/provenance/v1", "--deny-self-hosted-runners", "--format", "json", + ])); + const bundle = JSON.parse(bundleBytes.toString("utf8")); + const statement = JSON.parse(Buffer.from(bundle.dsseEnvelope.payload, "base64").toString("utf8")); + if (!Array.isArray(verified) || verified.length !== 1 || + !verified[0]?.verificationResult?.signature?.certificate || + !verified[0]?.verificationResult?.verifiedTimestamps?.length || + !isDeepStrictEqual(verified[0]?.verificationResult?.statement, statement)) { + throw new Error("Historical calibration requires the exact cryptographically verified statement"); + } + const [finalDigest, finalBaseline, finalBundle, finalProfile] = await Promise.all([ + sourceDigest(paths, path => regularBytes(resolve(root, path))), + regularBytes(baselinePath), regularBytes(bundlePath), regularBytes(profilePath), + ]); + if (finalDigest !== expectedDigest || !finalBaseline.equals(baselineBytes) || + !finalBundle.equals(bundleBytes) || !finalProfile.equals(profileBytes)) { + throw new Error("Calibration inputs changed during verification"); + } + return { + protocol: "legacy-v2" as const, + sourceSha: SOURCE, + workflowRunId: baseline.profiles[PROFILE].calibration.workflowRunId as string, + evaluatorSha256: expectedDigest, + behaviorCompatibility: "UNKNOWN" as const, + observedRuntimeIdentity: "UNKNOWN" as const, + executionEnabled: false as const, + }; +} + +export async function calibrationMain(args: readonly string[], input: Readonly> = process.env) { + if (args.length === 1 && args[0] === "dispatch") { + const dispatch = validateCalibrationDispatch(input); + return `mode=${dispatch.mode}\n${"candidateSha" in dispatch ? `candidate_sha=${dispatch.candidateSha}\n` : ""}`; + } + if (args.length === 1 && args[0] === "legacy") return JSON.stringify(await verifyLegacyCalibration()) + "\n"; + if (args.length === 2 && args[0] === "bootstrap") { + validateCalibrationDispatch({ POSTIL_DISPATCH_MODE: "calibration-bootstrap", POSTIL_DISPATCH_CANDIDATE_SHA: args[1] }); + throw new Error(EXECUTION_UNAVAILABLE); + } + throw new Error("Expected dispatch, legacy, or bootstrap ; additional arguments are unsupported"); +} + +if (import.meta.main) { + try { + process.stdout.write(await calibrationMain(process.argv.slice(2))); + } catch { + // Child tools and malformed input may contain sensitive diagnostic content. + console.error("Calibration verification refused; exact legacy inputs are required. Bootstrap execution is unavailable: credential isolation is UNKNOWN and no candidate is admitted"); + process.exitCode = 1; + } +}