From 3c2fb703c19bbf58caaebaab9b4f1ea8a9a959a4 Mon Sep 17 00:00:00 2001 From: Tim Smart Date: Mon, 21 Sep 2026 23:08:32 +0000 Subject: [PATCH] test: specify publish approval contracts Tests-first contract for the two-PR publish flow (EFF-1460): release manifest identity, readiness against the stage queue, the Publish Packages pull request, stage approval over the registry API, publication with partial-publication recovery and the website gate, the CLI surface, and the readiness and publish workflows. New modules are stubs that fail with 'not implemented'; Git gains a stubbed lastCommitTouching. --- packages/tools/release/CONTRACT.md | 148 +++++- packages/tools/release/src/Git.ts | 11 +- packages/tools/release/src/NotImplemented.ts | 14 + packages/tools/release/src/Publication.ts | 142 ++++++ .../tools/release/src/PublishPullRequest.ts | 87 ++++ packages/tools/release/src/Readiness.ts | 56 +++ packages/tools/release/src/ReleaseManifest.ts | 86 ++++ packages/tools/release/src/StageApproval.ts | 42 ++ .../tools/release/test/Publication.test.ts | 432 ++++++++++++++++++ .../tools/release/test/PublishCli.test.ts | 157 +++++++ .../release/test/PublishPullRequest.test.ts | 246 ++++++++++ .../release/test/PublishWorkflow.test.ts | 185 ++++++++ packages/tools/release/test/Readiness.test.ts | 196 ++++++++ .../release/test/ReleaseManifest.test.ts | 180 ++++++++ .../tools/release/test/StageApproval.test.ts | 137 ++++++ packages/tools/release/test/utils.ts | 119 ++++- 16 files changed, 2229 insertions(+), 9 deletions(-) create mode 100644 packages/tools/release/src/NotImplemented.ts create mode 100644 packages/tools/release/src/Publication.ts create mode 100644 packages/tools/release/src/PublishPullRequest.ts create mode 100644 packages/tools/release/src/Readiness.ts create mode 100644 packages/tools/release/src/ReleaseManifest.ts create mode 100644 packages/tools/release/src/StageApproval.ts create mode 100644 packages/tools/release/test/Publication.test.ts create mode 100644 packages/tools/release/test/PublishCli.test.ts create mode 100644 packages/tools/release/test/PublishPullRequest.test.ts create mode 100644 packages/tools/release/test/PublishWorkflow.test.ts create mode 100644 packages/tools/release/test/Readiness.test.ts create mode 100644 packages/tools/release/test/ReleaseManifest.test.ts create mode 100644 packages/tools/release/test/StageApproval.test.ts diff --git a/packages/tools/release/CONTRACT.md b/packages/tools/release/CONTRACT.md index 5ff1b8f150..64e0f72456 100644 --- a/packages/tools/release/CONTRACT.md +++ b/packages/tools/release/CONTRACT.md @@ -110,6 +110,145 @@ its website dispatch are designed. The existing `deploy-website` workflow and The `rc` tag is a workflow constant until the fixed group leaves the `rc` lane. +## Publish approval (EFF-1460; contract only until the implementation run) + +Merging "Version Packages (rc)" stages a release. Making it public is a +second pull request, "Publish Packages (rc)", that the readiness workflow +opens only once every staged version has passed the registry's validation. +Merging that PR authorises publication of exactly the staged tarballs it pins. +The tests in `test/ReleaseManifest.test.ts`, `test/Readiness.test.ts`, +`test/PublishPullRequest.test.ts`, `test/StageApproval.test.ts`, +`test/Publication.test.ts`, `test/PublishCli.test.ts` and +`test/PublishWorkflow.test.ts` are the executable contract; the modules they +import exist as stubs in `src/` and fail with `not implemented` until the +implementation run fills them in. + +### Modules + +| Module | Role | Backed by | +| -------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------- | +| `ReleaseManifest` | `fromStaged`, `encode`, `decode`, `identity`; `MANIFEST_PATH`, `LEDGER_PATH` | pure | +| `Readiness` | `assess`: `Ready` or `NotReady` with blockers; the status vocabulary sets | pure | +| `PublishPullRequest` | `title`, `body`, `identityFromBody`, `sync` | `Git`, `GitHub`, `FileSystem` | +| `StageApproval` | `viewStaged`, `approve` (the only registry writes in the tool) | `HttpClient`; `NPM_APPROVE_TOKEN` | +| `Publication` | `readiness` and `publish` orchestration | all of the above, `Registry`, `Workspace` | +| `Cli` | `release readiness --tag [--dry-run]`, `release publish --expect-identity [--dry-run]` | `Publication` | + +`Git` gains `lastCommitTouching(path)`; nothing else in the existing modules +changes. + +### The manifest + +`.release/manifest.json` (`ReleaseManifest.MANIFEST_PATH`) pins the release: +`schema`, the dist-`tag`, `sourceSha` (the last first-parent commit that +touched `.changeset/ledger.yaml`, which is the "Version Packages" merge the +tarballs were built from; the website deploys this revision) and `packages`, +one `{ name, version, stageId }` per public package, sorted by name. `encode` +is canonical and byte-stable; `identity` is the first 16 hex characters of +the SHA-256 of that encoding. The identity appears in the publish PR body as +``, and a maintainer passes it to +`release publish --expect-identity`. `decode` rejects unknown schemas, missing +fields and unsorted package lists, so a hand-edited manifest cannot slip +through. + +### Readiness + +`Readiness.assess` classifies every manifest package against the queue and +the registry: `public` (already served), `approvable` (the pinned stage id +exists at the pinned name and version with a status in +`APPROVABLE_STATUSES`), `pending` (`validating`), `missing` (no item with the +pinned id, or the id now belongs to something else; the detail names a newer +id when the version was re-staged), `blocked` (`blocked`, `rejected`, +`deleted`) or `unknown` (no status, or a word outside every set). A release +is `Ready` only when every package is `public` or `approvable`; anything else +fails closed. The status words are the contract's assumption, taken from the +npm CLI fixtures and pnpm's renderer; the live probe may amend the sets. + +### The readiness workflow + +`release-readiness.yml` runs on a schedule (and on demand) and calls +`release readiness --tag rc`, which: + +1. lists the workspace, the queue and the published state; the release set is + every public package whose manifest version is not published. Empty → + `Idle`; +2. if the manifest already on `main` still pins items in the queue, that + release is authorised and unfinished → `InProgress`, no new PR; +3. any release-set package with no upload at its version → `Incomplete`; +4. otherwise builds the manifest (`fromStaged` fails on a stale upload at + another version, exactly like `Routing`), assesses readiness and calls + `PublishPullRequest.sync`. + +`sync` never touches git while the release is not ready: with an open PR it +rewrites the title to `Publish Packages (rc) [not ready]` and lists the +blockers in the body (`Marked`); without one it does nothing (`Skipped`). +When ready, an open PR that already carries this identity is left alone +(`NoChanges`), so repeated runs are no-ops; otherwise the branch +`publish-release/main` is reset from `main`, the manifest committed as +"Publish Packages", force-pushed, and the PR created or updated. The step +holds `NPM_STAGE_TOKEN` (queue reads) and `CHANGESET_GITHUB_TOKEN` (branch +push and PR) and nothing else; the job has no `id-token` permission and runs +no build. + +### Publication + +`publish.yml` is `workflow_dispatch` only, runs only on `main`, has +`contents: read`, no build, version or stage steps, and takes two inputs: the +identity from the merged PR and a one-time password. `release publish +--expect-identity ` reads the OTP from `NPM_OTP` (never a flag, so it is +not on argv) and: + +1. decodes the manifest at `MANIFEST_PATH` on the checkout; its identity must + equal the expected one, otherwise it fails before any registry call. This + is what ties the merge to one exact manifest: neither the current queue + nor an unmerged branch is ever consulted for what to publish; +2. rechecks the whole release with `Readiness.assess`; any blocker fails the + run before anything is approved; +3. approves each `approvable` package in manifest order with + `StageApproval.approve` (`POST /-/stage//approve`, `npm-otp` header), + one registry operation each. There is no batch or transactional approve, + so publication is not atomic: the first failure stops the loop and the + error names what was approved and what remains; +4. polls `Registry.isPublished` for every approved package every + `CONFIRM_INTERVAL` until all are served or `CONFIRM_TIMEOUT` elapses, and + only then returns `Published` with `websiteRevision = sourceSha`. + +Packages already public are verified, never re-approved, so re-dispatching +the workflow with the same identity and a fresh OTP finishes a partially +published release. When everything is already public it returns +`AlreadyPublished` with the same website revision, so a failed website +dispatch is retried by re-dispatching the workflow. The workflow writes +`published=true` and `revision=` to its outputs; the website step +runs only on `published == 'true'` with channel `v4` and that revision. + +### Credentials and what is still unverified + +Verified against pnpm 11.20's bundled `stage/approve.js`, the npm docs +(`npm-stage`, about-access-tokens, trusted-publishers) and the September 2026 +GitHub changelog: + +- approve is `POST /-/stage//approve` with `Authorization: Bearer`, + `npm-auth-type: web`, `npm-command: stage` and `npm-otp`; a 401 carrying + `authUrl`/`doneUrl` or a `www-authenticate` header mentioning OTP is the + proof-of-presence challenge; +- OIDC trust tokens can only `stage publish`; `list`, `view`, `approve` and + `reject` "require interactive authentication and cannot use OIDC tokens"; +- stage-only granular tokens cannot approve; approval needs "a maintainer with + 2FA enabled", via the CLI with `--otp` or npmjs.com. There is no unattended + CI approval, which is why merging the publish PR authorises publication and + a maintainer still supplies the OTP at dispatch time. + +Not verifiable without the live probe (EFF-1455 P1, P3, P5): whether +`NPM_STAGE_TOKEN` can read `GET /-/stage`; the exact status vocabulary; and +whether a granular publish token from a 2FA account plus one TOTP approves +non-interactively, and whether the registry accepts the same TOTP across 31 +consecutive approvals inside its 30-second window. If P5 fails, `release +publish` runs unchanged from a maintainer's terminal against a checkout of +`main` (`NPM_APPROVE_TOKEN` and `NPM_OTP` in the environment), and +`publish.yml` becomes the website-dispatch step only. `NPM_STAGE_TOKEN` and +`NPM_APPROVE_TOKEN` are not configured on the repository yet (only +`CHANGESET_GITHUB_TOKEN` and `WEBSITE_DISPATCH_TOKEN` exist). + ## Release tracks and the 4.0 GA handoff This migration applies only to `main`. The `v3` branch keeps its existing @@ -162,8 +301,7 @@ duplicate staged version. ## Out of scope -The approval gate (all staged versions ready, then approve), the approval -path itself, and the website deployment that follows publication wait on the -live spike findings and on the maintainer decision recorded in EFF-1455. -`Registry.listStaged` is defined here only because routing needs to skip -versions already awaiting approval. +The approval gate, the approval path and the website deployment are +specified above (EFF-1460) and implemented separately; until that lands, +`Registry.listStaged` is used only so that routing skips versions already +awaiting approval. diff --git a/packages/tools/release/src/Git.ts b/packages/tools/release/src/Git.ts index e5c0c546fa..a59a6ba0f8 100644 --- a/packages/tools/release/src/Git.ts +++ b/packages/tools/release/src/Git.ts @@ -6,6 +6,7 @@ import * as Option from "effect/Option" import type * as Path from "effect/Path" import { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner" import { ReleaseError } from "./Errors.ts" +import { notImplementedEffect } from "./NotImplemented.ts" import { findWorkspaceRoot, runCommand, runCommandOk } from "./Process.ts" /** @@ -23,6 +24,13 @@ export class Git extends Context.Service Effect.Effect /** `git checkout `; used to return to the original commit afterwards. */ readonly checkout: (ref: string) => Effect.Effect + /** + * Full SHA of the last first-parent commit that touched `path` + * (`git log -1 --first-parent --format=%H -- `); fails when none did. + * The publish flow uses it on `.changeset/ledger.yaml` to find the + * "Version Packages" merge a staged release was built from. + */ + readonly lastCommitTouching: (path: string) => Effect.Effect }>()("@effect/release/Git") { static readonly layer: Layer.Layer = Layer .effect( @@ -55,7 +63,8 @@ export class Git extends Context.Service git(["checkout", "-B", branch, from]).pipe(Effect.asVoid), commitAll, pushForce: (branch) => git(["push", "--force", "origin", branch]).pipe(Effect.asVoid), - checkout: (ref) => git(["checkout", ref]).pipe(Effect.asVoid) + checkout: (ref) => git(["checkout", ref]).pipe(Effect.asVoid), + lastCommitTouching: () => notImplementedEffect("Git.lastCommitTouching") }) }) ) diff --git a/packages/tools/release/src/NotImplemented.ts b/packages/tools/release/src/NotImplemented.ts new file mode 100644 index 0000000000..7a56133f29 --- /dev/null +++ b/packages/tools/release/src/NotImplemented.ts @@ -0,0 +1,14 @@ +import * as Effect from "effect/Effect" + +/** + * Placeholder for contract members that the implementation run fills in. + * Throwing (rather than failing) keeps "not implemented" distinct from every + * modelled `ReleaseError` in the tests. Delete this module once every member + * is implemented. + */ +export const notImplemented = (member: string): never => { + throw new Error(`not implemented: ${member}`) +} + +export const notImplementedEffect = (member: string): Effect.Effect => + Effect.die(new Error(`not implemented: ${member}`)) diff --git a/packages/tools/release/src/Publication.ts b/packages/tools/release/src/Publication.ts new file mode 100644 index 0000000000..6b8aaace07 --- /dev/null +++ b/packages/tools/release/src/Publication.ts @@ -0,0 +1,142 @@ +import * as Context from "effect/Context" +import type * as Duration from "effect/Duration" +import type * as Effect from "effect/Effect" +import type * as FileSystem from "effect/FileSystem" +import * as Layer from "effect/Layer" +import type * as Option from "effect/Option" +import type * as Path from "effect/Path" +import type * as Redacted from "effect/Redacted" +import type { ReleaseError } from "./Errors.ts" +import type { Git } from "./Git.ts" +import type { GitHub, PullRequest } from "./GitHub.ts" +import { notImplementedEffect } from "./NotImplemented.ts" +import type { SyncResult } from "./PublishPullRequest.ts" +import type { PackageReadiness, Readiness } from "./Readiness.ts" +import type { Registry } from "./Registry.ts" +import type { ManifestPackage, ReleaseManifest } from "./ReleaseManifest.ts" +import type { StageApproval } from "./StageApproval.ts" +import type { Workspace } from "./Workspace.ts" + +/** Environment variable holding the one-time password for `publish`; never a CLI flag. */ +export const OTP = "NPM_OTP" + +/** How `publish` waits for the registry to serve an approved version. */ +export const CONFIRM_INTERVAL: Duration.Input = "15 seconds" +export const CONFIRM_TIMEOUT: Duration.Input = "10 minutes" + +export interface ReadinessOptions { + /** dist-tag the release was staged under; must match every staged item's tag. */ + readonly tag: string + /** Assess and print the proposed PR without touching git or GitHub. */ + readonly dryRun?: boolean | undefined +} + +export type ReadinessResult = + /** No public package has an unpublished manifest version in the stage queue. */ + | { readonly _tag: "Idle"; readonly reason: string } + /** + * The manifest already merged on `main` still pins items that sit in the + * queue: that release is authorised and awaiting (or part-way through) + * publication. No new PR is opened until it finishes. + */ + | { readonly _tag: "InProgress"; readonly identity: string; readonly remaining: ReadonlyArray } + /** Some unpublished public packages are not in the queue at all; no manifest can be built. */ + | { + readonly _tag: "Incomplete" + readonly missing: ReadonlyArray<{ readonly name: string; readonly version: string }> + } + | { + readonly _tag: "NotReady" + readonly manifest: ReleaseManifest + readonly identity: string + readonly blockers: ReadonlyArray + readonly pullRequest: Option.Option + } + | { + readonly _tag: "Ready" + readonly manifest: ReleaseManifest + readonly identity: string + readonly pullRequest: SyncResult + } + | { + readonly _tag: "ReadinessDryRun" + readonly manifest: ReleaseManifest + readonly identity: string + readonly readiness: Readiness + readonly title: string + readonly body: string + } + +export interface PublishOptions { + /** The identity printed in the merged publish PR; must equal the identity of the manifest on `main`. */ + readonly expectedIdentity: string + readonly otp: Redacted.Redacted + /** Recheck and print what would be approved without approving anything. */ + readonly dryRun?: boolean | undefined +} + +export type PublishResult = + | { + readonly _tag: "Published" + readonly identity: string + readonly approved: ReadonlyArray + readonly alreadyPublic: ReadonlyArray + /** `manifest.sourceSha`; the workflow deploys the website from it. */ + readonly websiteRevision: string + } + /** Every manifest version was already public; nothing approved. Safe to re-run the website deployment. */ + | { readonly _tag: "AlreadyPublished"; readonly identity: string; readonly websiteRevision: string } + | { + readonly _tag: "PublishDryRun" + readonly identity: string + readonly toApprove: ReadonlyArray + readonly alreadyPublic: ReadonlyArray + } + +/** + * Orchestrates the two halves of the publish flow. + * + * `readiness` (scheduled, and after every Stage run): + * + * 1. `Workspace.packages`, `Registry.listStaged`, and one `Registry.isPublished` + * per public package at its manifest version. The release set is every + * public package whose version is not published. Empty → `Idle`. + * 2. If `MANIFEST_PATH` exists on the checkout and any of its stage ids is in + * the queue → `InProgress`, nothing else happens. + * 3. Any release-set package with no queue item at its version → `Incomplete`. + * 4. `ReleaseManifest.fromStaged` with `sourceSha = Git.lastCommitTouching(LEDGER_PATH)`, + * then `Readiness.assess`. `dryRun` → `ReadinessDryRun` with the proposed + * title and body, no git or GitHub. Otherwise `PublishPullRequest.sync`, + * reported as `NotReady` (with the marked or absent PR) or `Ready`. + * + * `publish` (dispatched by a maintainer after the publish PR merged): + * + * 1. Read and decode `MANIFEST_PATH` from the checkout; its identity must + * equal `expectedIdentity`, otherwise fail before any registry call. + * 2. `Registry.listStaged` and `Registry.isPublished` for every manifest + * package; `Readiness.assess`. `NotReady` → fail naming every blocker; + * nothing is approved. Packages already `public` are verified, not + * approved: this is what makes a retry after partial publication finish + * the same release. + * 3. Nothing left to approve → `AlreadyPublished`. `dryRun` → `PublishDryRun`. + * 4. `StageApproval.approve(stageId, otp)` for each approvable package in + * manifest order, one registry operation each (there is no batch approve; + * publication is not atomic). The first failure stops the loop and fails + * with the approved and remaining packages named. + * 5. Poll `Registry.isPublished` for every approved package every + * `CONFIRM_INTERVAL` until all are served or `CONFIRM_TIMEOUT` elapses; + * on timeout fail naming the unconfirmed packages. Only then `Published`, + * which is the website gate. + * + * Neither half runs `pnpm version`, `pnpm build` or `pnpm stage publish`. + */ +export class Publication extends Context.Service Effect.Effect + readonly publish: (options: PublishOptions) => Effect.Effect +}>()("@effect/release/Publication") { + static readonly layer: Layer.Layer< + Publication, + never, + Git | GitHub | Registry | StageApproval | Workspace | FileSystem.FileSystem | Path.Path + > = Layer.effect(Publication, notImplementedEffect("Publication.layer")) +} diff --git a/packages/tools/release/src/PublishPullRequest.ts b/packages/tools/release/src/PublishPullRequest.ts new file mode 100644 index 0000000000..c42acaf1c4 --- /dev/null +++ b/packages/tools/release/src/PublishPullRequest.ts @@ -0,0 +1,87 @@ +import type * as Effect from "effect/Effect" +import type * as FileSystem from "effect/FileSystem" +import type * as Option from "effect/Option" +import type * as Path from "effect/Path" +import type { ReleaseError } from "./Errors.ts" +import type { Git } from "./Git.ts" +import type { GitHub, PullRequest } from "./GitHub.ts" +import { notImplemented, notImplementedEffect } from "./NotImplemented.ts" +import type { PackageReadiness, Readiness } from "./Readiness.ts" +import type { ReleaseManifest } from "./ReleaseManifest.ts" + +/** Sibling of `changeset-release/main`; one branch per base, force-pushed on every change. */ +export const PUBLISH_BRANCH = "publish-release/main" +export const BASE_BRANCH = "main" +export const COMMIT_MESSAGE = "Publish Packages" +export const TITLE = "Publish Packages" +/** Appended to the title while the release is not approvable. */ +export const NOT_READY_SUFFIX = "[not ready]" + +/** + * HTML comment carrying the manifest identity, ``. + * It is how a readiness run tells whether the open PR already describes this + * exact manifest, so repeated runs are no-ops. + */ +export const IDENTITY_MARKER = "release-manifest" + +/** First paragraph of every publish PR body; the rest is generated. */ +export const BODY_INTRO = + "This PR was opened by the release readiness workflow. Every package below is staged on npm and has passed " + + "the registry's validation. Merging this PR authorises publication of exactly the staged tarballs pinned in " + + "`.release/manifest.json`: nothing is rebuilt or re-versioned. After merging, a maintainer runs the Publish " + + "workflow with the identity below and a one-time password; publication rechecks the whole release first." + +/** + * `Publish Packages` when `manifest.tag` is `latest`, otherwise + * `Publish Packages ()`; with ` [not ready]` appended when `readiness` + * is `NotReady`. + */ +export const title = (_manifest: ReleaseManifest, _readiness: Readiness): string => + notImplemented("PublishPullRequest.title") + +/** + * Markdown body: {@link BODY_INTRO}; the identity marker line; a `## Release` + * section stating the identity, tag and source commit; a `## Packages` table + * with one row per manifest package (`name`, `version`, stage id, state); + * and, when `readiness` is `NotReady`, a `## Blockers` list naming each + * blocker with its detail. Deterministic for a given manifest and readiness. + */ +export const body = (_manifest: ReleaseManifest, _readiness: Readiness): string => + notImplemented("PublishPullRequest.body") + +/** The identity carried by a body's marker line, if present. */ +export const identityFromBody = (_body: string): Option.Option => + notImplemented("PublishPullRequest.identityFromBody") + +export type SyncResult = + | { readonly _tag: "Created"; readonly pullRequest: PullRequest } + | { readonly _tag: "Updated"; readonly pullRequest: PullRequest } + /** The open PR already carries this identity with a ready title; nothing touched. */ + | { readonly _tag: "NoChanges"; readonly pullRequest: PullRequest } + /** Not ready and an open PR exists: its title and body now say so; no git mutation. */ + | { readonly _tag: "Marked"; readonly pullRequest: PullRequest; readonly blockers: ReadonlyArray } + /** Not ready and no open PR: nothing created. */ + | { readonly _tag: "Skipped"; readonly blockers: ReadonlyArray } + +/** + * Creates, refreshes or marks the publish PR for `manifest`: + * + * 1. `GitHub.findPullRequest({ head: PUBLISH_BRANCH, base: BASE_BRANCH })`. + * 2. `readiness` is `NotReady`: with an open PR, `updatePullRequest` with the + * not-ready title and body and return `Marked`; without one, return + * `Skipped`. Git is never touched on this path, so an unready release can + * never be committed as approvable. + * 3. `readiness` is `Ready` and the open PR's body carries this manifest's + * identity and its title is the ready title: `NoChanges`, no git. + * 4. Otherwise remember `Git.headSha`; `Git.resetBranch(PUBLISH_BRANCH, BASE_BRANCH)`; + * write `ReleaseManifest.encode(manifest)` to `MANIFEST_PATH` under the + * workspace root (creating `.release/`); `Git.commitAll(COMMIT_MESSAGE)`; + * `Git.pushForce(PUBLISH_BRANCH)`; then `updatePullRequest` or + * `createPullRequest` with the ready title and body; always, even on + * failure, `Git.checkout` of the remembered SHA. + */ +export const sync = ( + _manifest: ReleaseManifest, + _readiness: Readiness +): Effect.Effect => + notImplementedEffect("PublishPullRequest.sync") diff --git a/packages/tools/release/src/Readiness.ts b/packages/tools/release/src/Readiness.ts new file mode 100644 index 0000000000..eb29b5c42e --- /dev/null +++ b/packages/tools/release/src/Readiness.ts @@ -0,0 +1,56 @@ +import { notImplemented } from "./NotImplemented.ts" +import type { StagedItem } from "./Registry.ts" +import type { ManifestPackage, ReleaseManifest } from "./ReleaseManifest.ts" + +/** + * Registry status words, as observed on `GET /-/stage` items. The registry + * documents none of them; the sets below are the contract's assumption and + * the live probe (EFF-1455 P3) may amend them. Anything outside every set is + * `unknown` and never ready: readiness fails closed on new vocabulary. + */ +export const APPROVABLE_STATUSES: ReadonlySet = new Set(["staged", "awaiting_approval"]) +export const PENDING_STATUSES: ReadonlySet = new Set(["validating"]) +export const BLOCKED_STATUSES: ReadonlySet = new Set(["blocked", "rejected", "deleted"]) + +/** + * - `public`: the registry already serves `name@version`; nothing to approve. + * - `approvable`: the pinned stage id exists at the pinned name and version + * with an approvable status. + * - `pending`: the pinned stage id exists but its scan has not finished. + * - `missing`: no staged item has the pinned id, or the item with that id is + * not `name@version`. If another item exists for the same name and version + * the detail names its id (the release was re-staged; the manifest is stale). + * - `blocked`: the pinned item is blocked, rejected or deleted. + * - `unknown`: the pinned item has no status or one outside every set. + */ +export type PackageState = "public" | "approvable" | "pending" | "missing" | "blocked" | "unknown" + +export interface PackageReadiness extends ManifestPackage { + readonly state: PackageState + /** Human-readable reason, e.g. `status validating` or `staged again as `. */ + readonly detail: string +} + +/** + * `Ready` when every package is `public` or `approvable`. Otherwise + * `NotReady`, with `blockers` listing every package in another state, in + * manifest order. `packages` always lists every manifest package. + */ +export type Readiness = + | { readonly _tag: "Ready"; readonly packages: ReadonlyArray } + | { + readonly _tag: "NotReady" + readonly packages: ReadonlyArray + readonly blockers: ReadonlyArray + } + +export interface ReadinessInput { + readonly manifest: ReleaseManifest + /** The whole stage queue; items outside the manifest are ignored. */ + readonly staged: ReadonlyArray + /** `name@version` keys the registry already serves (`Routing.versionKey`). */ + readonly published: ReadonlySet +} + +/** Pure; assessed against the manifest only, never against the queue at large. */ +export const assess = (_input: ReadinessInput): Readiness => notImplemented("Readiness.assess") diff --git a/packages/tools/release/src/ReleaseManifest.ts b/packages/tools/release/src/ReleaseManifest.ts new file mode 100644 index 0000000000..642b7d3088 --- /dev/null +++ b/packages/tools/release/src/ReleaseManifest.ts @@ -0,0 +1,86 @@ +import type * as Effect from "effect/Effect" +import type { ReleaseError } from "./Errors.ts" +import { notImplemented, notImplementedEffect } from "./NotImplemented.ts" +import type { StagedItem } from "./Registry.ts" +import type { WorkspacePackage } from "./Workspace.ts" + +/** + * The release manifest is the reviewable, committed record of exactly what a + * "Publish Packages" pull request authorises. It pins the complete package + * set, the version of each, and the registry stage id of the uploaded + * tarball, so that neither later pushes to `main` nor unrelated items in the + * stage queue can change what gets published. + * + * It lives at {@link MANIFEST_PATH} on the publish branch and, once the + * publish PR merges, on `main`. `publish` reads it from the checked-out + * `main` and refuses to act on anything else. + */ +export interface ManifestPackage { + readonly name: string + readonly version: string + /** Registry stage id (UUID) of the staged tarball for exactly this version. */ + readonly stageId: string +} + +export interface ReleaseManifest { + readonly schema: typeof SCHEMA_VERSION + /** dist-tag every staged item was uploaded under (`rc` until 4.0 GA). */ + readonly tag: string + /** + * The commit on `main` that introduced these versions: the last first-parent + * commit touching {@link LEDGER_PATH} (`pnpm version -r` writes the ledger, so + * that is the "Version Packages" merge). The website deploys this revision. + */ + readonly sourceSha: string + /** Every public package of the release, sorted by name. */ + readonly packages: ReadonlyArray +} + +export const SCHEMA_VERSION = 1 +export const MANIFEST_PATH = ".release/manifest.json" +export const LEDGER_PATH = ".changeset/ledger.yaml" + +/** Length of {@link identity}: 16 hex characters of the SHA-256 of {@link encode}. */ +export const IDENTITY_LENGTH = 16 + +/** + * Builds the manifest for a staged release. `packages` is the workspace; + * private packages are ignored. Every public package must have exactly one + * staged item at its manifest version whose `tag` is absent or equal to + * `tag`. Fails with a `ReleaseError` naming the package when a public package + * has no such item ("not staged"), has more than one ("ambiguous"), or has a + * staged item at a different version ("stale", mirroring `Routing`). + * Staged items for names outside the workspace are ignored. The result is + * sorted by package name. + */ +export const fromStaged = (_input: { + readonly tag: string + readonly sourceSha: string + readonly packages: ReadonlyArray + readonly staged: ReadonlyArray +}): Effect.Effect => notImplementedEffect("ReleaseManifest.fromStaged") + +/** + * Canonical JSON: two-space indentation, keys in the order `schema`, `tag`, + * `sourceSha`, `packages`, each package as `name`, `version`, `stageId`, + * packages sorted by name, single trailing newline. Deterministic: the same + * manifest always encodes to the same bytes, which is what {@link identity} + * hashes and what the publish PR commits. + */ +export const encode = (_manifest: ReleaseManifest): string => notImplemented("ReleaseManifest.encode") + +/** + * Parses {@link encode} output. Fails with a `ReleaseError` on malformed JSON, + * an unknown `schema`, a missing field, or a package list that is not sorted + * by name (a hand-edited manifest must not slip through). + */ +export const decode = (_text: string): Effect.Effect => + notImplementedEffect("ReleaseManifest.decode") + +/** + * The release identity: the first {@link IDENTITY_LENGTH} hex characters of + * the SHA-256 of {@link encode}. It is what the publish PR body carries, what + * a maintainer passes to `release publish --expect-identity`, and what ties + * the merge authorisation to one exact manifest. + */ +export const identity = (_manifest: ReleaseManifest): string => notImplemented("ReleaseManifest.identity") diff --git a/packages/tools/release/src/StageApproval.ts b/packages/tools/release/src/StageApproval.ts new file mode 100644 index 0000000000..58f23ff398 --- /dev/null +++ b/packages/tools/release/src/StageApproval.ts @@ -0,0 +1,42 @@ +import * as Context from "effect/Context" +import type * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import type * as Option from "effect/Option" +import type * as Redacted from "effect/Redacted" +import type * as HttpClient from "effect/unstable/http/HttpClient" +import type { ReleaseError } from "./Errors.ts" +import { notImplementedEffect } from "./NotImplemented.ts" +import type { StagedItem } from "./Registry.ts" + +/** Environment variable holding the maintainer token used to approve. */ +export const APPROVE_TOKEN = "NPM_APPROVE_TOKEN" + +/** + * The two registry calls that make a staged version public, kept apart from + * the read-only `Registry` because they need a different credential. + * + * Verified against pnpm 11.20's bundled `stage/approve.js` and the npm docs: + * + * - `viewStaged`: `GET /-/stage/` with `Authorization: Bearer `, + * `npm-auth-type: web`, `npm-command: stage`. 404 is `none`; any other + * non-200 status is a `ReleaseError`. + * - `approve`: `POST /-/stage//approve` with the same headers plus + * `npm-otp: `. A 401 whose body carries `authUrl`/`doneUrl` or whose + * `www-authenticate` header mentions `otp` is the registry's proof-of-presence + * challenge; it fails with a `ReleaseError` that says the OTP was rejected + * or missing. Any other non-2xx status fails with the status and body text. + * + * The token comes from `NPM_APPROVE_TOKEN` (a maintainer's granular token on + * a 2FA account; OIDC trust tokens and stage-only tokens cannot approve). A + * missing token fails before any request. The OTP never appears in an error + * message, a log line or a URL. + */ +export class StageApproval extends Context.Service Effect.Effect, ReleaseError> + readonly approve: (id: string, otp: Redacted.Redacted) => Effect.Effect +}>()("@effect/release/StageApproval") { + static readonly layer: Layer.Layer = Layer.effect( + StageApproval, + notImplementedEffect("StageApproval.layer") + ) +} diff --git a/packages/tools/release/test/Publication.test.ts b/packages/tools/release/test/Publication.test.ts new file mode 100644 index 0000000000..d9d6d77742 --- /dev/null +++ b/packages/tools/release/test/Publication.test.ts @@ -0,0 +1,432 @@ +import { Publication } from "@effect/release/Publication" +import * as PublishPullRequest from "@effect/release/PublishPullRequest" +import type { StagedItem } from "@effect/release/Registry" +import * as ReleaseManifest from "@effect/release/ReleaseManifest" +import { versionKey } from "@effect/release/Routing" +import { assert, describe, it } from "@effect/vitest" +import * as Effect from "effect/Effect" +import * as Fiber from "effect/Fiber" +import * as Layer from "effect/Layer" +import * as Path from "effect/Path" +import { TestClock } from "effect/testing" +import { + callNames, + callsTo, + EFFECT_STAGE_ID, + fileSystemLayer, + githubLayer, + gitLayer, + LEDGER_SHA, + makeCalls, + manifest, + manifestQueue, + otp, + packages, + pullRequest, + registryLayer, + stageApprovalLayer, + stagedWithId, + VITEST_STAGE_ID, + workspaceLayer +} from "./utils.ts" + +/** Computed lazily so that an unimplemented member fails the test that needs it, not the whole file. */ +const identity = () => ReleaseManifest.identity(manifest) + +/** The real orchestrator over stubbed git, GitHub, registry, approval, workspace and file system. */ +const app = (options: { + readonly staged?: Array + readonly published?: Set + readonly files?: Map + readonly existing?: ReturnType + readonly failing?: ReadonlySet + /** Whether approving marks the version public in the registry stub (default: yes). */ + readonly publishOnApprove?: boolean +}) => { + const calls = makeCalls() + const published = options.published ?? new Set() + const staged = options.staged ?? [] + const byId = new Map(staged.map((item) => [item.id, item])) + const layer = Publication.layer.pipe( + Layer.provideMerge(Layer.mergeAll( + gitLayer(calls, { headSha: "abc123" }), + githubLayer(calls, options.existing === undefined ? undefined : { existing: options.existing }), + registryLayer(calls, { published, staged }), + stageApprovalLayer(calls, { + items: staged, + failing: options.failing, + onApproved: (id) => { + const item = byId.get(id) + if (item !== undefined && options.publishOnApprove !== false) { + published.add(versionKey(item.packageName, item.version)) + } + } + }), + workspaceLayer(calls, packages), + fileSystemLayer(calls, options.files), + Path.layer + )) + ) + return { calls, layer, published, staged } +} + +const mutationNames = (calls: ReturnType) => + callNames(calls).filter((name) => + name.startsWith("git.") && name !== "git.headSha" && name !== "git.lastCommitTouching" || + name.startsWith("github.create") || name.startsWith("github.update") || + name.startsWith("fs.write") || name.startsWith("fs.makeDirectory") || + name === "approval.approve" + ) + +const onMain = () => new Map([[ReleaseManifest.MANIFEST_PATH, ReleaseManifest.encode(manifest)]]) + +describe("Publication.readiness", () => { + it.effect("is Idle when every public version is already published", () => + Effect.gen(function*() { + const { calls, layer } = app({ + published: new Set([versionKey("effect", "4.0.0-rc.117"), versionKey("@effect/vitest", "4.0.0-rc.117")]) + }) + const result = yield* Effect.provide(Effect.flatMap(Publication, (p) => p.readiness({ tag: "rc" })), layer) + assert.strictEqual(result._tag, "Idle") + assert.deepStrictEqual(mutationNames(calls), []) + assert.deepStrictEqual(callsTo(calls, "github.findPullRequest"), []) + })) + + it.effect("is Idle when nothing is staged and nothing is published (a Stage run is still due)", () => + Effect.gen(function*() { + const { calls, layer } = app({}) + const result = yield* Effect.provide(Effect.flatMap(Publication, (p) => p.readiness({ tag: "rc" })), layer) + assert.oneOf(result._tag, ["Idle", "Incomplete"]) + assert.deepStrictEqual(mutationNames(calls), []) + })) + + it.effect("reports Incomplete when an unpublished public package has no staged upload", () => + Effect.gen(function*() { + const { calls, layer } = app({ staged: [stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117")] }) + const result = yield* Effect.provide(Effect.flatMap(Publication, (p) => p.readiness({ tag: "rc" })), layer) + assert.strictEqual(result._tag, "Incomplete") + if (result._tag === "Incomplete") { + assert.deepStrictEqual(result.missing, [{ name: "effect", version: "4.0.0-rc.117" }]) + } + assert.deepStrictEqual(mutationNames(calls), []) + assert.deepStrictEqual(callsTo(calls, "github.findPullRequest"), []) + })) + + it.effect("leaves an authorised release alone while its pinned items are still in the queue", () => + Effect.gen(function*() { + const { calls, layer } = app({ + staged: [stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117")], + published: new Set([versionKey("@effect/vitest", "4.0.0-rc.117")]), + files: onMain() + }) + const result = yield* Effect.provide(Effect.flatMap(Publication, (p) => p.readiness({ tag: "rc" })), layer) + assert.strictEqual(result._tag, "InProgress") + if (result._tag === "InProgress") { + assert.strictEqual(result.identity, identity()) + assert.deepStrictEqual(result.remaining.map((pkg) => pkg.name), ["effect"]) + } + assert.deepStrictEqual(mutationNames(calls), []) + assert.deepStrictEqual(callsTo(calls, "github.findPullRequest"), []) + })) + + it.effect("opens the publish PR with the manifest once every upload is approvable", () => + Effect.gen(function*() { + const { calls, layer } = app({ staged: [...manifestQueue] }) + const result = yield* Effect.provide(Effect.flatMap(Publication, (p) => p.readiness({ tag: "rc" })), layer) + assert.strictEqual(result._tag, "Ready") + if (result._tag === "Ready") { + assert.strictEqual(result.identity, identity()) + assert.deepStrictEqual(result.manifest, manifest) + assert.strictEqual(result.pullRequest._tag, "Created") + } + assert.deepStrictEqual(callsTo(calls, "git.lastCommitTouching")[0].args, [ReleaseManifest.LEDGER_PATH]) + assert.deepStrictEqual(callsTo(calls, "fs.writeFileString")[0].args, [ + ReleaseManifest.MANIFEST_PATH, + ReleaseManifest.encode(manifest) + ]) + assert.lengthOf(callsTo(calls, "github.createPullRequest"), 1) + assert.deepStrictEqual(callsTo(calls, "approval.approve"), []) + })) + + it.effect("is idempotent: a second run against the same queue changes nothing", () => + Effect.gen(function*() { + const existing = pullRequest({ + headRef: "publish-release/main", + title: "Publish Packages (rc)", + body: PublishPullRequest.body( + manifest, + { _tag: "Ready", packages: manifest.packages.map((pkg) => ({ ...pkg, state: "approvable", detail: "" })) } + ) + }) + const { calls, layer } = app({ staged: [...manifestQueue], existing }) + const result = yield* Effect.provide(Effect.flatMap(Publication, (p) => p.readiness({ tag: "rc" })), layer) + assert.strictEqual(result._tag, "Ready") + if (result._tag === "Ready") { + assert.strictEqual(result.pullRequest._tag, "NoChanges") + } + assert.deepStrictEqual(mutationNames(calls), []) + })) + + it.effect("opens nothing while an upload is still validating", () => + Effect.gen(function*() { + const { calls, layer } = app({ + staged: [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117", "validating"), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") + ] + }) + const result = yield* Effect.provide(Effect.flatMap(Publication, (p) => p.readiness({ tag: "rc" })), layer) + assert.strictEqual(result._tag, "NotReady") + if (result._tag === "NotReady") { + assert.deepStrictEqual(result.blockers.map((pkg) => [pkg.name, pkg.state]), [["effect", "pending"]]) + assert.isTrue(result.pullRequest._tag === "None") + } + assert.deepStrictEqual(mutationNames(calls), []) + })) + + it.effect("marks the open PR when a previously ready release regresses", () => + Effect.gen(function*() { + const existing = pullRequest({ number: 8500, headRef: "publish-release/main", title: "Publish Packages (rc)" }) + const { calls, layer } = app({ + staged: [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117", "blocked"), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") + ], + existing + }) + const result = yield* Effect.provide(Effect.flatMap(Publication, (p) => p.readiness({ tag: "rc" })), layer) + assert.strictEqual(result._tag, "NotReady") + if (result._tag === "NotReady") { + assert.strictEqual(result.pullRequest._tag, "Some") + } + assert.deepStrictEqual(mutationNames(calls), ["github.updatePullRequest"]) + const [, input] = callsTo(calls, "github.updatePullRequest")[0].args as [number, { title: string }] + assert.strictEqual(input.title, "Publish Packages (rc) [not ready]") + })) + + it.effect("fails before GitHub when a stale version sits in the queue", () => + Effect.gen(function*() { + const { calls, layer } = app({ + staged: [...manifestQueue, stagedWithId("7c6b5a49-3827-4165-9f0e-1d2c3b4a5968", "effect", "4.0.0-rc.116")] + }) + const error = yield* Effect.flip( + Effect.provide(Effect.flatMap(Publication, (p) => p.readiness({ tag: "rc" })), layer) + ) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, "4.0.0-rc.116") + assert.deepStrictEqual(mutationNames(calls), []) + assert.deepStrictEqual(callsTo(calls, "github.findPullRequest"), []) + })) + + it.effect("previews the PR on a dry run without touching git or GitHub", () => + Effect.gen(function*() { + const { calls, layer } = app({ staged: [...manifestQueue] }) + const result = yield* Effect.provide( + Effect.flatMap(Publication, (p) => p.readiness({ tag: "rc", dryRun: true })), + layer + ) + assert.strictEqual(result._tag, "ReadinessDryRun") + if (result._tag === "ReadinessDryRun") { + assert.strictEqual(result.identity, identity()) + assert.strictEqual(result.title, "Publish Packages (rc)") + assert.include(result.body, identity()) + } + assert.deepStrictEqual( + callNames(calls).filter((name) => name.startsWith("github.") || name.startsWith("fs.write")), + [] + ) + assert.deepStrictEqual(mutationNames(calls), []) + })) +}) + +const publish = (options: { readonly expectedIdentity?: string; readonly dryRun?: boolean } = {}) => + Effect.flatMap( + Publication, + (p) => p.publish({ expectedIdentity: options.expectedIdentity ?? identity(), otp, dryRun: options.dryRun }) + ) + +describe("Publication.publish", () => { + it.effect("approves every pinned upload in manifest order and confirms each is public", () => + Effect.gen(function*() { + const { calls, layer } = app({ staged: [...manifestQueue], files: onMain() }) + const result = yield* Effect.provide(publish(), layer) + assert.strictEqual(result._tag, "Published") + if (result._tag === "Published") { + assert.strictEqual(result.identity, identity()) + assert.deepStrictEqual(result.approved.map((pkg) => pkg.name), ["@effect/vitest", "effect"]) + assert.deepStrictEqual(result.alreadyPublic, []) + assert.strictEqual(result.websiteRevision, LEDGER_SHA) + } + assert.deepStrictEqual(callsTo(calls, "approval.approve").map((call) => call.args), [ + [VITEST_STAGE_ID, "123456"], + [EFFECT_STAGE_ID, "123456"] + ]) + const confirmed = callsTo(calls, "registry.isPublished").map((call) => call.args.join("@")) + assert.include(confirmed, "effect@4.0.0-rc.117") + assert.include(confirmed, "@effect/vitest@4.0.0-rc.117") + assert.deepStrictEqual( + callNames(calls).filter((name) => name.startsWith("pnpm.") || name.startsWith("github.")), + [] + ) + })) + + it.effect("refuses a manifest whose identity is not the one that was approved, before any registry call", () => + Effect.gen(function*() { + const { calls, layer } = app({ staged: [...manifestQueue], files: onMain() }) + const error = yield* Effect.flip(Effect.provide(publish({ expectedIdentity: "0000000000000000" }), layer)) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, "0000000000000000") + assert.include(error.message, identity()) + assert.deepStrictEqual( + callNames(calls).filter((name) => name.startsWith("registry.") || name.startsWith("approval.")), + [] + ) + })) + + it.effect("fails when no manifest has been merged", () => + Effect.gen(function*() { + const { calls, layer } = app({ staged: [...manifestQueue] }) + const error = yield* Effect.flip(Effect.provide(publish(), layer)) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, ReleaseManifest.MANIFEST_PATH) + assert.deepStrictEqual(callsTo(calls, "approval.approve"), []) + })) + + it.effect("rechecks the whole release and approves nothing while any upload is not ready", () => + Effect.gen(function*() { + const { calls, layer } = app({ + staged: [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117", "validating"), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") + ], + files: onMain() + }) + const error = yield* Effect.flip(Effect.provide(publish(), layer)) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, "effect") + assert.include(error.message, "validating") + assert.deepStrictEqual(callsTo(calls, "approval.approve"), []) + })) + + it.effect("approves nothing when a pinned upload has disappeared from the queue", () => + Effect.gen(function*() { + const { calls, layer } = app({ + staged: [stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117")], + files: onMain() + }) + const error = yield* Effect.flip(Effect.provide(publish(), layer)) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, "effect") + assert.deepStrictEqual(callsTo(calls, "approval.approve"), []) + })) + + it.effect("ignores newer queue contents: only the pinned ids are ever approved", () => + Effect.gen(function*() { + const restaged = "3b2a1908-7f6e-4d5c-9b4a-3f2e1d0c9b8a" + const { calls, layer } = app({ + staged: [...manifestQueue, stagedWithId(restaged, "effect", "4.0.0-rc.118")], + files: onMain() + }) + yield* Effect.provide(publish(), layer) + assert.deepStrictEqual(callsTo(calls, "approval.approve").map((call) => call.args[0]), [ + VITEST_STAGE_ID, + EFFECT_STAGE_ID + ]) + })) + + it.effect("finishes a partially published release: verifies public versions and approves only the rest", () => + Effect.gen(function*() { + const { calls, layer } = app({ + staged: [stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117")], + published: new Set([versionKey("@effect/vitest", "4.0.0-rc.117")]), + files: onMain() + }) + const result = yield* Effect.provide(publish(), layer) + assert.strictEqual(result._tag, "Published") + if (result._tag === "Published") { + assert.deepStrictEqual(result.approved.map((pkg) => pkg.name), ["effect"]) + assert.deepStrictEqual(result.alreadyPublic.map((pkg) => pkg.name), ["@effect/vitest"]) + assert.strictEqual(result.websiteRevision, LEDGER_SHA) + } + assert.deepStrictEqual(callsTo(calls, "approval.approve").map((call) => call.args[0]), [EFFECT_STAGE_ID]) + })) + + it.effect("approves nothing and still reports the website revision when everything is already public", () => + Effect.gen(function*() { + const { calls, layer } = app({ + published: new Set([versionKey("effect", "4.0.0-rc.117"), versionKey("@effect/vitest", "4.0.0-rc.117")]), + files: onMain() + }) + const result = yield* Effect.provide(publish(), layer) + assert.deepStrictEqual(result, { _tag: "AlreadyPublished", identity: identity(), websiteRevision: LEDGER_SHA }) + assert.deepStrictEqual(callsTo(calls, "approval.approve"), []) + })) + + it.effect("stops at the first failed approval and names what is approved and what remains", () => + Effect.gen(function*() { + const { calls, layer } = app({ + staged: [...manifestQueue], + files: onMain(), + failing: new Set([VITEST_STAGE_ID]) + }) + const error = yield* Effect.flip(Effect.provide(publish(), layer)) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, "@effect/vitest") + assert.include(error.message, "effect") + assert.deepStrictEqual(callsTo(calls, "approval.approve").map((call) => call.args[0]), [VITEST_STAGE_ID]) + })) + + it.effect("waits for the registry to serve an approved version before reporting success", () => + Effect.gen(function*() { + const { calls, layer, published } = app({ staged: [...manifestQueue], files: onMain(), publishOnApprove: false }) + const fiber = yield* Effect.forkChild(Effect.provide(publish(), layer)) + yield* TestClock.adjust("15 seconds") + const before = callsTo(calls, "registry.isPublished").length + yield* TestClock.adjust("15 seconds") + assert.isAbove(callsTo(calls, "registry.isPublished").length, before) + published.add(versionKey("effect", "4.0.0-rc.117")) + published.add(versionKey("@effect/vitest", "4.0.0-rc.117")) + yield* TestClock.adjust("15 seconds") + const result = yield* Fiber.join(fiber) + assert.strictEqual(result._tag, "Published") + })) + + it.effect("fails naming the unconfirmed packages when the registry never serves an approved version", () => + Effect.gen(function*() { + const { layer } = app({ staged: [...manifestQueue], files: onMain(), publishOnApprove: false }) + const fiber = yield* Effect.forkChild(Effect.flip(Effect.provide(publish(), layer))) + yield* TestClock.adjust("11 minutes") + const error = yield* Fiber.join(fiber) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, "effect") + assert.include(error.message, "@effect/vitest") + })) + + it.effect("previews the approvals on a dry run without approving", () => + Effect.gen(function*() { + const { calls, layer } = app({ + staged: [stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117")], + published: new Set([versionKey("@effect/vitest", "4.0.0-rc.117")]), + files: onMain() + }) + const result = yield* Effect.provide(publish({ dryRun: true }), layer) + assert.strictEqual(result._tag, "PublishDryRun") + if (result._tag === "PublishDryRun") { + assert.deepStrictEqual(result.toApprove.map((pkg) => pkg.name), ["effect"]) + assert.deepStrictEqual(result.alreadyPublic.map((pkg) => pkg.name), ["@effect/vitest"]) + } + assert.deepStrictEqual(callsTo(calls, "approval.approve"), []) + })) + + it.effect("never versions, builds or stages at publication time", () => + Effect.gen(function*() { + const { calls, layer } = app({ staged: [...manifestQueue], files: onMain() }) + yield* Effect.provide(publish(), layer) + assert.deepStrictEqual( + callNames(calls).filter((name) => + name.startsWith("pnpm.") || name.startsWith("git.") || name.startsWith("github.") + ), + [] + ) + })) +}) diff --git a/packages/tools/release/test/PublishCli.test.ts b/packages/tools/release/test/PublishCli.test.ts new file mode 100644 index 0000000000..282ca2e923 --- /dev/null +++ b/packages/tools/release/test/PublishCli.test.ts @@ -0,0 +1,157 @@ +import { cli } from "@effect/release" +import { Publication, type PublishOptions, type ReadinessOptions } from "@effect/release/Publication" +import { Release } from "@effect/release/Release" +import { assert, describe, it } from "@effect/vitest" +import * as ConfigProvider from "effect/ConfigProvider" +import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" +import * as Layer from "effect/Layer" +import * as Path from "effect/Path" +import * as Redacted from "effect/Redacted" +import * as Stdio from "effect/Stdio" +import * as Terminal from "effect/Terminal" +import { TestConsole } from "effect/testing" +import * as CliOutput from "effect/unstable/cli/CliOutput" +import * as Command from "effect/unstable/cli/Command" +import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner" +import { LEDGER_SHA } from "./utils.ts" + +const cliEnvironment = (env: Record) => + Layer.mergeAll( + FileSystem.layerNoop({}), + Path.layer, + Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => Effect.die("no child processes in these tests")) + ), + Stdio.layerTest({}), + TestConsole.layer, + CliOutput.layer(CliOutput.defaultFormatter({ colors: false })), + ConfigProvider.layer(ConfigProvider.fromEnv({ env })), + Layer.succeed( + Terminal.Terminal, + Terminal.make({ + columns: Effect.succeed(80), + rows: Effect.succeed(24), + readInput: Effect.die("unused"), + readLine: Effect.die("unused"), + display: () => Effect.void + }) + ) + ) + +/** Records what the CLI asks the orchestrator for; the orchestrator itself is tested separately. */ +const appLayer = (env: Record) => { + const readinessCalls: Array = [] + const publishCalls: Array<{ readonly expectedIdentity: string; readonly otp: string; readonly dryRun: boolean }> = [] + const layer = Layer.mergeAll( + Layer.succeed( + Publication, + Publication.of({ + readiness: (options) => + Effect.sync(() => { + readinessCalls.push(options) + return { _tag: "Idle", reason: "nothing staged" } as const + }), + publish: (options: PublishOptions) => + Effect.sync(() => { + publishCalls.push({ + expectedIdentity: options.expectedIdentity, + otp: Redacted.value(options.otp), + dryRun: options.dryRun === true + }) + return { + _tag: "AlreadyPublished", + identity: options.expectedIdentity, + websiteRevision: LEDGER_SHA + } as const + }) + }) + ), + Layer.succeed( + Release, + Release.of({ + plan: Effect.die("unused"), + route: Effect.die("unused"), + run: () => Effect.die("unused") + }) + ) + ).pipe(Layer.provideMerge(cliEnvironment(env))) + return { readinessCalls, publishCalls, layer } +} + +const run = (args: ReadonlyArray) => Command.runWith(cli, { version: "0.0.0", renderErrors: false })(args) + +describe("release readiness", () => { + it.effect("assesses the queue for the given tag and prints the result as JSON", () => + Effect.gen(function*() { + const { layer, readinessCalls } = appLayer({}) + yield* run(["readiness", "--tag", "rc"]).pipe(Effect.provide(layer)) + assert.deepStrictEqual(readinessCalls, [{ tag: "rc", dryRun: false }]) + const printed = JSON.parse((yield* TestConsole.logLines).join("\n")) as { _tag: string } + assert.strictEqual(printed._tag, "Idle") + })) + + it.effect("passes --dry-run through", () => + Effect.gen(function*() { + const { layer, readinessCalls } = appLayer({}) + yield* run(["readiness", "--tag", "rc", "--dry-run"]).pipe(Effect.provide(layer)) + assert.deepStrictEqual(readinessCalls, [{ tag: "rc", dryRun: true }]) + })) + + it.effect("requires --tag", () => + Effect.gen(function*() { + const { layer, readinessCalls } = appLayer({}) + const error = yield* Effect.flip(run(["readiness"]).pipe(Effect.provide(layer))) + assert.notStrictEqual((error as { _tag: string })._tag, "ReleaseError") + assert.deepStrictEqual(readinessCalls, []) + })) +}) + +describe("release publish", () => { + it.effect("reads the OTP from the environment, never from argv, and prints the result as JSON", () => + Effect.gen(function*() { + const { layer, publishCalls } = appLayer({ NPM_OTP: "654321" }) + yield* run(["publish", "--expect-identity", "0123456789abcdef"]).pipe(Effect.provide(layer)) + assert.deepStrictEqual(publishCalls, [{ expectedIdentity: "0123456789abcdef", otp: "654321", dryRun: false }]) + const printed = JSON.parse((yield* TestConsole.logLines).join("\n")) as { _tag: string; websiteRevision: string } + assert.strictEqual(printed._tag, "AlreadyPublished") + assert.strictEqual(printed.websiteRevision, LEDGER_SHA) + })) + + it.effect("rejects an --otp flag", () => + Effect.gen(function*() { + const { layer, publishCalls } = appLayer({ NPM_OTP: "654321" }) + const error = yield* Effect.flip( + run(["publish", "--expect-identity", "0123456789abcdef", "--otp", "654321"]).pipe(Effect.provide(layer)) + ) + assert.exists(error) + assert.deepStrictEqual(publishCalls, []) + })) + + it.effect("fails before publishing when NPM_OTP is not set, and names the variable", () => + Effect.gen(function*() { + const { layer, publishCalls } = appLayer({}) + const error = yield* Effect.flip( + run(["publish", "--expect-identity", "0123456789abcdef"]).pipe(Effect.provide(layer)) + ) + assert.strictEqual((error as { _tag: string })._tag, "ReleaseError") + assert.include((error as Error).message, "NPM_OTP") + assert.deepStrictEqual(publishCalls, []) + })) + + it.effect("requires --expect-identity", () => + Effect.gen(function*() { + const { layer, publishCalls } = appLayer({ NPM_OTP: "654321" }) + const error = yield* Effect.flip(run(["publish"]).pipe(Effect.provide(layer))) + assert.exists(error) + assert.deepStrictEqual(publishCalls, []) + })) + + it.effect("passes --dry-run through", () => + Effect.gen(function*() { + const { layer, publishCalls } = appLayer({ NPM_OTP: "654321" }) + yield* run(["publish", "--expect-identity", "0123456789abcdef", "--dry-run"]).pipe(Effect.provide(layer)) + assert.deepStrictEqual(publishCalls, [{ expectedIdentity: "0123456789abcdef", otp: "654321", dryRun: true }]) + })) +}) diff --git a/packages/tools/release/test/PublishPullRequest.test.ts b/packages/tools/release/test/PublishPullRequest.test.ts new file mode 100644 index 0000000000..888e3c387f --- /dev/null +++ b/packages/tools/release/test/PublishPullRequest.test.ts @@ -0,0 +1,246 @@ +import * as PublishPullRequest from "@effect/release/PublishPullRequest" +import * as Readiness from "@effect/release/Readiness" +import * as ReleaseManifest from "@effect/release/ReleaseManifest" +import { assert, describe, it } from "@effect/vitest" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as Option from "effect/Option" +import * as Path from "effect/Path" +import { + callNames, + callsTo, + EFFECT_STAGE_ID, + fileSystemLayer, + githubLayer, + gitLayer, + LEDGER_SHA, + makeCalls, + manifest, + manifestQueue, + pullRequest, + stagedWithId, + VITEST_STAGE_ID +} from "./utils.ts" + +// Computed lazily so that an unimplemented member fails the test that needs it, not the whole file. +const ready = () => Readiness.assess({ manifest, staged: manifestQueue, published: new Set() }) +const notReady = () => + Readiness.assess({ + manifest, + staged: [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117", "validating"), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") + ], + published: new Set() + }) +const identity = () => ReleaseManifest.identity(manifest) +const marker = () => `` + +describe("PublishPullRequest.title", () => { + it("names the dist-tag and flags an unready release", () => { + assert.strictEqual(PublishPullRequest.title(manifest, ready()), "Publish Packages (rc)") + assert.strictEqual(PublishPullRequest.title(manifest, notReady()), "Publish Packages (rc) [not ready()]") + assert.strictEqual(PublishPullRequest.title({ ...manifest, tag: "latest" }, ready()), "Publish Packages") + }) +}) + +describe("PublishPullRequest.body", () => { + it("pins the identity(), the source commit and every package with its stage id", () => { + const body = PublishPullRequest.body(manifest, ready()) + assert.isTrue(body.startsWith(PublishPullRequest.BODY_INTRO)) + assert.include(body, marker()) + assert.include(body, "## Release") + assert.include(body, identity()) + assert.include(body, LEDGER_SHA) + assert.include(body, "`rc`") + assert.include(body, "## Packages") + for (const pkg of manifest.packages) { + assert.include(body, pkg.name) + assert.include(body, pkg.version) + assert.include(body, pkg.stageId) + } + assert.include(body, "approvable") + assert.notInclude(body, "## Blockers") + assert.strictEqual(body, PublishPullRequest.body(manifest, ready())) + assert.deepStrictEqual(PublishPullRequest.identityFromBody(body), Option.some(identity())) + }) + + it("lists blockers when the release is not ready()", () => { + const body = PublishPullRequest.body(manifest, notReady()) + assert.include(body, marker()) + assert.include(body, "## Blockers") + assert.include(body, "effect") + assert.include(body, "validating") + }) + + it("finds no identity in a body without the marker", () => { + assert.deepStrictEqual(PublishPullRequest.identityFromBody("old body"), Option.none()) + assert.deepStrictEqual(PublishPullRequest.identityFromBody(``), Option.none()) + }) +}) + +const environment = (calls: ReturnType, files?: Map) => + Layer.mergeAll(fileSystemLayer(calls, files), Path.layer) + +describe("PublishPullRequest.sync", () => { + it.effect("commits the manifest on the publish branch and opens the PR when none exists", () => + Effect.gen(function*() { + const calls = makeCalls() + const files = new Map() + const result = yield* PublishPullRequest.sync(manifest, ready()).pipe( + Effect.provide( + Layer.mergeAll(gitLayer(calls, { headSha: "abc123" }), githubLayer(calls), environment(calls, files)) + ) + ) + assert.strictEqual(result._tag, "Created") + + const names = callNames(calls) + const order = [ + "git.resetBranch", + "fs.writeFileString", + "git.commitAll", + "git.pushForce", + "github.createPullRequest" + ] + const positions = order.map((name) => names.indexOf(name)) + assert.deepStrictEqual([...positions].sort((a, b) => a - b), positions, names.join(",")) + assert.isTrue(positions.every((index) => index !== -1), names.join(",")) + assert.strictEqual(names.at(-1), "git.checkout") + + assert.deepStrictEqual(callsTo(calls, "git.resetBranch")[0].args, ["publish-release/main", "main"]) + assert.deepStrictEqual(callsTo(calls, "fs.writeFileString")[0].args, [ + ReleaseManifest.MANIFEST_PATH, + ReleaseManifest.encode(manifest) + ]) + assert.deepStrictEqual(callsTo(calls, "git.commitAll")[0].args, ["Publish Packages"]) + assert.deepStrictEqual(callsTo(calls, "git.pushForce")[0].args, ["publish-release/main"]) + assert.deepStrictEqual(callsTo(calls, "git.checkout")[0].args, ["abc123"]) + assert.deepStrictEqual(callsTo(calls, "github.findPullRequest")[0].args, [{ + head: "publish-release/main", + base: "main" + }]) + const [input] = callsTo(calls, "github.createPullRequest")[0].args as [ + { head: string; base: string; title: string; body: string } + ] + assert.strictEqual(input.head, "publish-release/main") + assert.strictEqual(input.base, "main") + assert.strictEqual(input.title, "Publish Packages (rc)") + assert.include(input.body, marker()) + assert.strictEqual(files.get(ReleaseManifest.MANIFEST_PATH), ReleaseManifest.encode(manifest)) + })) + + it.effect("is a no-op when the open PR already carries this identity", () => + Effect.gen(function*() { + const calls = makeCalls() + const existing = pullRequest({ + headRef: "publish-release/main", + title: "Publish Packages (rc)", + body: PublishPullRequest.body(manifest, ready()) + }) + const result = yield* PublishPullRequest.sync(manifest, ready()).pipe( + Effect.provide(Layer.mergeAll(gitLayer(calls), githubLayer(calls, { existing }), environment(calls))) + ) + assert.strictEqual(result._tag, "NoChanges") + assert.deepStrictEqual(callNames(calls).filter((name) => !name.startsWith("github.findPullRequest")), []) + })) + + it.effect("refreshes the branch and the PR when the open PR describes another manifest", () => + Effect.gen(function*() { + const calls = makeCalls() + const stale = { + ...manifest, + packages: [manifest.packages[0], { ...manifest.packages[1], version: "4.0.0-rc.116" }] + } + const existing = pullRequest({ + number: 8500, + headRef: "publish-release/main", + title: "Publish Packages (rc)", + body: PublishPullRequest.body(stale, Readiness.assess({ manifest: stale, staged: [], published: new Set() })) + }) + const result = yield* PublishPullRequest.sync(manifest, ready()).pipe( + Effect.provide(Layer.mergeAll(gitLayer(calls), githubLayer(calls, { existing }), environment(calls))) + ) + assert.strictEqual(result._tag, "Updated") + assert.lengthOf(callsTo(calls, "git.pushForce"), 1) + assert.deepStrictEqual(callsTo(calls, "github.createPullRequest"), []) + const [number, input] = callsTo(calls, "github.updatePullRequest")[0].args as [ + number, + { title: string; body: string } + ] + assert.strictEqual(number, 8500) + assert.strictEqual(input.title, "Publish Packages (rc)") + assert.include(input.body, marker()) + })) + + it.effect("re-marks a previously unready PR as ready()", () => + Effect.gen(function*() { + const calls = makeCalls() + const existing = pullRequest({ + headRef: "publish-release/main", + title: "Publish Packages (rc) [not ready()]", + body: PublishPullRequest.body(manifest, notReady()) + }) + const result = yield* PublishPullRequest.sync(manifest, ready()).pipe( + Effect.provide(Layer.mergeAll(gitLayer(calls), githubLayer(calls, { existing }), environment(calls))) + ) + assert.strictEqual(result._tag, "Updated") + const [, input] = callsTo(calls, "github.updatePullRequest")[0].args as [number, { title: string; body: string }] + assert.strictEqual(input.title, "Publish Packages (rc)") + assert.notInclude(input.body, "## Blockers") + })) + + it.effect("marks an open PR as not ready() without touching git", () => + Effect.gen(function*() { + const calls = makeCalls() + const existing = pullRequest({ + number: 8500, + headRef: "publish-release/main", + title: "Publish Packages (rc)", + body: PublishPullRequest.body(manifest, ready()) + }) + const result = yield* PublishPullRequest.sync(manifest, notReady()).pipe( + Effect.provide(Layer.mergeAll(gitLayer(calls), githubLayer(calls, { existing }), environment(calls))) + ) + assert.strictEqual(result._tag, "Marked") + if (result._tag === "Marked") { + assert.deepStrictEqual(result.blockers.map((pkg) => pkg.name), ["effect"]) + } + assert.deepStrictEqual(callNames(calls).filter((name) => name.startsWith("git.") || name.startsWith("fs.")), []) + const [number, input] = callsTo(calls, "github.updatePullRequest")[0].args as [ + number, + { title: string; body: string } + ] + assert.strictEqual(number, 8500) + assert.strictEqual(input.title, "Publish Packages (rc) [not ready()]") + assert.include(input.body, "## Blockers") + assert.include(input.body, "validating") + })) + + it.effect("creates nothing while the release is not ready()", () => + Effect.gen(function*() { + const calls = makeCalls() + const result = yield* PublishPullRequest.sync(manifest, notReady()).pipe( + Effect.provide(Layer.mergeAll(gitLayer(calls), githubLayer(calls), environment(calls))) + ) + assert.strictEqual(result._tag, "Skipped") + assert.deepStrictEqual(callNames(calls), ["github.findPullRequest"]) + })) + + it.effect("checks the original commit back out when the push fails", () => + Effect.gen(function*() { + const calls = makeCalls() + const error = yield* Effect.flip( + PublishPullRequest.sync(manifest, ready()).pipe( + Effect.provide(Layer.mergeAll( + gitLayer(calls, { headSha: "abc123", pushFailure: Effect.fail(new Error("push rejected")) }), + githubLayer(calls), + environment(calls) + )) + ) + ) + assert.exists(error) + assert.deepStrictEqual(callsTo(calls, "git.checkout")[0].args, ["abc123"]) + assert.deepStrictEqual(callsTo(calls, "github.createPullRequest"), []) + assert.strictEqual(callNames(calls).at(-1), "git.checkout") + })) +}) diff --git a/packages/tools/release/test/PublishWorkflow.test.ts b/packages/tools/release/test/PublishWorkflow.test.ts new file mode 100644 index 0000000000..dfb856ad71 --- /dev/null +++ b/packages/tools/release/test/PublishWorkflow.test.ts @@ -0,0 +1,185 @@ +import { assert, describe, it } from "@effect/vitest" +import { readFile } from "node:fs/promises" +import { parse } from "yaml" + +interface Step { + readonly id?: string + readonly name?: string + readonly uses?: string + readonly if?: string + readonly run?: string + readonly env?: Record + readonly with?: Record +} + +interface Job { + readonly if?: string + readonly env?: Record + readonly permissions?: Record + readonly steps?: ReadonlyArray +} + +interface Workflow { + readonly on?: Record + readonly env?: Record + readonly concurrency?: { readonly group?: string; readonly "cancel-in-progress"?: boolean } + readonly permissions?: Record + readonly jobs: Record +} + +const workflows = new URL("../../../../.github/workflows/", import.meta.url) + +const load = async (file: string) => parse(await readFile(new URL(file, workflows), "utf8")) as Workflow + +const secretReferences = (value: unknown, path: ReadonlyArray = []): Array => { + if (typeof value === "string") { + return value.includes("secrets.") ? [[path.join("."), value]] : [] + } + if (Array.isArray(value)) { + return value.flatMap((item, index) => secretReferences(item, [...path, String(index)])) + } + if (value !== null && typeof value === "object") { + return Object.entries(value).flatMap(([key, item]) => secretReferences(item, [...path, key])) + } + return [] +} + +const buildCommands = ["scripts/set-strip-internal.mjs", "pnpm codemod", "pnpm build", "pnpm version", "stage publish"] + +const assertCommonSafety = (name: string, workflow: Workflow) => { + assert.deepStrictEqual(workflow.permissions, {}, `${name}: top-level permissions`) + assert.deepStrictEqual(secretReferences(workflow.env, ["env"]), [], `${name}: workflow env secrets`) + assert.strictEqual(workflow.concurrency?.["cancel-in-progress"], false, `${name}: cancel-in-progress`) + for (const [jobName, job] of Object.entries(workflow.jobs)) { + assert.include(job.if, "github.repository_owner == 'Effect-Ts'", `${jobName}: owner guard`) + assert.deepStrictEqual(secretReferences(job.env, ["jobs", jobName, "env"]), [], `${jobName}: job env secrets`) + assert.notProperty(job.permissions ?? {}, "id-token", `${jobName}: must not mint OIDC tokens`) + const install = job.steps?.find((step) => step.uses === "./.github/actions/setup") + assert.exists(install, `${jobName}: install step`) + assert.isUndefined(install.env, `${jobName}: install step must not inherit step secrets`) + for (const checkout of job.steps?.filter((step) => step.uses?.startsWith("actions/checkout@")) ?? []) { + assert.strictEqual(checkout.with?.["persist-credentials"], false, `${jobName}: checkout persists credentials`) + assert.notProperty(checkout.with ?? {}, "token", `${jobName}: checkout receives a token`) + } + for (const command of buildCommands) { + assert.isFalse( + job.steps?.some((step) => step.run?.includes(command)) ?? false, + `${jobName}: must not run ${command}; nothing is rebuilt or re-versioned after staging` + ) + } + } +} + +describe("release readiness workflow", () => { + it("runs on a schedule and on demand, with the stage token and the PAT confined to the readiness step", async () => { + const workflow = await load("release-readiness.yml") + assertCommonSafety("release-readiness", workflow) + + assert.exists(workflow.on?.schedule, "schedule trigger") + assert.property(workflow.on ?? {}, "workflow_dispatch") + assert.notProperty(workflow.on ?? {}, "push") + + assert.deepStrictEqual(Object.keys(workflow.jobs), ["readiness"]) + const job = workflow.jobs.readiness + assert.deepStrictEqual(job.permissions, { contents: "write", "pull-requests": "write" }) + + const step = job.steps?.find((step) => step.run?.includes("release readiness")) + assert.exists(step, "readiness step") + assert.include(step.run, "gh auth setup-git") + assert.include(step.run, "release readiness --tag rc") + assert.deepStrictEqual(Object.keys(step.env ?? {}).sort(), ["GH_TOKEN", "NPM_STAGE_TOKEN"]) + assert.include(String(step.env?.GH_TOKEN), "secrets.CHANGESET_GITHUB_TOKEN") + assert.include(String(step.env?.NPM_STAGE_TOKEN), "secrets.NPM_STAGE_TOKEN") + + const index = job.steps?.indexOf(step) + assert.deepStrictEqual( + secretReferences(workflow).map(([path]) => path).sort(), + [`jobs.readiness.steps.${index}.env.GH_TOKEN`, `jobs.readiness.steps.${index}.env.NPM_STAGE_TOKEN`] + ) + assert.isFalse(job.steps?.some((step) => step.uses === "./.github/actions/deploy-website")) + }) +}) + +describe("publish workflow", () => { + it("is dispatched by a maintainer against main with the identity and a one-time password", async () => { + const workflow = await load("publish.yml") + assertCommonSafety("publish", workflow) + + assert.deepStrictEqual(Object.keys(workflow.on ?? {}), ["workflow_dispatch"]) + const dispatch = workflow.on?.workflow_dispatch as { + inputs?: Record + } + assert.exists(dispatch.inputs?.identity, "identity input") + assert.strictEqual(dispatch.inputs?.identity.required, true) + assert.exists(dispatch.inputs?.otp, "otp input") + assert.strictEqual(dispatch.inputs?.otp.required, true) + + assert.deepStrictEqual(Object.keys(workflow.jobs), ["publish"]) + const job = workflow.jobs.publish + assert.include(job.if, "github.ref == 'refs/heads/main'") + assert.deepStrictEqual(job.permissions, { contents: "read" }) + for (const checkout of job.steps?.filter((step) => step.uses?.startsWith("actions/checkout@")) ?? []) { + assert.notProperty(checkout.with ?? {}, "ref", "publish must read the manifest from the dispatched main") + } + }) + + it("confines the approve credentials to the publish step and gates the website on its output", async () => { + const workflow = await load("publish.yml") + const job = workflow.jobs.publish + + const publish = job.steps?.find((step) => step.run?.includes("release publish")) + assert.exists(publish, "publish step") + assert.strictEqual(publish.id, "publish") + assert.include(publish.run, "release publish --expect-identity") + assert.notInclude(publish.run, "--otp") + assert.notInclude(publish.run, "inputs.otp") + assert.deepStrictEqual(Object.keys(publish.env ?? {}).sort(), [ + "IDENTITY", + "NPM_APPROVE_TOKEN", + "NPM_OTP", + "NPM_STAGE_TOKEN" + ]) + assert.include(String(publish.env?.NPM_OTP), "inputs.otp") + assert.include(String(publish.env?.IDENTITY), "inputs.identity") + assert.include(String(publish.env?.NPM_APPROVE_TOKEN), "secrets.NPM_APPROVE_TOKEN") + assert.include(String(publish.env?.NPM_STAGE_TOKEN), "secrets.NPM_STAGE_TOKEN") + assert.include(publish.run, "published=") + assert.include(publish.run, "revision=") + assert.include(publish.run, "GITHUB_OUTPUT") + + const website = job.steps?.find((step) => step.uses === "./.github/actions/deploy-website") + assert.exists(website, "website step") + assert.include(website.if, "steps.publish.outputs.published == 'true'") + assert.strictEqual(website.with?.channel, "v4") + assert.include(String(website.with?.revision), "steps.publish.outputs.revision") + assert.include(String(website.with?.["dispatch-token"]), "secrets.WEBSITE_DISPATCH_TOKEN") + assert.isAbove(job.steps?.indexOf(website) ?? -1, job.steps?.indexOf(publish) ?? -1) + + const publishIndex = job.steps?.indexOf(publish) + const websiteIndex = job.steps?.indexOf(website) + assert.deepStrictEqual( + secretReferences(workflow).map(([path]) => path).sort(), + [ + `jobs.publish.steps.${publishIndex}.env.NPM_APPROVE_TOKEN`, + `jobs.publish.steps.${publishIndex}.env.NPM_STAGE_TOKEN`, + `jobs.publish.steps.${websiteIndex}.with.dispatch-token` + ] + ) + }) +}) + +describe("release workflow after the publish flow", () => { + it("still never publishes or deploys the website on a push to main", async () => { + const workflow = await load("release.yml") + for (const [name, job] of Object.entries(workflow.jobs)) { + assert.isFalse(job.steps?.some((step) => step.uses === "./.github/actions/deploy-website"), `${name}: website`) + assert.isFalse(job.steps?.some((step) => step.run?.includes("release publish")), `${name}: publish`) + assert.isFalse(job.steps?.some((step) => step.run?.includes("stage approve")), `${name}: approve`) + } + assert.deepStrictEqual(secretReferences(workflow).filter(([, value]) => value.includes("NPM_APPROVE_TOKEN")), []) + assert.deepStrictEqual( + secretReferences(workflow).filter(([, value]) => value.includes("WEBSITE_DISPATCH_TOKEN")), + [] + ) + }) +}) diff --git a/packages/tools/release/test/Readiness.test.ts b/packages/tools/release/test/Readiness.test.ts new file mode 100644 index 0000000000..6bb4fed37e --- /dev/null +++ b/packages/tools/release/test/Readiness.test.ts @@ -0,0 +1,196 @@ +import * as Readiness from "@effect/release/Readiness" +import { versionKey } from "@effect/release/Routing" +import { assert, describe, it } from "@effect/vitest" +import * as Option from "effect/Option" +import { + EFFECT_STAGE_ID, + effectManifestPackage, + manifest, + manifestQueue, + stagedWithId, + VITEST_STAGE_ID, + vitestManifestPackage +} from "./utils.ts" + +const states = (readiness: Readiness.Readiness) => readiness.packages.map((pkg) => [pkg.name, pkg.state] as const) + +describe("Readiness.assess", () => { + it("is Ready when every pinned stage id is approvable", () => { + const readiness = Readiness.assess({ manifest, staged: manifestQueue, published: new Set() }) + assert.strictEqual(readiness._tag, "Ready") + assert.deepStrictEqual(states(readiness), [["@effect/vitest", "approvable"], ["effect", "approvable"]]) + }) + + it("treats every documented approvable status as approvable and nothing else", () => { + for (const status of Readiness.APPROVABLE_STATUSES) { + const readiness = Readiness.assess({ + manifest, + staged: [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117", status), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117", status) + ], + published: new Set() + }) + assert.strictEqual(readiness._tag, "Ready", status) + } + assert.isFalse(Readiness.APPROVABLE_STATUSES.has("validating")) + assert.isFalse(Readiness.APPROVABLE_STATUSES.has("published")) + }) + + it("is Ready when a package is already public, even without a queue item", () => { + const readiness = Readiness.assess({ + manifest, + staged: [stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117")], + published: new Set([versionKey("effect", "4.0.0-rc.117")]) + }) + assert.strictEqual(readiness._tag, "Ready") + assert.deepStrictEqual(states(readiness), [["@effect/vitest", "approvable"], ["effect", "public"]]) + }) + + it("is Ready with every package public after a completed publication", () => { + const readiness = Readiness.assess({ + manifest, + staged: [], + published: new Set([versionKey("effect", "4.0.0-rc.117"), versionKey("@effect/vitest", "4.0.0-rc.117")]) + }) + assert.strictEqual(readiness._tag, "Ready") + assert.deepStrictEqual(states(readiness), [["@effect/vitest", "public"], ["effect", "public"]]) + }) + + it("is NotReady while a pinned item is still validating", () => { + const readiness = Readiness.assess({ + manifest, + staged: [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117", "validating"), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") + ], + published: new Set() + }) + assert.strictEqual(readiness._tag, "NotReady") + if (readiness._tag === "NotReady") { + assert.deepStrictEqual(readiness.blockers.map((pkg) => [pkg.name, pkg.state]), [["effect", "pending"]]) + assert.include(readiness.blockers[0].detail, "validating") + assert.lengthOf(readiness.packages, 2) + } + }) + + it("is NotReady when a pinned stage id is missing from the queue", () => { + const readiness = Readiness.assess({ + manifest, + staged: [stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117")], + published: new Set() + }) + assert.strictEqual(readiness._tag, "NotReady") + if (readiness._tag === "NotReady") { + assert.deepStrictEqual(readiness.blockers.map((pkg) => [pkg.name, pkg.state]), [["effect", "missing"]]) + } + }) + + it("is NotReady, naming the newer id, when the version was staged again under another id", () => { + const restaged = "3b2a1908-7f6e-4d5c-9b4a-3f2e1d0c9b8a" + const readiness = Readiness.assess({ + manifest, + staged: [ + stagedWithId(restaged, "effect", "4.0.0-rc.117"), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") + ], + published: new Set() + }) + assert.strictEqual(readiness._tag, "NotReady") + if (readiness._tag === "NotReady") { + assert.lengthOf(readiness.blockers, 1) + assert.strictEqual(readiness.blockers[0].state, "missing") + assert.include(readiness.blockers[0].detail, restaged) + } + }) + + it("is NotReady when the pinned id now belongs to a different package or version", () => { + const readiness = Readiness.assess({ + manifest, + staged: [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.118"), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") + ], + published: new Set() + }) + assert.strictEqual(readiness._tag, "NotReady") + if (readiness._tag === "NotReady") { + assert.deepStrictEqual(readiness.blockers.map((pkg) => [pkg.name, pkg.state]), [["effect", "missing"]]) + assert.include(readiness.blockers[0].detail, "4.0.0-rc.118") + } + }) + + it("is NotReady when a pinned item was blocked, rejected or deleted", () => { + for (const status of Readiness.BLOCKED_STATUSES) { + const readiness = Readiness.assess({ + manifest, + staged: [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117", status), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") + ], + published: new Set() + }) + assert.strictEqual(readiness._tag, "NotReady", status) + if (readiness._tag === "NotReady") { + assert.deepStrictEqual(readiness.blockers.map((pkg) => [pkg.name, pkg.state]), [["effect", "blocked"]]) + assert.include(readiness.blockers[0].detail, status) + } + } + }) + + it("fails closed on a status word it does not know, or no status at all", () => { + const unknown = Readiness.assess({ + manifest, + staged: [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117", "quarantined"), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") + ], + published: new Set() + }) + assert.strictEqual(unknown._tag, "NotReady") + if (unknown._tag === "NotReady") { + assert.deepStrictEqual(unknown.blockers.map((pkg) => [pkg.name, pkg.state]), [["effect", "unknown"]]) + assert.include(unknown.blockers[0].detail, "quarantined") + } + + const absent = Readiness.assess({ + manifest, + staged: [ + { ...stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117"), status: Option.none() }, + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") + ], + published: new Set() + }) + assert.strictEqual(absent._tag, "NotReady") + if (absent._tag === "NotReady") { + assert.strictEqual(absent.blockers[0].state, "unknown") + } + }) + + it("lists every blocker in manifest order and ignores queue items outside the manifest", () => { + const readiness = Readiness.assess({ + manifest, + staged: [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117", "validating"), + stagedWithId( + "9d8c7b6a-5f4e-4d3c-8b2a-1f0e9d8c7b6a", + "@effect/release-spike-fixture", + "0.0.0-spike.1", + "blocked" + ) + ], + published: new Set() + }) + assert.strictEqual(readiness._tag, "NotReady") + if (readiness._tag === "NotReady") { + assert.deepStrictEqual(readiness.blockers.map((pkg) => [pkg.name, pkg.state]), [ + ["@effect/vitest", "missing"], + ["effect", "pending"] + ]) + assert.deepStrictEqual(readiness.packages.map((pkg) => pkg.stageId), [ + vitestManifestPackage.stageId, + effectManifestPackage.stageId + ]) + } + }) +}) diff --git a/packages/tools/release/test/ReleaseManifest.test.ts b/packages/tools/release/test/ReleaseManifest.test.ts new file mode 100644 index 0000000000..467a01160a --- /dev/null +++ b/packages/tools/release/test/ReleaseManifest.test.ts @@ -0,0 +1,180 @@ +import * as ReleaseManifest from "@effect/release/ReleaseManifest" +import { assert, describe, it } from "@effect/vitest" +import * as Effect from "effect/Effect" +import * as Option from "effect/Option" +import { createHash } from "node:crypto" +import { + EFFECT_STAGE_ID, + effectPackage, + LEDGER_SHA, + manifest, + manifestQueue, + packages, + scratchpadPackage, + stagedWithId, + VITEST_STAGE_ID, + vitestPackage +} from "./utils.ts" + +const expectedEncoding = `{ + "schema": 1, + "tag": "rc", + "sourceSha": "${LEDGER_SHA}", + "packages": [ + { + "name": "@effect/vitest", + "version": "4.0.0-rc.117", + "stageId": "${VITEST_STAGE_ID}" + }, + { + "name": "effect", + "version": "4.0.0-rc.117", + "stageId": "${EFFECT_STAGE_ID}" + } + ] +} +` + +describe("ReleaseManifest", () => { + it("encodes canonically: fixed key order, two spaces, packages sorted by name, trailing newline", () => { + assert.strictEqual(ReleaseManifest.encode(manifest), expectedEncoding) + const reversed = { ...manifest, packages: [...manifest.packages].reverse() } + assert.strictEqual(ReleaseManifest.encode(reversed), expectedEncoding) + }) + + it("derives the identity from the SHA-256 of the canonical encoding", () => { + const expected = createHash("sha256").update(expectedEncoding).digest("hex").slice( + 0, + ReleaseManifest.IDENTITY_LENGTH + ) + assert.strictEqual(ReleaseManifest.identity(manifest), expected) + assert.lengthOf(ReleaseManifest.identity(manifest), 16) + assert.match(ReleaseManifest.identity(manifest), /^[0-9a-f]{16}$/) + }) + + it("changes the identity when any pinned fact changes, and not when package order changes", () => { + const base = ReleaseManifest.identity(manifest) + const [vitest, effect] = manifest.packages + const variants = [ + { ...manifest, tag: "latest" }, + { ...manifest, sourceSha: "deadbeef".repeat(5) }, + { ...manifest, packages: [vitest, { ...effect, version: "4.0.0-rc.118" }] }, + { ...manifest, packages: [vitest, { ...effect, stageId: "00000000-0000-4000-8000-000000000000" }] }, + { ...manifest, packages: [effect] } + ] + for (const variant of variants) { + assert.notStrictEqual(ReleaseManifest.identity(variant), base) + } + assert.strictEqual(ReleaseManifest.identity({ ...manifest, packages: [effect, vitest] }), base) + }) + + it.effect("round-trips through decode", () => + Effect.gen(function*() { + const decoded = yield* ReleaseManifest.decode(ReleaseManifest.encode(manifest)) + assert.deepStrictEqual(decoded, manifest) + })) + + it.effect("rejects malformed, foreign-schema, incomplete and unsorted manifests", () => + Effect.gen(function*() { + const cases: ReadonlyArray<[string, string]> = [ + ["malformed", "{"], + ["schema", expectedEncoding.replace("\"schema\": 1", "\"schema\": 2")], + [ + "stageId", + expectedEncoding.replace(` "stageId": "${EFFECT_STAGE_ID}"\n`, "").replace(",\n }", "\n }") + ], + [ + "unsorted", + JSON.stringify({ ...manifest, packages: [...manifest.packages].reverse() }, null, 2) + "\n" + ] + ] + for (const [label, text] of cases) { + const error = yield* Effect.flip(ReleaseManifest.decode(text)) + assert.strictEqual(error._tag, "ReleaseError", label) + } + })) + + it.effect("builds a sorted manifest from the workspace and the queue, ignoring private and foreign items", () => + Effect.gen(function*() { + const built = yield* ReleaseManifest.fromStaged({ + tag: "rc", + sourceSha: LEDGER_SHA, + packages: [effectPackage, scratchpadPackage, vitestPackage], + staged: [ + ...manifestQueue, + stagedWithId("9d8c7b6a-5f4e-4d3c-8b2a-1f0e9d8c7b6a", "@effect/release-spike-fixture", "0.0.0-spike.1"), + stagedWithId("0a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d", "scratchpad", "0.0.0") + ] + }) + assert.deepStrictEqual(built, manifest) + })) + + it.effect("accepts a staged item without a tag", () => + Effect.gen(function*() { + const built = yield* ReleaseManifest.fromStaged({ + tag: "rc", + sourceSha: LEDGER_SHA, + packages, + staged: [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117", "staged", Option.none()), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") + ] + }) + assert.deepStrictEqual(built, manifest) + })) + + it.effect("fails naming the package when a public package is not staged", () => + Effect.gen(function*() { + const error = yield* Effect.flip(ReleaseManifest.fromStaged({ + tag: "rc", + sourceSha: LEDGER_SHA, + packages, + staged: [stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117")] + })) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, "effect") + assert.notInclude(error.message, "@effect/vitest") + })) + + it.effect("fails when a staged item carries a different dist-tag", () => + Effect.gen(function*() { + const error = yield* Effect.flip(ReleaseManifest.fromStaged({ + tag: "rc", + sourceSha: LEDGER_SHA, + packages, + staged: [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117", "staged", Option.some("latest")), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") + ] + })) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, "effect") + })) + + it.effect("fails naming both ids when the same version is staged twice", () => + Effect.gen(function*() { + const duplicate = "5e4d3c2b-1a09-4f8e-8d7c-6b5a4f3e2d1c" + const error = yield* Effect.flip(ReleaseManifest.fromStaged({ + tag: "rc", + sourceSha: LEDGER_SHA, + packages, + staged: [...manifestQueue, stagedWithId(duplicate, "effect", "4.0.0-rc.117")] + })) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, EFFECT_STAGE_ID) + assert.include(error.message, duplicate) + })) + + it.effect("fails naming both versions when a public package has a stale staged version", () => + Effect.gen(function*() { + const error = yield* Effect.flip(ReleaseManifest.fromStaged({ + tag: "rc", + sourceSha: LEDGER_SHA, + packages, + staged: [...manifestQueue, stagedWithId("7c6b5a49-3827-4165-9f0e-1d2c3b4a5968", "effect", "4.0.0-rc.116")] + })) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, "4.0.0-rc.116") + assert.include(error.message, "4.0.0-rc.117") + })) +}) diff --git a/packages/tools/release/test/StageApproval.test.ts b/packages/tools/release/test/StageApproval.test.ts new file mode 100644 index 0000000000..1e4e904ef3 --- /dev/null +++ b/packages/tools/release/test/StageApproval.test.ts @@ -0,0 +1,137 @@ +import { StageApproval } from "@effect/release/StageApproval" +import { assert, describe, it } from "@effect/vitest" +import * as ConfigProvider from "effect/ConfigProvider" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as Option from "effect/Option" +import * as HttpClient from "effect/unstable/http/HttpClient" +import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse" +import { EFFECT_STAGE_ID, otp } from "./utils.ts" + +const TOKEN = "approve-token-value" + +const respond = (responses: Array) => { + const requests: Array = [] + const client = HttpClient.make((request) => { + requests.push(request) + const response = responses.shift() + return response === undefined + ? Effect.die("unexpected request") + : Effect.succeed(HttpClientResponse.fromWeb(request, response)) + }) + return { requests, client } +} + +const json = (body: unknown, status = 200, headers: Record = {}) => + new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } }) + +const withToken = (token?: string) => + ConfigProvider.layer(ConfigProvider.fromEnv({ env: token === undefined ? {} : { NPM_APPROVE_TOKEN: token } })) + +const layer = (client: HttpClient.HttpClient, token?: string) => + StageApproval.layer.pipe( + Layer.provide(Layer.succeed(HttpClient.HttpClient, client)), + Layer.provide(withToken(token)) + ) + +describe("StageApproval layer", () => { + it.effect("views a staged item with the stage authentication headers", () => { + const { client, requests } = respond([ + json({ id: EFFECT_STAGE_ID, packageName: "effect", version: "4.0.0-rc.117", tag: "rc", status: "staged" }), + json({ error: "not found" }, 404) + ]) + return Effect.gen(function*() { + const approval = yield* StageApproval + const item = yield* approval.viewStaged(EFFECT_STAGE_ID) + assert.deepStrictEqual( + item, + Option.some({ + id: EFFECT_STAGE_ID, + packageName: "effect", + version: "4.0.0-rc.117", + tag: Option.some("rc"), + status: Option.some("staged") + }) + ) + assert.deepStrictEqual(yield* approval.viewStaged(EFFECT_STAGE_ID), Option.none()) + + assert.strictEqual(requests[0].method, "GET") + assert.strictEqual(requests[0].url, `https://registry.npmjs.org/-/stage/${EFFECT_STAGE_ID}`) + assert.strictEqual(requests[0].headers.authorization, `Bearer ${TOKEN}`) + assert.strictEqual(requests[0].headers["npm-auth-type"], "web") + assert.strictEqual(requests[0].headers["npm-command"], "stage") + assert.isUndefined(requests[0].headers["npm-otp"]) + }).pipe(Effect.provide(layer(client, TOKEN))) + }) + + it.effect("approves with a POST carrying the OTP header", () => { + const { client, requests } = respond([json({ id: EFFECT_STAGE_ID, status: "published" })]) + return Effect.gen(function*() { + const approval = yield* StageApproval + yield* approval.approve(EFFECT_STAGE_ID, otp) + assert.lengthOf(requests, 1) + assert.strictEqual(requests[0].method, "POST") + assert.strictEqual(requests[0].url, `https://registry.npmjs.org/-/stage/${EFFECT_STAGE_ID}/approve`) + assert.strictEqual(requests[0].headers.authorization, `Bearer ${TOKEN}`) + assert.strictEqual(requests[0].headers["npm-auth-type"], "web") + assert.strictEqual(requests[0].headers["npm-command"], "stage") + assert.strictEqual(requests[0].headers["npm-otp"], "123456") + }).pipe(Effect.provide(layer(client, TOKEN))) + }) + + it.effect("reports the registry's proof-of-presence challenge as an OTP failure without leaking the OTP", () => { + const { client } = respond([ + json({ authUrl: "https://www.npmjs.com/auth/cli/x", doneUrl: "https://www.npmjs.com/auth/cli/x/done" }, 401), + json({ error: "OTP required" }, 401, { "www-authenticate": "OTP" }) + ]) + return Effect.gen(function*() { + const approval = yield* StageApproval + for (let attempt = 0; attempt < 2; attempt++) { + const error = yield* Effect.flip(approval.approve(EFFECT_STAGE_ID, otp)) + assert.strictEqual(error._tag, "ReleaseError") + assert.match(error.message, /one-time password|OTP/) + assert.include(error.message, EFFECT_STAGE_ID) + assert.notInclude(error.message, "123456") + assert.notInclude(error.message, TOKEN) + } + }).pipe(Effect.provide(layer(client, TOKEN))) + }) + + it.effect("fails with the status and body on any other rejection, never echoing credentials", () => { + const { client } = respond([json({ error: "forbidden: token cannot approve" }, 403)]) + return Effect.gen(function*() { + const approval = yield* StageApproval + const error = yield* Effect.flip(approval.approve(EFFECT_STAGE_ID, otp)) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, "403") + assert.include(error.message, "token cannot approve") + assert.notInclude(error.message, "123456") + assert.notInclude(error.message, TOKEN) + }).pipe(Effect.provide(layer(client, TOKEN))) + }) + + it.effect("rejects an unexpected status on view", () => { + const { client } = respond([json({}, 503)]) + return Effect.gen(function*() { + const approval = yield* StageApproval + const error = yield* Effect.flip(approval.viewStaged(EFFECT_STAGE_ID)) + assert.strictEqual(error._tag, "ReleaseError") + assert.include(error.message, "503") + }).pipe(Effect.provide(layer(client, TOKEN))) + }) + + it.effect("fails before any request when the approve token is missing", () => { + const { client, requests } = respond([]) + return Effect.gen(function*() { + const approval = yield* StageApproval + const approveError = yield* Effect.flip(approval.approve(EFFECT_STAGE_ID, otp)) + assert.strictEqual(approveError._tag, "ReleaseError") + assert.include(approveError.message, "NPM_APPROVE_TOKEN") + const viewError = yield* Effect.flip(approval.viewStaged(EFFECT_STAGE_ID)) + assert.strictEqual(viewError._tag, "ReleaseError") + assert.include(viewError.message, "NPM_APPROVE_TOKEN") + assert.lengthOf(requests, 0) + }).pipe(Effect.provide(layer(client))) + }) +}) diff --git a/packages/tools/release/test/utils.ts b/packages/tools/release/test/utils.ts index 125173705a..4dd8b0278b 100644 --- a/packages/tools/release/test/utils.ts +++ b/packages/tools/release/test/utils.ts @@ -1,12 +1,18 @@ +import { ReleaseError } from "@effect/release/Errors" import { Git } from "@effect/release/Git" import { GitHub, type PullRequest } from "@effect/release/GitHub" import { Pnpm, type StagedPackage } from "@effect/release/Pnpm" import { Registry, type StagedItem } from "@effect/release/Registry" +import type { ManifestPackage, ReleaseManifest } from "@effect/release/ReleaseManifest" import type { AppliedVersion, ReleasePlan } from "@effect/release/ReleasePlan" +import { StageApproval } from "@effect/release/StageApproval" import { Workspace, type WorkspacePackage } from "@effect/release/Workspace" import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" import * as Layer from "effect/Layer" import * as Option from "effect/Option" +import * as PlatformError from "effect/PlatformError" +import * as Redacted from "effect/Redacted" // --------------------------------------------------------------------------- // Fixtures @@ -73,12 +79,54 @@ export const stagedItem = (packageName: string, version: string, status = "stage status: Option.some(status) }) +/** Registry stage ids are UUIDs; pnpm refuses anything else, so the fixtures use real ones. */ +export const EFFECT_STAGE_ID = "8a4f1c2e-3b6d-4e7f-9a1b-2c3d4e5f6a70" +export const VITEST_STAGE_ID = "1f2e3d4c-5b6a-4978-8f7e-6d5c4b3a2910" +export const LEDGER_SHA = "c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00" + +/** A queue item with an explicit id, for manifest fixtures. */ +export const stagedWithId = ( + id: string, + packageName: string, + version: string, + status = "staged", + tag: Option.Option = Option.some("rc") +): StagedItem => ({ id, packageName, version, tag, status: Option.some(status) }) + +export const effectManifestPackage: ManifestPackage = { + name: "effect", + version: "4.0.0-rc.117", + stageId: EFFECT_STAGE_ID +} + +export const vitestManifestPackage: ManifestPackage = { + name: "@effect/vitest", + version: "4.0.0-rc.117", + stageId: VITEST_STAGE_ID +} + +/** The release of the two public fixture packages, packages sorted by name (`@` sorts before `e`). */ +export const manifest: ReleaseManifest = { + schema: 1, + tag: "rc", + sourceSha: LEDGER_SHA, + packages: [vitestManifestPackage, effectManifestPackage] +} + +/** The queue as it looks once both fixture packages are staged and scanned. */ +export const manifestQueue: ReadonlyArray = [ + stagedWithId(EFFECT_STAGE_ID, "effect", "4.0.0-rc.117"), + stagedWithId(VITEST_STAGE_ID, "@effect/vitest", "4.0.0-rc.117") +] + +export const otp = Redacted.make("123456") + // --------------------------------------------------------------------------- // Call recording // --------------------------------------------------------------------------- export interface Call { - readonly service: "git" | "github" | "pnpm" | "registry" | "workspace" + readonly service: "git" | "github" | "pnpm" | "registry" | "workspace" | "approval" | "fs" readonly method: string readonly args: ReadonlyArray } @@ -107,6 +155,8 @@ const track = (calls: Calls, service: Call["service"], method: string, ...args: export const gitLayer = (calls: Calls, options?: { readonly headSha?: string readonly commitSha?: Option.Option + readonly ledgerSha?: string + readonly pushFailure?: Effect.Effect | undefined }) => Layer.succeed( Git, @@ -117,8 +167,11 @@ export const gitLayer = (calls: Calls, options?: { track(calls, "git", "commitAll", message).pipe( Effect.as(options?.commitSha ?? Option.some("fedcba9876543210")) ), - pushForce: (branch) => track(calls, "git", "pushForce", branch), - checkout: (ref) => track(calls, "git", "checkout", ref) + pushForce: (branch) => + track(calls, "git", "pushForce", branch).pipe(Effect.andThen(options?.pushFailure ?? Effect.void)), + checkout: (ref) => track(calls, "git", "checkout", ref), + lastCommitTouching: (path) => + track(calls, "git", "lastCommitTouching", path).pipe(Effect.as(options?.ledgerSha ?? LEDGER_SHA)) }) ) @@ -196,3 +249,63 @@ export const workspaceLayer = (calls: Calls, list: ReadonlyArray + readonly failing?: ReadonlySet | undefined + readonly onApproved?: (id: string) => void +}) => + Layer.succeed( + StageApproval, + StageApproval.of({ + viewStaged: (id) => + track(calls, "approval", "viewStaged", id).pipe( + Effect.as(Option.fromUndefinedOr(options?.items?.find((item) => item.id === id))) + ), + approve: (id, otp) => + track(calls, "approval", "approve", id, Redacted.value(otp)).pipe( + Effect.flatMap(() => + options?.failing?.has(id) + ? Effect.fail(new ReleaseError({ message: `Failed to approve staged package ${id} (status 403)` })) + : Effect.sync(() => options?.onApproved?.(id)) + ) + ) + }) + ) + +/** + * A file system that serves `files` (workspace-relative path → content) and + * records writes; `exists` and `readFileString` work on the same map, so a + * write becomes visible to later reads within the test. + */ +export const fileSystemLayer = (calls: Calls, files: Map = new Map()) => { + const relative = (path: string) => path.replace(/^.*?(?=\.release\/|\.changeset\/|pnpm-workspace\.yaml)/, "") + return Layer.succeed( + FileSystem.FileSystem, + FileSystem.makeNoop({ + exists: (path) => Effect.succeed(path.endsWith("pnpm-workspace.yaml") || files.has(relative(path))), + readFileString: (path) => + Effect.suspend(() => { + const content = files.get(relative(path)) + return content === undefined + ? Effect.fail( + new PlatformError.PlatformError( + new PlatformError.BadArgument({ module: "FileSystem", method: "readFileString", description: path }) + ) + ) + : Effect.succeed(content) + }), + makeDirectory: (path) => track(calls, "fs", "makeDirectory", relative(path)), + writeFileString: (path, content) => + track(calls, "fs", "writeFileString", relative(path), content).pipe( + Effect.tap(() => Effect.sync(() => files.set(relative(path), content))) + ) + }) + ) +}