Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions pkgs/desktop-commander/worker/promote.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Type surface for promote.mjs (a plain Node script; vitest tests import
// its pure helper). deploymentStatus classifies the live deployment
// against a provenance manifest: "already-promoted" when the manifest
// version is already the sole 100% deployment, "at-baseline" when the
// active version matches the manifest baseline, "drifted" otherwise.
export type DeploymentStatus = "already-promoted" | "at-baseline" | "drifted";

export interface ManifestVersionEntry {
version_id?: string;
percentage?: number;
}

export interface ManifestDeployment {
versions?: ManifestVersionEntry[];
}

export interface PromotionManifest {
versionId: string;
baselineVersionId: string;
}

export function deploymentStatus(
current: ManifestDeployment | undefined,
manifest: PromotionManifest,
): DeploymentStatus;
161 changes: 96 additions & 65 deletions pkgs/desktop-commander/worker/promote.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
// version to 100% of traffic. The version must come from a provenance
// manifest emitted by upload-version.mjs in a successful publish run
// that verify-upload-run.mjs has already vouched for, and the live
// deployment must still sit at the manifest's baseline — any drift
// aborts the promotion instead of guessing.
// deployment must either still sit at the manifest's baseline or
// already serve exactly this version at 100% (an idempotent re-run);
// any other drift aborts the promotion instead of guessing.
// Usage: promote.mjs --manifest <provenance.json> --promote
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
Expand All @@ -13,77 +14,103 @@ import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
const cfBin = join(here, "node_modules", ".bin", "cf");

const args = process.argv.slice(2);
const manifestFlag = args.indexOf("--manifest");
const manifestPath = manifestFlag >= 0 ? args[manifestFlag + 1] : undefined;
const rest = args.filter((_, i) => i !== manifestFlag && i !== manifestFlag + 1);
if (!manifestPath || rest.length !== 1 || rest[0] !== "--promote") {
console.error("usage: promote.mjs --manifest <provenance.json> --promote");
process.exit(2);
// Classify the live deployment against the manifest without side
// effects: "already-promoted" when the manifest version is already the
// sole version at 100% of traffic, "at-baseline" when promotion may
// proceed, "drifted" for anything else. Pure, for unit tests.
export function deploymentStatus(current, manifest) {
const versions = current?.versions ?? [];
if (
versions.length === 1 &&
versions[0]?.version_id === manifest.versionId &&
versions[0]?.percentage === 100
) {
return "already-promoted";
}
if (versions[0]?.version_id === manifest.baselineVersionId) {
return "at-baseline";
Comment on lines +30 to +31

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve null-baseline handling for the first promotion

On a first publish with no existing deployment, upload-version.mjs explicitly records baselineVersionId: null. If the deployment list is empty when promoting that upload, this comparison checks undefined === null and classifies the state as drifted, preventing the initial deployment. The previous implementation normalized a missing active version with ?? null, allowing this supported bootstrap path. Preserve that normalization when comparing against the baseline.

Useful? React with 👍 / 👎.

}
return "drifted";
}

const config = JSON.parse(readFileSync(join(here, "config.json"), "utf8"));
const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
const verified = JSON.parse(readFileSync(requireEnv("DC_WORKER_VERIFIED_RUN_FILE"), "utf8"));
const token = requireEnv("DC_WORKER_CF_TOKEN");
requireEnv("CLOUDFLARE_ACCOUNT_ID");
function main() {
const args = process.argv.slice(2);
const manifestFlag = args.indexOf("--manifest");
const manifestPath = manifestFlag >= 0 ? args[manifestFlag + 1] : undefined;
const rest = args.filter((_, i) => i !== manifestFlag && i !== manifestFlag + 1);
if (!manifestPath || rest.length !== 1 || rest[0] !== "--promote") {
console.error("usage: promote.mjs --manifest <provenance.json> --promote");
process.exit(2);
}

if (!existsSync(cfBin)) {
throw new Error("pinned cf CLI missing; install dependencies before supplying credentials");
}
if (manifest.worker !== config.worker) {
throw new Error(`manifest worker ${manifest.worker} does not match config worker ${config.worker}`);
}
if (manifest.sha !== verified.sha || String(manifest.runId) !== String(verified.id) || String(manifest.runAttempt) !== String(verified.attempt)) {
throw new Error("manifest does not match the verified upload run; refusing to promote");
}
if (manifest.repository?.toLowerCase() !== process.env.GITHUB_REPOSITORY?.toLowerCase()) {
throw new Error("manifest repository does not match this repository; refusing to promote");
}
if (typeof manifest.versionId !== "string" || !manifest.versionId) {
throw new Error("manifest has no versionId; refusing to promote");
}
const config = JSON.parse(readFileSync(join(here, "config.json"), "utf8"));
const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
const verified = JSON.parse(readFileSync(requireEnv("DC_WORKER_VERIFIED_RUN_FILE"), "utf8"));
const token = requireEnv("DC_WORKER_CF_TOKEN");
requireEnv("CLOUDFLARE_ACCOUNT_ID");

function cfJson(argv) {
const output = execFileSync(cfBin, argv, {
cwd: here,
encoding: "utf8",
env: { ...process.env, CLOUDFLARE_API_TOKEN: token },
});
let parsed;
try {
parsed = JSON.parse(output);
} catch {
throw new Error("cf returned non-JSON output; refusing to continue");
if (!existsSync(cfBin)) {
throw new Error("pinned cf CLI missing; install dependencies before supplying credentials");
}
if (manifest.worker !== config.worker) {
throw new Error(`manifest worker ${manifest.worker} does not match config worker ${config.worker}`);
}
if (manifest.sha !== verified.sha || String(manifest.runId) !== String(verified.id) || String(manifest.runAttempt) !== String(verified.attempt)) {
throw new Error("manifest does not match the verified upload run; refusing to promote");
}
if (manifest.repository?.toLowerCase() !== process.env.GITHUB_REPOSITORY?.toLowerCase()) {
throw new Error("manifest repository does not match this repository; refusing to promote");
}
if (typeof manifest.versionId !== "string" || !manifest.versionId) {
throw new Error("manifest has no versionId; refusing to promote");
}
return parsed?.result ?? parsed;
}

const version = cfJson(["workers", "versions", "get", manifest.versionId, "--worker-id", config.worker]);
if ((version.id ?? version.version_id) !== manifest.versionId) {
throw new Error("cf did not return the manifest version; refusing to promote");
}
if (version.annotations?.["workers/tag"] && version.annotations["workers/tag"] !== manifest.tag) {
throw new Error("the version's tag does not match the manifest tag; refusing to promote");
}
function cfJson(argv) {
const output = execFileSync(cfBin, argv, {
cwd: here,
encoding: "utf8",
env: { ...process.env, CLOUDFLARE_API_TOKEN: token },
});
let parsed;
try {
parsed = JSON.parse(output);
} catch {
throw new Error("cf returned non-JSON output; refusing to continue");
}
return parsed?.result ?? parsed;
}

const deployments = cfJson(["workers", "deployments", "list", "--worker", config.worker, "--per-page", "1"]);
const current = Array.isArray(deployments) ? deployments[0] : deployments?.deployments?.[0];
const currentVersionId = current?.versions?.[0]?.version_id ?? null;
if (currentVersionId !== manifest.baselineVersionId) {
throw new Error(
`active version ${currentVersionId} is not the manifest baseline ${manifest.baselineVersionId}; refusing to promote over drift`,
);
}
const version = cfJson(["workers", "versions", "get", manifest.versionId, "--worker-id", config.worker]);
if ((version.id ?? version.version_id) !== manifest.versionId) {
throw new Error("cf did not return the manifest version; refusing to promote");
}
if (version.annotations?.["workers/tag"] && version.annotations["workers/tag"] !== manifest.tag) {
throw new Error("the version's tag does not match the manifest tag; refusing to promote");
}

const created = cfJson([
"workers", "deployments", "create",
"--worker", config.worker,
"--strategy", "percentage",
"--versions", JSON.stringify([{ version_id: manifest.versionId, percentage: 100 }]),
]);
const deploymentId = created?.id ?? created?.deployment_id;
console.log(`promoted ${config.worker} version ${manifest.versionId} (tag ${manifest.tag}) to 100%${deploymentId ? `; deployment ${deploymentId}` : ""}`);
const deployments = cfJson(["workers", "deployments", "list", "--worker", config.worker, "--per-page", "1"]);
const current = Array.isArray(deployments) ? deployments[0] : deployments?.deployments?.[0];
const status = deploymentStatus(current, manifest);
if (status === "already-promoted") {
console.log(`verified ${config.worker} version ${manifest.versionId} (tag ${manifest.tag}) is already the sole 100% deployment; nothing to promote`);
return;
}
if (status === "drifted") {
const active = current?.versions?.[0]?.version_id ?? null;
throw new Error(
`active version ${active} is neither the manifest baseline ${manifest.baselineVersionId} nor the verified upload ${manifest.versionId}; refusing to promote over drift`,
);
}

const created = cfJson([
"workers", "deployments", "create",
"--worker", config.worker,
"--strategy", "percentage",
"--versions", JSON.stringify([{ version_id: manifest.versionId, percentage: 100 }]),
]);
const deploymentId = created?.id ?? created?.deployment_id;
console.log(`promoted ${config.worker} version ${manifest.versionId} (tag ${manifest.tag}) to 100%${deploymentId ? `; deployment ${deploymentId}` : ""}`);
}

function requireEnv(name) {
const value = process.env[name];
Expand All @@ -92,3 +119,7 @@ function requireEnv(name) {
}
return value;
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
main();
}
57 changes: 57 additions & 0 deletions pkgs/desktop-commander/worker/test/promote.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { describe, expect, it } from "vitest";
import { deploymentStatus } from "../promote.mjs";

// Oracle: the promote drift contract in pkgs/desktop-commander/worker/README.md —
// promotion proceeds only at the manifest baseline, is a no-op success when the
// verified upload is already the sole 100% deployment, and refuses any other
// live state (#13472: the target version had already been deployed and the
// baseline-only check misread that success as drift).

const manifest = {
versionId: "37e2f6a3-f2ed-4f77-a84a-a7acf67f6ff4",
baselineVersionId: "c2ac67bb-f7ab-4912-a820-aa2ead4aa908",
};

describe("promotion drift classification", () => {
it("treats the verified upload already serving 100% as already-promoted", () => {
expect(
deploymentStatus(
{ versions: [{ version_id: manifest.versionId, percentage: 100 }] },
manifest,
),
).toBe("already-promoted");
});

it("allows promotion when the live deployment still matches the baseline", () => {
expect(
deploymentStatus(
{ versions: [{ version_id: manifest.baselineVersionId, percentage: 100 }] },
manifest,
),
).toBe("at-baseline");
});

it("refuses drift to an unrelated active version", () => {
expect(
deploymentStatus(
{ versions: [{ version_id: "00000000-0000-0000-0000-000000000000", percentage: 100 }] },
manifest,
),
).toBe("drifted");
});

it("refuses a partial rollout of the verified upload instead of guessing", () => {
expect(
deploymentStatus(
{ versions: [{ version_id: manifest.versionId, percentage: 50 }, { version_id: manifest.baselineVersionId, percentage: 50 }] },
manifest,
),
).toBe("drifted");
});

it("refuses an empty or malformed deployment record", () => {
expect(deploymentStatus(undefined, manifest)).toBe("drifted");
expect(deploymentStatus({}, manifest)).toBe("drifted");
expect(deploymentStatus({ versions: [] }, manifest)).toBe("drifted");
});
});