diff --git a/.bun-version b/.bun-version new file mode 100644 index 000000000..88c5fb891 --- /dev/null +++ b/.bun-version @@ -0,0 +1 @@ +1.4.0 diff --git a/.github/workflows/ci-integration.yml b/.github/workflows/ci-integration.yml index 5e859e4ce..032b90bae 100644 --- a/.github/workflows/ci-integration.yml +++ b/.github/workflows/ci-integration.yml @@ -9,7 +9,7 @@ permissions: contents: read env: - BUN_VERSION: "1.3.14" + BUN_VERSION: "1.4.0" NODE_VERSION: "24.15.0" jobs: @@ -182,34 +182,37 @@ jobs: run: bun run cms:migrate:status - name: Apply demo seed run: psql "$DATABASE_URL" -f supabase/seed.sql -v ON_ERROR_STOP=1 + - name: Install Playwright Chromium + run: bunx playwright install --with-deps chromium - name: Start donor app run: | nohup bun run --cwd apps/donor dev -- --port 3005 --hostname 127.0.0.1 > /tmp/donor-dev.log 2>&1 & echo $! > /tmp/donor-dev.pid - - name: Start admin app - run: | - nohup bun run --cwd apps/admin dev -- --port 3030 --hostname 127.0.0.1 > /tmp/admin-dev.log 2>&1 & - echo $! > /tmp/admin-dev.pid - - name: Install Playwright Chromium - run: bunx playwright install --with-deps chromium - name: Wait for donor health endpoint run: | for i in $(seq 1 120); do - if curl -sf http://127.0.0.1:3005/api/health >/dev/null; then - echo "Health endpoint ready after ${i}s" + if curl -sf http://127.0.0.1:3005/api/health >/dev/null \ + && curl -sf http://127.0.0.1:3005/api/auth/demo-account >/dev/null; then + echo "Donor health and demo auth ready after ${i}s" exit 0 fi if [ "$i" -eq 120 ]; then - echo "Timed out waiting for health endpoint" + echo "Timed out waiting for donor health or demo auth" echo "--- donor dev log (tail) ---" - tail -n 100 /tmp/donor-dev.log || true - echo "--- curl verbose ---" - curl -v http://127.0.0.1:3005/api/health || true + tail -n 150 /tmp/donor-dev.log || true + echo "--- health ---" + curl -sv http://127.0.0.1:3005/api/health || true + echo "--- demo auth ---" + curl -sv http://127.0.0.1:3005/api/auth/demo-account || true kill "$(cat /tmp/donor-dev.pid)" 2>/dev/null || true exit 1 fi sleep 1 done + - name: Start admin app + run: | + nohup bun run --cwd apps/admin dev -- --port 3030 --hostname 127.0.0.1 > /tmp/admin-dev.log 2>&1 & + echo $! > /tmp/admin-dev.pid - name: Wait for admin health endpoint run: | for i in $(seq 1 120); do @@ -236,6 +239,13 @@ jobs: PLAYWRIGHT_ADMIN_BASE_URL: "http://127.0.0.1:3030" PLAYWRIGHT_INCLUDE_ADMIN: "1" run: bun run test:e2e:smoke + - name: Show dev server logs on failure + if: failure() + run: | + echo "--- donor dev log (tail) ---" + tail -n 150 /tmp/donor-dev.log || true + echo "--- admin dev log (tail) ---" + tail -n 150 /tmp/admin-dev.log || true - name: Upload artifact on failure if: failure() uses: actions/upload-artifact@v7 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 22eb67f75..f03caca58 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,7 @@ permissions: pull-requests: read env: - BUN_VERSION: "1.3.14" + BUN_VERSION: "1.4.0" NODE_VERSION: "24.15.0" jobs: diff --git a/.github/workflows/qa-smoke-preview-deploy.yml b/.github/workflows/qa-smoke-preview-deploy.yml index e82153ff9..2fdb50e92 100644 --- a/.github/workflows/qa-smoke-preview-deploy.yml +++ b/.github/workflows/qa-smoke-preview-deploy.yml @@ -21,7 +21,7 @@ concurrency: cancel-in-progress: true env: - BUN_VERSION: "1.3.14" + BUN_VERSION: "1.4.0" NODE_VERSION: "24.15.0" jobs: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2a03cf405..81c152ab8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -24,7 +24,7 @@ commit metadata does not. CODEOWNERS routes reviews but does not grant access. - **Base branch:** branch from and open normal pull requests to `develop`. `production` is updated only through the intentional release workflow, and the canonical repository has no `main` branch; do not create or target one. -- **Package manager:** `bun` pinned via `package.json#packageManager` (currently `bun@1.3.14`). `bun run setup` and `scripts/setup/*` call `bun run verify:bun-version` so a mismatched local Bun fails fast with upgrade instructions. +- **Package manager:** `bun` pinned via `package.json#packageManager` and `.bun-version` (currently `bun@1.4.0`). `bun run setup` and `scripts/setup/*` call `bun run verify:bun-version` so a mismatched local Bun fails fast with upgrade instructions. Apps still run on Node.js via Next.js; Bun is the package manager and script runner, not a replacement Node runtime. Do not set `bunVersion` in app `vercel.json` files. - **Conventions:** `docs/conventions.md` (folder structure, code style, and pre-commit checklist). - **Setup (macOS/Linux):** `bun run setup` (creates/validates `.env.local`, installs deps, runs verification). - **Mission Control in Cursor Cloud:** `bun run setup:mission-control:cloud && bun run dev:mission-control` (writes gitignored dev placeholders only). diff --git a/README.md b/README.md index 26483ad4f..8fb302c48 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A high-performance Next.js 16.3.0-preview.9 (App Router) Turborepo monorepo for ## Quickstart -1. **Install prerequisites:** [Node.js 20.9+](https://nodejs.org/), [Bun 1.3.14](https://bun.sh), and Git on your PATH. +1. **Install prerequisites:** [Node.js 20.9+](https://nodejs.org/), [Bun 1.4.0](https://bun.sh), and Git on your PATH. 2. **Choose your setup path.** ### Credential-free Mission Control sandbox @@ -227,7 +227,7 @@ Commit both the canonical files and any mirror updates. ### Package Manager -This repo uses **Bun** pinned in root `package.json` `packageManager` (currently **1.3.14**). Install that exact version locally (`bun run verify:bun-version` after setup). Prefer `bun` / `bunx` for scripts in this workspace; CI installs with `bun ci`. +This repo uses **Bun** pinned in root `package.json` `packageManager` and `.bun-version` (currently **1.4.0**). Install that exact version locally (`bun run verify:bun-version` after setup). Prefer `bun` / `bunx` for scripts in this workspace; CI installs with `bun ci`. Apps still run on **Node.js 24** via Next.js (`next build` / `next start`). Do not use `bun --bun`, and do not add `bunVersion` to `apps/*/vercel.json` — that switches Vercel Functions onto the Bun runtime ([changelog](https://vercel.com/changelog/bun-1-4-is-now-available-in-vercel-functions)), which is not this repo’s deploy path. ### Monorepo Workspace Contract diff --git a/docs/ai/stack-registry.md b/docs/ai/stack-registry.md index 330ab494c..8c7f7e44d 100644 --- a/docs/ai/stack-registry.md +++ b/docs/ai/stack-registry.md @@ -8,8 +8,8 @@ Agents MUST use this to build better Nia query preambles and to pick the right d - Next.js (App Router) - React - TypeScript (default language; exact installed version in root `package.json`); readiness policy: `docs/guides/typescript-6-readiness.md` -- Node.js (runtime target) -- Bun (preferred package manager/runtime) +- Node.js (runtime target; Vercel Functions `nodeVersion` `24.x`) +- Bun (package manager and script runner only; apps still run on Node.js. Do not set `vercel.json` `bunVersion` or `bun --bun` — that opts Vercel Functions onto the Bun runtime, which is separate from the pinned Bun package manager) - PostgreSQL (Supabase Postgres) Nia keywords: @@ -18,7 +18,7 @@ Nia keywords: - React, hooks, components - TypeScript, tsconfig - Node.js -- Bun, bun.lock +- Bun, bun.lock, bunVersion, Vercel Functions runtime - Postgres, SQL, Supabase ## Monorepo and Tooling diff --git a/docs/ci.md b/docs/ci.md index 20e661ae4..ffdb2d177 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -31,12 +31,26 @@ The exact live required-check sets are recorded only in § Branch protection. ### Bun toolchain -- **Pinned version:** root `package.json` `packageManager` (currently `bun@1.3.14`). -- **GitHub Actions:** both workflows set `env.BUN_VERSION` to that exact version; every `oven-sh/setup-bun@v2` step uses `bun-version: ${{ env.BUN_VERSION }}`. +- **Pinned version:** root `package.json` `packageManager` and `.bun-version` (currently `bun@1.4.0`, stable only — never canary). +- **Runtime vs package manager:** Bun is the install/script runner. Next.js apps still execute on Node.js (Vercel project `nodeVersion` is `24.x`). Do not pass `bun --bun`, and do not set `bunVersion` in `apps/*/vercel.json`. +- **Vercel Functions Bun 1.4 is a separate runtime:** [Vercel's Bun 1.4 changelog](https://vercel.com/changelog/bun-1-4-is-now-available-in-vercel-functions) documents opting **Functions and Middleware** onto Bun via `"bunVersion": "1.4.x"`. That is not how you pin the package manager. `"1.x"` still selects Bun 1.3.14 on Functions. Next.js on the Bun runtime also requires `bun run --bun next dev|build` ([runtime docs](https://vercel.com/docs/functions/runtimes/bun)). Core stays on the Node path (`next dev` / `next build` / `next start`) because Payload, Stripe, Supabase SSR, and eve-runtime are validated there; Vercel treats the Bun Functions runtime as an explicit breaking-change opt-in. +- **Vercel install vs GitHub install:** App `installCommand` is `bun install --cwd ../.. --frozen-lockfile` (workspace root, frozen lockfile). That matches [Vercel package-manager detection](https://vercel.com/docs/package-managers) for `bun.lock` (`bun install`, not `bun ci`, and not `bun install --save-text-lockfile`). GitHub Actions keeps `bun ci --no-cache --backend=copyfile` for the portable file-copy backend. [Pinning a Bun version for Vercel _builds_](https://vercel.com/kb/guide/how-to-pin-a-specific-bun-version-for-vercel-builds) is `bunx bun@1.4.0 install`; Corepack does **not** pin Bun (it is for pnpm/Yarn). Do not change the install command unless a deploy proves the build-image Bun cannot read this `lockfileVersion` 1 file. +- **GitHub Actions:** `ci.yml`, `ci-integration.yml`, and `qa-smoke-preview-deploy.yml` set `env.BUN_VERSION` to that exact version; every first-party `oven-sh/setup-bun@v2` step uses `bun-version: ${{ env.BUN_VERSION }}`. +- **Workflow pin verification:** `verify:bun-version` parses workflow YAML with Bun's built-in parser, so it also works before dependencies are installed. It checks each setup step's own `with.bun-version` and the workflow/job/step environment in scope; comments, run-script text, unrelated inputs, and another job's environment cannot satisfy the pin contract. Quoted scalars and YAML aliases remain supported. +- **Live runtime verification:** `verify:vercel-build-controls` reads all three Vercel projects and requires `nodeVersion: "24.x"` with `bunVersion` absent or `null`. Any explicit Bun runtime value fails, even if source-controlled `vercel.json` files still select Node. This verifier only reads project settings. - **Install in CI:** `bun ci --no-cache --backend=copyfile` (frozen lockfile install with Bun's portable file-copy backend). Do not use `bun install --frozen-lockfile` in workflows unless a future Bun release documents a regression. +- **Lockfile format:** `bun.lock` remains `"lockfileVersion": 1` with `"configVersion": 1` (isolated linker). Bun 1.4 writes lockfileVersion 2 for _new_ lockfiles, but does not bump an existing v1 file on re-save ([oven-sh/bun#31602](https://github.com/oven-sh/bun/pull/31602)). Do not regenerate `bun.lock` just to pick up v2, and do not run `bun install --save-text-lockfile` — that rewrite can retarget nested resolutions without a manifest change. Installed Turborepo `2.10.0` parses bun lockfile versions 0 and 1 only. `bun run verify:bun-lock-drift` fails closed on any `lockfileVersion` other than `0` or `1` and tells operators to keep or restore that ceiling — not to run `bun install`, which on Bun 1.4 can rewrite a v1 lock to v2. If a future install rewrites `bun.lock` to lockfileVersion 2 or 3, copy the tree (do not rewrite the committed lock in place) and require both of these to pass on the installed turbo before accepting that lock: + +```sh +bunx --no-install turbo prune @asym/donor --docker +(cd out/json && bun install --frozen-lockfile) +``` + +`verify:bun-lock-drift` still rejects versions above 1 and does not replace this parser check. + - **Lockfile drift:** a frozen-lockfile install does **not** notice when a `package.json` dependency is missing from `bun.lock`'s `workspaces` map — commit `ea9a7673` added a root dependency without the regenerated lockfile and CI stayed green, while every contributor's next plain `bun install` silently rewrote `bun.lock`. `bun run verify:bun-lock-drift` compares the two files directly and is the check that catches this; it is a pure file read, so it needs no install and no network. - **Turbo cache keys** in `ci.yml` include `bun-${{ env.BUN_VERSION }}` so cache restores do not cross Bun upgrades. -- **Local parity:** match the pin (`bun run verify:bun-version`); reproducible install from a clean tree is `bun ci`. GitHub Actions uses `bun ci --no-cache --backend=copyfile` so Linux runners use Bun's portable install backend for vendored `file:` tarballs. +- **Local parity:** match the pin (`bun run verify:bun-version`). That command also fails if a first-party `.github/workflows/*.{yml,yaml}` `BUN_VERSION` or `oven-sh/setup-bun` pin disagrees with `packageManager`. Reproducible install from a clean tree is `bun ci`. GitHub Actions uses `bun ci --no-cache --backend=copyfile` so Linux runners use Bun's portable install backend for vendored `file:` tarballs. ## Local CI parity (pre-push) @@ -243,7 +257,7 @@ Current coverage caveat: the repo's custom raw V8 fallback provider writes cover ### `test-e2e-smoke` (needs: `smoke`) -- _What it does:_ Re-applies SQL migrations against a fresh Postgres container through `node scripts/verify/supabase-migrations.mjs`, runs Payload migrations + status checks, then applies seed data, starts `apps/donor` on port 3005 and `apps/admin` on port 3030 with `E2E_AUTH_BYPASS=true`, waits for both `/api/health` endpoints, and runs the bounded Playwright smoke suite via `bun run test:e2e:smoke` (demo auth preflight, usability smoke, donate, upload-crop under the donor-auth project, and Support Hub smoke). The job has a 25-minute cap, the Playwright smoke step has a 15-minute cap, and failures upload `playwright-smoke-report/`. +- _What it does:_ Re-applies SQL migrations against a fresh Postgres container through `node scripts/verify/supabase-migrations.mjs`, runs Payload migrations + status checks, then applies seed data. Playwright Chromium is installed before either dev server starts, so `bunx` does not mutate the module graph while Turbopack is compiling. The job then starts `apps/donor` on port 3005 with `E2E_AUTH_BYPASS=true`, waits until `/api/health` and `/api/auth/demo-account` both succeed, starts `apps/admin` on port 3030, waits for admin `/api/health`, and runs the bounded Playwright smoke suite via `bun run test:e2e:smoke` (demo auth preflight, usability smoke, donate, upload-crop under the donor-auth project, and Support Hub smoke). The job has a 25-minute cap, the Playwright smoke step has a 15-minute cap, and failures upload `playwright-smoke-report/` plus the dev-server logs. - _Branch behavior:_ Produces `e2e-smoke-gate`; `integration-gate` also summarizes this result. See § Branch protection for which contexts GitHub currently requires. diff --git a/docs/ops/environments.md b/docs/ops/environments.md index c2323f139..0be756452 100644 --- a/docs/ops/environments.md +++ b/docs/ops/environments.md @@ -108,7 +108,10 @@ behavior, or prebuilt deployment flow; those controls are adjacent deployment discipline settings and remain outside this phase. Each Vercel app also owns its install, build, and ignored-build commands in -`apps/*/vercel.json`: +`apps/*/vercel.json`. Those files must **omit** `bunVersion`: that key selects +the [Bun Functions runtime](https://vercel.com/docs/functions/runtimes/bun) +(`"1.4.x"` or `"1.x"`), not the package manager. These projects stay on the +Next.js + Node 24.x Functions runtime. | Vercel project | `installCommand` | `buildCommand` | `ignoreCommand` | | -------------- | ------------------------------------------- | -------------------------------------- | -------------------------------------------------------------- | diff --git a/openspec/changes/verify-toolchain-runtime-pins/design.md b/openspec/changes/verify-toolchain-runtime-pins/design.md new file mode 100644 index 000000000..60eb62dd8 --- /dev/null +++ b/openspec/changes/verify-toolchain-runtime-pins/design.md @@ -0,0 +1,21 @@ +# Design + +The Bun version guard is used before node_modules exists. Use the installed Bun +binary's built-in YAML parser through a fixed expression with workflow contents +on stdin; do not import a package requiring prior dependency installation or +execute workflow content. Node remains the verifier entry point. + +Check each setup-bun step's own with.bun-version expression and the merged +workflow/job/step environment. Comments, block strings, unrelated inputs and +another job's environment cannot supply that step's pin. Invalid YAML and +unsupported environment shapes fail closed; valid quoted scalars and aliases +remain supported. + +The live Vercel validator requires nodeVersion 24.x and treats only absent/null +bunVersion as unset. It continues to read project data without updating it. +Existing local config, branch, queue and preview checks remain in place. + +The published PR keeps its history. Earlier unpublished repairs are reference +material: current source and failing regressions establish the required change. +The integration coordinator owns latest-base reconciliation, full gates and +publication. No provider or deployment setting is mutated by these verifiers. diff --git a/openspec/changes/verify-toolchain-runtime-pins/proposal.md b/openspec/changes/verify-toolchain-runtime-pins/proposal.md new file mode 100644 index 000000000..659eaeec9 --- /dev/null +++ b/openspec/changes/verify-toolchain-runtime-pins/proposal.md @@ -0,0 +1,23 @@ +# Verify each Bun setup step and live app runtime + +## Why + +PR #1338's two remaining review findings reproduce on its current head. A +comment can hide a wrong Actions setup pin, and live Vercel runtime drift can +be reported ready despite the accepted Node 24 policy. + +## What Changes + +- Parse actual workflow YAML and check each setup step's own input and scoped + environment, including before dependency installation. +- Require Node 24 and no configured Bun runtime in live project settings. +- Add positive and negative regression coverage at the exported verifier seam. + +## Impact + +- New capability: `toolchain-verification`. +- Affects two read-only verification scripts, their tests and CI documentation. +- Keeps the candidate's Bun 1.4.0 package-manager pin, Node runtime contract, + dependency graph and deployment settings unchanged. +- Rollback restores the previous verifiers and their known false acceptances; + it does not roll back a runtime or deployment. diff --git a/openspec/changes/verify-toolchain-runtime-pins/specs/toolchain-verification/spec.md b/openspec/changes/verify-toolchain-runtime-pins/specs/toolchain-verification/spec.md new file mode 100644 index 000000000..fa226e69d --- /dev/null +++ b/openspec/changes/verify-toolchain-runtime-pins/specs/toolchain-verification/spec.md @@ -0,0 +1,46 @@ +## ADDED Requirements + +### Requirement: Every Bun setup step owns its verified version pin + +The toolchain verifier SHALL inspect each first-party setup-bun step's own +version input and effective workflow, job and step environment. It SHALL require +the repository's exact stable package-manager pin through the accepted +env.BUN_VERSION expression. It MUST work before dependency installation and +MUST reject malformed workflow data instead of reporting readiness. + +#### Scenario: Unrelated text resembles a valid pin + +- GIVEN a setup step installs a different version +- WHEN a comment, run-script string or another action contains the expected pin +- THEN the verifier rejects the setup step + +#### Scenario: A job or step shadows the workflow environment + +- GIVEN a setup step inherits a different BUN_VERSION or no in-scope pin +- WHEN the verifier inspects its effective environment +- THEN it rejects that step regardless of pins in unrelated jobs + +#### Scenario: Dependencies are not installed yet + +- GIVEN Bun is installed but node_modules is absent +- WHEN a valid workflow uses quoted scalars or supported YAML aliases +- THEN the verifier can validate the correct scoped pin + +### Requirement: Live app runtime settings match the Node policy + +The deployment-control verifier SHALL require live Vercel project nodeVersion +24.x and an absent or null bunVersion for the three applications. It MUST reject +runtime drift even when checked-in configuration remains correct. Verification +SHALL be read-only. + +#### Scenario: Live runtime settings drift + +- GIVEN a project reports a different or missing Node runtime or an explicit Bun runtime +- WHEN the deployment-control verifier reads its settings +- THEN it reports the project as not ready without changing the project + +#### Scenario: Live runtime remains Node 24 + +- GIVEN a project reports Node 24 and no configured Bun runtime +- WHEN its other deployment controls also pass +- THEN runtime verification reports ready diff --git a/openspec/changes/verify-toolchain-runtime-pins/tasks.md b/openspec/changes/verify-toolchain-runtime-pins/tasks.md new file mode 100644 index 000000000..77a880575 --- /dev/null +++ b/openspec/changes/verify-toolchain-runtime-pins/tasks.md @@ -0,0 +1,8 @@ +# Tasks + +- [x] 1.1 Verify current head, complete review inventory and candidate version pins. +- [x] 1.2 Reproduce both false acceptances and run failing verifier regressions. +- [x] 2.1 Implement scoped workflow and live runtime checks without new dependencies. +- [x] 2.2 Pass focused tests, bootstrap proof, syntax/lint and strict specification checks. +- [ ] 3.1 Reconcile latest develop and complete independent review and normal full gates. +- [ ] 3.2 Publish fixes, resolve verified conversations and merge through protections. diff --git a/package.json b/package.json index d3a58f803..1ffed8761 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "version": "0.1.0", "private": true, "license": "AGPL-3.0-only", - "packageManager": "bun@1.3.14", + "packageManager": "bun@1.4.0", "workspaces": [ "apps/*", "packages/*", diff --git a/plans/004-remove-radix-dependencies.md b/plans/004-remove-radix-dependencies.md index 6aed48912..065221b2c 100644 --- a/plans/004-remove-radix-dependencies.md +++ b/plans/004-remove-radix-dependencies.md @@ -37,7 +37,7 @@ Verified: - `apps/admin/package.json:44` — `"@radix-ui/react-visually-hidden": "^1.2.4"` — unused (zero imports in `apps/admin`). - `apps/donor/package.json:34` — `"@radix-ui/react-tabs": "^1.1.13"` — unused (zero imports in `apps/donor`; donor uses `@asym/ui/components/shadcn/tabs`). - `bun.lock` — ~152 lines matching `radix` (the rollup package + transitive `@radix-ui/*` packages). -- Root `package.json` declares `"packageManager": "bun@1.3.14"` — all +- Root `package.json` declares `"packageManager": "bun@1.4.0"` — all dependency operations must use Bun. ## Commands you will need diff --git a/scripts/verify/bun-lock-drift.mjs b/scripts/verify/bun-lock-drift.mjs index b1978d15c..87475eb73 100644 --- a/scripts/verify/bun-lock-drift.mjs +++ b/scripts/verify/bun-lock-drift.mjs @@ -39,7 +39,47 @@ export const DEPENDENCY_FIELDS = [ export const ROOT_WORKSPACE_KEY = ""; const MANIFEST_SUFFIX = "/package.json"; -const REMEDIATION = "Run `bun install` and commit the updated bun.lock."; + +export const WORKSPACE_DRIFT_REMEDIATION = + "Run `bun install` and commit the updated bun.lock."; + +export const LOCKFILE_VERSION_REMEDIATION = + "Keep or restore lockfileVersion 0 or 1. Do not run `bun install` to rewrite bun.lock on Bun 1.4+."; + +export function isLockfileVersionViolation(violation) { + return violation.startsWith("bun.lock lockfileVersion "); +} + +export function formatBunLockDriftFailure(violations) { + if (violations.some((violation) => isLockfileVersionViolation(violation))) { + return [ + "bun.lock lockfileVersion is not supported:", + ...violations.map((violation) => `- ${violation}`), + LOCKFILE_VERSION_REMEDIATION, + ].join("\n"); + } + + return [ + "bun.lock is out of sync with workspace package.json files:", + ...violations.map((violation) => `- ${violation}`), + WORKSPACE_DRIFT_REMEDIATION, + ].join("\n"); +} + +export function collectUnsupportedLockfileVersion(lockfileVersion) { + if ( + typeof lockfileVersion === "number" && + Number.isInteger(lockfileVersion) && + lockfileVersion >= 0 && + lockfileVersion <= 1 + ) { + return []; + } + + return [ + `bun.lock lockfileVersion ${JSON.stringify(lockfileVersion)} is not supported. Keep lockfileVersion 0 or 1 until installed turbo prune can parse a rewritten lock.`, + ]; +} /** * `bun.lock` is JSONC-ish: it is JSON apart from trailing commas before `}` @@ -254,6 +294,13 @@ export async function readWorkspaceManifests(repoRoot = defaultRepoRoot) { export async function findBunLockDrift(repoRoot = defaultRepoRoot) { const lockText = await readFile(path.join(repoRoot, "bun.lock"), "utf8"); const lock = parseBunLock(lockText); + const versionViolations = collectUnsupportedLockfileVersion( + lock.lockfileVersion, + ); + + if (versionViolations.length > 0) { + return versionViolations; + } return collectBunLockDriftViolations({ lockWorkspaces: lock.workspaces ?? {}, @@ -268,11 +315,7 @@ async function main() { return; } - console.error("bun.lock is out of sync with workspace package.json files:"); - for (const violation of violations) { - console.error(`- ${violation}`); - } - console.error(REMEDIATION); + console.error(formatBunLockDriftFailure(violations)); process.exit(1); } diff --git a/scripts/verify/bun-version.mjs b/scripts/verify/bun-version.mjs index 7934d813b..1be279a72 100644 --- a/scripts/verify/bun-version.mjs +++ b/scripts/verify/bun-version.mjs @@ -1,16 +1,25 @@ #!/usr/bin/env node import { spawnSync } from "node:child_process"; -import { existsSync, readFileSync } from "node:fs"; +import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs"; import { homedir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; -const repoRoot = path.resolve( +const defaultRepoRoot = path.resolve( path.dirname(fileURLToPath(import.meta.url)), "../..", ); -const packageJsonPath = path.join(repoRoot, "package.json"); +const scriptPath = fileURLToPath(import.meta.url); +const STABLE_BUN_VERSION = /^\d+\.\d+\.\d+$/; + +function resolveExistingPath(filePath) { + try { + return realpathSync(filePath); + } catch { + return path.resolve(filePath); + } +} function candidateBunPaths() { const candidates = process.env.BUN_BINARY ? [process.env.BUN_BINARY] : []; @@ -32,7 +41,9 @@ function candidateBunPaths() { return [...new Set(candidates)]; } -function readExpectedVersion() { +export function readExpectedVersion(root = defaultRepoRoot) { + const packageJsonPath = path.join(root, "package.json"); + if (!existsSync(packageJsonPath)) { throw new Error(`missing root package.json at ${packageJsonPath}`); } @@ -52,7 +63,152 @@ function readExpectedVersion() { ); } - return match[1].replace(/^v/, ""); + const expected = match[1].replace(/^v/i, ""); + + if (!STABLE_BUN_VERSION.test(expected)) { + throw new Error( + `packageManager must pin a stable bun@x.y.z release, got: ${packageManager}`, + ); + } + + const bunVersionPath = path.join(root, ".bun-version"); + + if (!existsSync(bunVersionPath)) { + throw new Error("missing .bun-version; it must match packageManager"); + } + + const bunVersionFile = readFileSync(bunVersionPath, "utf8") + .trim() + .replace(/^v/i, ""); + + if (bunVersionFile !== expected) { + throw new Error( + `.bun-version (${bunVersionFile}) does not match packageManager bun@${expected}`, + ); + } + + return expected; +} + +export function isGitHubWorkflowFile(name) { + return name.endsWith(".yml") || name.endsWith(".yaml"); +} + +// This verifier runs before bun install during setup, so use Bun's built-in +// YAML parser without importing a package from node_modules. +function parseWorkflowYaml(source) { + for (const candidate of candidateBunPaths()) { + const useShell = process.platform === "win32" && candidate.endsWith(".cmd"); + const expression = + "process.stdout.write(JSON.stringify(Bun.YAML.parse(await Bun.stdin.text())))"; + const result = spawnSync( + candidate, + ["--eval", useShell ? `"${expression}"` : expression], + { + input: source, + encoding: "utf8", + shell: useShell, + stdio: ["pipe", "pipe", "ignore"], + }, + ); + if (result.error) continue; + if (result.status !== 0) continue; + return JSON.parse(result.stdout); + } + throw new Error("Unable to parse workflow YAML"); +} + +function isMapping(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function readWorkflowEnv(env, label, expected, errors) { + if (env == null) return {}; + if (!isMapping(env)) { + errors.push(`${label} env must be a static mapping`); + return {}; + } + if (Object.hasOwn(env, "BUN_VERSION") && env.BUN_VERSION !== expected) { + errors.push( + `${label} BUN_VERSION is ${String(env.BUN_VERSION)}, expected ${expected}`, + ); + } + return env; +} + +export function collectGitHubWorkflowBunPinDrift(root, expected) { + const workflowDir = path.join(root, ".github", "workflows"); + if (!existsSync(workflowDir)) return []; + + const errors = []; + for (const fileName of readdirSync(workflowDir).filter( + isGitHubWorkflowFile, + )) { + let workflow; + try { + workflow = parseWorkflowYaml( + readFileSync(path.join(workflowDir, fileName), "utf8"), + ); + } catch { + errors.push(`${fileName} is not valid workflow YAML`); + continue; + } + if (!isMapping(workflow) || !isMapping(workflow.jobs)) { + errors.push(`${fileName} must define a jobs mapping`); + continue; + } + + const workflowEnv = readWorkflowEnv( + workflow.env, + fileName, + expected, + errors, + ); + for (const [jobId, job] of Object.entries(workflow.jobs)) { + const jobLabel = `${fileName} job ${jobId}`; + if (!isMapping(job)) { + errors.push(`${jobLabel} must be a mapping`); + continue; + } + const jobEnv = readWorkflowEnv(job.env, jobLabel, expected, errors); + if (job.steps == null) continue; + if (!Array.isArray(job.steps)) { + errors.push(`${jobLabel} steps must be an array`); + continue; + } + + for (const [index, step] of job.steps.entries()) { + const stepLabel = `${jobLabel} step ${index + 1}`; + if (!isMapping(step)) { + errors.push(`${stepLabel} must be a mapping`); + continue; + } + const stepEnv = readWorkflowEnv(step.env, stepLabel, expected, errors); + if ( + typeof step.uses !== "string" || + !/^oven-sh\/setup-bun@/i.test(step.uses) + ) + continue; + + const version = step.with?.["bun-version"]; + if ( + typeof version !== "string" || + !/^\$\{\{\s*env\.BUN_VERSION\s*\}\}$/.test(version) + ) { + errors.push( + `${stepLabel} must set its own with.bun-version to \${{ env.BUN_VERSION }}`, + ); + } + const effectiveEnv = { ...workflowEnv, ...jobEnv, ...stepEnv }; + if (!Object.hasOwn(effectiveEnv, "BUN_VERSION")) { + errors.push( + `${stepLabel} uses oven-sh/setup-bun but has no BUN_VERSION env pin in scope`, + ); + } + } + } + } + return errors; } function readInstalledVersion() { @@ -71,11 +227,11 @@ function readInstalledVersion() { return null; } -function main() { +export function main(root = defaultRepoRoot) { let expected; try { - expected = readExpectedVersion(); + expected = readExpectedVersion(root); } catch (error) { console.error(`error: ${error.message}`); process.exit(2); @@ -100,7 +256,25 @@ function main() { process.exit(1); } + const workflowDrift = collectGitHubWorkflowBunPinDrift(root, expected); + + if (workflowDrift.length > 0) { + console.error( + "error: GitHub Actions Bun pin does not match packageManager.", + ); + for (const line of workflowDrift) { + console.error(` ${line}`); + } + process.exit(2); + } + console.log(`Bun version OK: bun@${installed}`); } -main(); +const isDirectRun = + Boolean(process.argv[1]) && + resolveExistingPath(process.argv[1]) === resolveExistingPath(scriptPath); + +if (isDirectRun) { + main(); +} diff --git a/scripts/verify/vercel-build-controls.mjs b/scripts/verify/vercel-build-controls.mjs index a2a336d0c..a578b2969 100644 --- a/scripts/verify/vercel-build-controls.mjs +++ b/scripts/verify/vercel-build-controls.mjs @@ -187,9 +187,18 @@ function buildMatrix(changedFiles) { ); } +function commandUsesBunRuntimeFlag(command) { + return typeof command === "string" && /(?:^|\s)--bun(?:\s|$)/.test(command); +} + export function validateLocalVercelConfig({ project, config }) { const checks = []; const branchGate = config?.git?.deploymentEnabled; + const bunRuntimeCommands = [ + config?.installCommand, + config?.buildCommand, + config?.ignoreCommand, + ].filter((command) => commandUsesBunRuntimeFlag(command)); requireCheck( checks, @@ -209,6 +218,20 @@ export function validateLocalVercelConfig({ project, config }) { `${project.key} vercel.json ignoreCommand`, config?.ignoreCommand ?? "", ); + requireCheck( + checks, + !Object.hasOwn(config ?? {}, "bunVersion"), + `${project.key} vercel.json omits bunVersion (Node Functions runtime)`, + Object.hasOwn(config ?? {}, "bunVersion") + ? String(config.bunVersion) + : "", + ); + requireCheck( + checks, + bunRuntimeCommands.length === 0, + `${project.key} vercel.json commands stay off bun --bun`, + bunRuntimeCommands[0] ?? "", + ); requireCheck( checks, branchGate?.["*"] === false && @@ -346,6 +369,18 @@ export function validateVercelProjectSettings({ project, settings }) { `${project.key} Vercel rootDirectory`, settings?.rootDirectory ?? "", ); + requireCheck( + checks, + settings?.nodeVersion === "24.x", + `${project.key} Vercel Node runtime is 24.x`, + settings?.nodeVersion ?? "", + ); + requireCheck( + checks, + settings?.bunVersion == null, + `${project.key} Vercel Bun runtime is not configured`, + settings?.bunVersion ?? "", + ); requireCheck( checks, settings?.enableAffectedProjectsDeployments === true, diff --git a/tests/unit/scripts/bun-lock-drift.test.ts b/tests/unit/scripts/bun-lock-drift.test.ts index 6fa656aad..508e30c7d 100644 --- a/tests/unit/scripts/bun-lock-drift.test.ts +++ b/tests/unit/scripts/bun-lock-drift.test.ts @@ -1,10 +1,18 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + import { describe, expect, it } from "vitest"; import { collectBunLockDriftViolations, + collectUnsupportedLockfileVersion, findBunLockDrift, + formatBunLockDriftFailure, + LOCKFILE_VERSION_REMEDIATION, parseBunLock, stripTrailingCommas, + WORKSPACE_DRIFT_REMEDIATION, } from "../../../scripts/verify/bun-lock-drift.mjs"; type Manifest = Record; @@ -220,8 +228,75 @@ describe("bun.lock workspace-manifest drift", () => { }); }); +describe("bun.lock lockfileVersion ceiling", () => { + it("accepts lockfileVersion 0 and 1", () => { + expect(collectUnsupportedLockfileVersion(0)).toEqual([]); + expect(collectUnsupportedLockfileVersion(1)).toEqual([]); + }); + + it("fails closed on lockfileVersion 2 or 3", () => { + expect(collectUnsupportedLockfileVersion(2)).toEqual([ + "bun.lock lockfileVersion 2 is not supported. Keep lockfileVersion 0 or 1 until installed turbo prune can parse a rewritten lock.", + ]); + expect(collectUnsupportedLockfileVersion(3)[0]).toContain( + "lockfileVersion 3", + ); + }); + + it("fails closed on a non-integer lockfileVersion", () => { + expect(collectUnsupportedLockfileVersion("1")[0]).toContain( + 'lockfileVersion "1"', + ); + }); + + it("findBunLockDrift returns the version ceiling before workspace drift", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "bun-lock-v2-")); + try { + writeFileSync( + path.join(dir, "bun.lock"), + '{ "lockfileVersion": 2, "workspaces": {} }\n', + ); + + await expect(findBunLockDrift(dir)).resolves.toEqual( + collectUnsupportedLockfileVersion(2), + ); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("does not tell operators to run bun install when lockfileVersion is unsupported", () => { + const message = formatBunLockDriftFailure( + collectUnsupportedLockfileVersion(2), + ); + + expect(message).toContain("lockfileVersion 2"); + expect(message).toContain(LOCKFILE_VERSION_REMEDIATION); + expect(message).not.toContain(WORKSPACE_DRIFT_REMEDIATION); + expect(message).not.toMatch(/Run `bun install`/); + }); + + it("still remediates workspace-manifest drift with bun install", () => { + const message = formatBunLockDriftFailure([ + 'package.json: dependencies "left-pad" is missing from bun.lock workspaces[""]', + ]); + + expect(message).toContain("out of sync with workspace package.json"); + expect(message).toContain(WORKSPACE_DRIFT_REMEDIATION); + }); +}); + describe("live repository state", () => { it("keeps bun.lock in sync with every workspace package.json", async () => { await expect(findBunLockDrift()).resolves.toEqual([]); }); + + it("keeps the committed bun.lock on lockfileVersion 1", () => { + const lock = parseBunLock( + readFileSync(path.join(process.cwd(), "bun.lock"), "utf8"), + ); + + expect(lock.lockfileVersion).toBe(1); + expect(lock.configVersion).toBe(1); + }); }); diff --git a/tests/unit/scripts/bun-pin-sync.test.ts b/tests/unit/scripts/bun-pin-sync.test.ts new file mode 100644 index 000000000..667f1a140 --- /dev/null +++ b/tests/unit/scripts/bun-pin-sync.test.ts @@ -0,0 +1,546 @@ +import { spawnSync } from "node:child_process"; +import { + copyFileSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + symlinkSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { + collectGitHubWorkflowBunPinDrift, + isGitHubWorkflowFile, + readExpectedVersion, +} from "../../../scripts/verify/bun-version.mjs"; + +const fixtureRoots = new Set(); + +afterEach(() => { + for (const root of fixtureRoots) { + rmSync(root, { recursive: true, force: true }); + } + fixtureRoots.clear(); +}); + +const repoRoot = process.cwd(); +const verifierSourcePath = path.join( + repoRoot, + "scripts", + "verify", + "bun-version.mjs", +); + +/** Official stable pin verified from GitHub `bun-v1.4.0` and npm `bun@latest`. */ +const VERIFIED_STABLE_BUN = "1.4.0"; +const PINNED_TURBO = "2.10.0"; + +const WORKFLOW_DIR = path.join(repoRoot, ".github", "workflows"); + +function readPackageJson(): { + packageManager?: string; + devDependencies?: Record; +} { + return JSON.parse(readFileSync(path.join(repoRoot, "package.json"), "utf8")); +} + +function countMatches(source: string, pattern: RegExp): number { + return source.match(pattern)?.length ?? 0; +} + +function writePinFixture(options: { + packageManager: string; + bunVersion?: string | null; +}): string { + const dir = mkdtempSync(path.join(tmpdir(), "bun-version-mjs-")); + fixtureRoots.add(dir); + writeFileSync( + path.join(dir, "package.json"), + `${JSON.stringify({ packageManager: options.packageManager }, null, 2)}\n`, + ); + + if (options.bunVersion !== null && options.bunVersion !== undefined) { + writeFileSync(path.join(dir, ".bun-version"), `${options.bunVersion}\n`); + } + + return dir; +} + +function writeIsolatedVerifier(options: { + packageManager: string; + bunVersion?: string | null; +}): { repoRoot: string; scriptPath: string } { + const isolatedRoot = writePinFixture(options); + const scriptDir = path.join(isolatedRoot, "scripts", "verify"); + mkdirSync(scriptDir, { recursive: true }); + const scriptPath = path.join(scriptDir, "bun-version.mjs"); + copyFileSync(verifierSourcePath, scriptPath); + return { repoRoot: isolatedRoot, scriptPath }; +} + +function writeIsolatedWorkflow( + repoRoot: string, + bunVersion: string, + fileName = "ci.yml", +) { + const workflowDir = path.join(repoRoot, ".github", "workflows"); + mkdirSync(workflowDir, { recursive: true }); + writeFileSync( + path.join(workflowDir, fileName), + [ + "name: ci", + "on: push", + "env:", + ` BUN_VERSION: "${bunVersion}"`, + "jobs:", + " check:", + " runs-on: ubuntu-latest", + " steps:", + " - uses: oven-sh/setup-bun@v2", + " with:", + " bun-version: ${{ env.BUN_VERSION }}", + "", + ].join("\n"), + ); +} + +function spawnVerifier(scriptPath: string, env?: NodeJS.ProcessEnv) { + return spawnSync(process.execPath, [scriptPath], { + encoding: "utf8", + env: env ? { ...process.env, ...env } : process.env, + }); +} + +describe("Bun toolchain pin sync", () => { + const packageJson = readPackageJson(); + + it("readExpectedVersion returns the verified stable pin", () => { + expect(readExpectedVersion(repoRoot)).toBe(VERIFIED_STABLE_BUN); + expect(packageJson.packageManager).toBe(`bun@${VERIFIED_STABLE_BUN}`); + }); + + it("keeps every first-party GitHub Actions BUN_VERSION on the same pin", () => { + const workflowFiles = + readdirSync(WORKFLOW_DIR).filter(isGitHubWorkflowFile); + const bunPins: string[] = []; + + for (const fileName of workflowFiles) { + const workflow = readFileSync(path.join(WORKFLOW_DIR, fileName), "utf8"); + const matches = [...workflow.matchAll(/^\s*BUN_VERSION:\s*"([^"]+)"/gm)]; + for (const match of matches) { + bunPins.push(`${fileName}:${match[1]}`); + } + } + + expect(bunPins.length).toBeGreaterThan(0); + expect( + collectGitHubWorkflowBunPinDrift(repoRoot, VERIFIED_STABLE_BUN), + ).toEqual([]); + }); + + it("pins every oven-sh/setup-bun step to env.BUN_VERSION", () => { + const workflowFiles = + readdirSync(WORKFLOW_DIR).filter(isGitHubWorkflowFile); + let scannedWorkflows = 0; + + for (const fileName of workflowFiles) { + const workflow = readFileSync(path.join(WORKFLOW_DIR, fileName), "utf8"); + const setupBunCount = countMatches( + workflow, + /uses:\s*oven-sh\/setup-bun@/g, + ); + if (setupBunCount === 0) { + continue; + } + + scannedWorkflows += 1; + } + + expect(scannedWorkflows).toBeGreaterThan(0); + expect( + collectGitHubWorkflowBunPinDrift(repoRoot, VERIFIED_STABLE_BUN), + ).toEqual([]); + expect(isGitHubWorkflowFile("ci.yml")).toBe(true); + expect(isGitHubWorkflowFile("ci.yaml")).toBe(true); + expect(isGitHubWorkflowFile("README.md")).toBe(false); + }); + + it("keeps first-party Vercel apps on the Node Functions runtime", () => { + const appRoots = ["admin", "donor", "missionary"] as const; + + for (const app of appRoots) { + const vercelConfig = JSON.parse( + readFileSync(path.join(repoRoot, "apps", app, "vercel.json"), "utf8"), + ) as { + bunVersion?: string; + installCommand?: string | null; + buildCommand?: string | null; + }; + + const buildCommand = vercelConfig.buildCommand ?? ""; + + expect( + vercelConfig.bunVersion, + `${app} vercel.json bunVersion (Functions runtime opt-in)`, + ).toBeUndefined(); + expect(vercelConfig.installCommand, `${app} installCommand`).toBe( + "bun install --cwd ../.. --frozen-lockfile", + ); + expect(vercelConfig.installCommand).not.toContain("--save-text-lockfile"); + expect(buildCommand, `${app} buildCommand`).not.toMatch(/--bun\b/); + + const appPackage = JSON.parse( + readFileSync(path.join(repoRoot, "apps", app, "package.json"), "utf8"), + ) as { scripts?: Record }; + + for (const scriptName of ["dev", "build", "start"] as const) { + const script = appPackage.scripts?.[scriptName] ?? ""; + expect(script, `${app} scripts.${scriptName}`).not.toMatch(/--bun\b/); + expect(script, `${app} scripts.${scriptName}`).toMatch(/^next /); + } + } + }); + + it("keeps the installed Turborepo pin at the lockfile v1 parser", () => { + expect(packageJson.devDependencies?.turbo).toBe(PINNED_TURBO); + }); +}); + +describe("bun-version.mjs pin contract", () => { + it("accepts a matching stable pin", () => { + const root = writePinFixture({ + packageManager: "bun@1.4.0", + bunVersion: "1.4.0", + }); + + expect(readExpectedVersion(root)).toBe("1.4.0"); + }); + + it("accepts a matching pin that used a leading v", () => { + const root = writePinFixture({ + packageManager: "bun@v1.4.0", + bunVersion: "v1.4.0", + }); + + expect(readExpectedVersion(root)).toBe("1.4.0"); + }); + + it("rejects a canary packageManager pin", () => { + const root = writePinFixture({ + packageManager: "bun@1.4.0-canary.20260820.1", + bunVersion: "1.4.0-canary.20260820.1", + }); + + expect(() => readExpectedVersion(root)).toThrow(/stable bun@x\.y\.z/); + }); + + it("rejects an rc packageManager pin", () => { + const root = writePinFixture({ + packageManager: "bun@1.4.0-rc.1", + bunVersion: "1.4.0-rc.1", + }); + + expect(() => readExpectedVersion(root)).toThrow(/stable bun@x\.y\.z/); + }); + + it("rejects a beta packageManager pin", () => { + const root = writePinFixture({ + packageManager: "bun@1.4.0-beta.1", + bunVersion: "1.4.0-beta.1", + }); + + expect(() => readExpectedVersion(root)).toThrow(/stable bun@x\.y\.z/); + }); + + it("rejects a missing .bun-version file", () => { + const root = writePinFixture({ + packageManager: "bun@1.4.0", + bunVersion: null, + }); + + expect(() => readExpectedVersion(root)).toThrow(/missing \.bun-version/); + }); + + it("rejects a .bun-version that does not match packageManager", () => { + const root = writePinFixture({ + packageManager: "bun@1.4.0", + bunVersion: "1.3.14", + }); + + expect(() => readExpectedVersion(root)).toThrow( + /\.bun-version \(1\.3\.14\) does not match packageManager bun@1\.4\.0/, + ); + }); + + it("reports a mismatched GitHub workflow BUN_VERSION before the process check", () => { + const root = writePinFixture({ + packageManager: "bun@1.4.0", + bunVersion: "1.4.0", + }); + try { + writeIsolatedWorkflow(root, "9.9.9", "ci.yaml"); + + expect(collectGitHubWorkflowBunPinDrift(root, "1.4.0")).toEqual([ + "ci.yaml BUN_VERSION is 9.9.9, expected 1.4.0", + ]); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("does not require workflow files when the fixture has none", () => { + const root = writePinFixture({ + packageManager: "bun@1.4.0", + bunVersion: "1.4.0", + }); + try { + expect(collectGitHubWorkflowBunPinDrift(root, "1.4.0")).toEqual([]); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); + +describe("workflow setup-bun step ownership", () => { + function drift(source: string) { + const root = writePinFixture({ + packageManager: "bun@1.4.0", + bunVersion: "1.4.0", + }); + try { + mkdirSync(path.join(root, ".github", "workflows"), { recursive: true }); + writeFileSync(path.join(root, ".github", "workflows", "ci.yml"), source); + return collectGitHubWorkflowBunPinDrift(root, "1.4.0"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + } + + const prefix = + 'env:\n BUN_VERSION: "1.4.0"\njobs:\n check:\n runs-on: ubuntu-latest\n'; + const pinnedStep = + " - uses: oven-sh/setup-bun@v2\n with:\n bun-version: ${{ env.BUN_VERSION }}\n"; + const badStep = + ' - uses: oven-sh/setup-bun@v2\n with:\n bun-version: "9.9.9"\n'; + + it("rejects a wrong setup pin masked by a commented env pin", () => { + expect( + drift( + prefix + + " steps:\n" + + badStep + + "# bun-version: ${{ env.BUN_VERSION }}\n", + ), + ).not.toEqual([]); + }); + + it("rejects a wrong setup pin masked by an unrelated action input", () => { + expect( + drift( + prefix + + " steps:\n" + + badStep + + " - uses: example/action@v1\n with:\n bun-version: ${{ env.BUN_VERSION }}\n", + ), + ).not.toEqual([]); + }); + + it("does not take another job's BUN_VERSION as the setup job's environment", () => { + expect( + drift( + 'jobs:\n unrelated:\n env:\n BUN_VERSION: "1.4.0"\n runs-on: ubuntu-latest\n steps: []\n check:\n runs-on: ubuntu-latest\n steps:\n' + + pinnedStep, + ), + ).not.toEqual([]); + }); + + it("rejects a shadowing job environment with a different quoted pin", () => { + expect( + drift( + prefix + + " env:\n BUN_VERSION: '9.9.9'\n steps:\n" + + pinnedStep, + ), + ).not.toEqual([]); + }); + + it("rejects a shadowing setup-step environment with a different unquoted pin", () => { + expect( + drift( + prefix + + " steps:\n" + + pinnedStep + + " env:\n BUN_VERSION: 9.9.9\n", + ), + ).not.toEqual([]); + }); + + it("checks quoted action references rather than skipping their setup step", () => { + expect( + drift( + prefix + + " steps:\n" + + badStep.replace("oven-sh/setup-bun@v2", '"oven-sh/setup-bun@v2"'), + ), + ).not.toEqual([]); + }); + + it("checks every setup step even when a comment balances the old counts", () => { + expect( + drift( + prefix + + " steps:\n" + + pinnedStep + + badStep + + "# bun-version: ${{ env.BUN_VERSION }}\n", + ), + ).not.toEqual([]); + }); + + it("does not read a run-script string as an environment declaration", () => { + expect( + drift( + 'jobs:\n check:\n runs-on: ubuntu-latest\n steps:\n - run: |\n BUN_VERSION: "1.4.0"\n' + + pinnedStep, + ), + ).not.toEqual([]); + }); + + it.each(["'1.4.0'", "1.4.0"])( + "accepts a canonical YAML scalar pin %s", + (value) => { + expect( + drift(prefix.replace('"1.4.0"', value) + " steps:\n" + pinnedStep), + ).toEqual([]); + }, + ); + + it("accepts correctly scoped job and step env indirection", () => { + expect( + drift( + 'jobs:\n check:\n runs-on: ubuntu-latest\n env:\n BUN_VERSION: "1.4.0"\n steps:\n' + + pinnedStep + + ' env:\n BUN_VERSION: "1.4.0"\n', + ), + ).toEqual([]); + }); + + it("supports YAML aliases for the workflow environment", () => { + expect( + drift( + prefix.replace("env:", "env: &toolchain") + + " env: *toolchain\n steps:\n" + + pinnedStep, + ), + ).toEqual([]); + }); + + it("fails closed for malformed workflow YAML", () => { + expect(drift("jobs: [\n")).not.toEqual([]); + }); +}); + +describe("bun-version.mjs CLI", () => { + it("validates workflow pins before dependency installation", () => { + const { repoRoot, scriptPath } = writeIsolatedVerifier({ + packageManager: "bun@1.4.0", + bunVersion: "1.4.0", + }); + try { + rmSync(path.join(repoRoot, "node_modules"), { + recursive: true, + force: true, + }); + writeIsolatedWorkflow(repoRoot, "1.4.0"); + + const result = spawnVerifier(scriptPath); + + expect(result.stderr).toBe(""); + expect(result.status).toBe(0); + expect(result.stdout).toContain("Bun version OK: bun@1.4.0"); + } finally { + rmSync(repoRoot, { recursive: true, force: true }); + } + }); + + it("exits 0 when invoked with the real script path and matching pins", () => { + const result = spawnVerifier(verifierSourcePath); + + expect(result.status).toBe(0); + expect(result.stdout).toContain( + `Bun version OK: bun@${VERIFIED_STABLE_BUN}`, + ); + }); + + it.skipIf(process.platform === "win32")( + "still runs main when invoked through a symlink", + () => { + const linkPath = path.join( + tmpdir(), + `bun-version-link-${Date.now()}.mjs`, + ); + symlinkSync(verifierSourcePath, linkPath); + + try { + const result = spawnVerifier(linkPath); + + expect(result.status).toBe(0); + expect(result.stdout).toContain( + `Bun version OK: bun@${VERIFIED_STABLE_BUN}`, + ); + expect(result.stdout).not.toBe(""); + } finally { + unlinkSync(linkPath); + } + }, + ); + + it("exits 2 when the isolated pin files are not a stable x.y.z", () => { + const { scriptPath } = writeIsolatedVerifier({ + packageManager: "bun@1.4.0-rc.1", + bunVersion: "1.4.0-rc.1", + }); + + const result = spawnVerifier(scriptPath); + + expect(result.status).toBe(2); + expect(result.stderr).toMatch(/stable bun@x\.y\.z/); + }); + + it("exits 1 when an isolated matching pin disagrees with installed Bun", () => { + const { scriptPath } = writeIsolatedVerifier({ + packageManager: "bun@0.0.1", + bunVersion: "0.0.1", + }); + + const result = spawnVerifier(scriptPath); + + expect(result.status).toBe(1); + expect(result.stderr).toContain("error: Bun version mismatch."); + }); + + it("exits 2 when an isolated workflow BUN_VERSION disagrees with the package pin", () => { + const { repoRoot, scriptPath } = writeIsolatedVerifier({ + packageManager: "bun@1.4.0", + bunVersion: "1.4.0", + }); + try { + writeIsolatedWorkflow(repoRoot, "9.9.9"); + + const result = spawnVerifier(scriptPath); + + expect(result.status).toBe(2); + expect(result.stderr).toContain("9.9.9"); + expect(result.stderr).toMatch(/workflow|BUN_VERSION/i); + } finally { + rmSync(repoRoot, { recursive: true, force: true }); + } + }); +}); diff --git a/tests/unit/scripts/bun-version.test.ts b/tests/unit/scripts/bun-version.test.ts index d640334f4..130004a15 100644 --- a/tests/unit/scripts/bun-version.test.ts +++ b/tests/unit/scripts/bun-version.test.ts @@ -1,12 +1,38 @@ -import { mkdtempSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; -import { spawnSync } from "node:child_process"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; + +const fixtureRoots = new Set(); + +afterEach(() => { + for (const root of fixtureRoots) { + rmSync(root, { recursive: true, force: true }); + } + fixtureRoots.clear(); +}); + +function createTempFixture(prefix: string): string { + const root = mkdtempSync(path.join(tmpdir(), prefix)); + fixtureRoots.add(root); + return root; +} const repoRoot = process.cwd(); const scriptPath = path.join(repoRoot, "scripts", "verify", "bun-version.sh"); +const expectedPackageManager = ( + JSON.parse(readFileSync(path.join(repoRoot, "package.json"), "utf8")) as { + packageManager: string; + } +).packageManager; const bashSystemPath = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; @@ -89,7 +115,9 @@ describe("bun version guard", () => { const result = runGuard(); expect(result.status).toBe(0); - expect(result.stdout).toContain("Bun version OK: bun@1.3.14"); + expect(result.stdout).toContain( + `Bun version OK: ${expectedPackageManager}`, + ); expect(result.stderr).toBe(""); }, 30000, @@ -98,7 +126,7 @@ describe("bun version guard", () => { itIfFakeBunCanShadowPath( "fails fast when the Bun binary does not match packageManager", () => { - const fakeBinDir = mkdtempSync(path.join(tmpdir(), "fake-bun-")); + const fakeBinDir = createTempFixture("fake-bun-"); const bashFakeBinDir = toBashPath(fakeBinDir); const realBun = toBashPath(resolveBunPath()); @@ -124,7 +152,7 @@ describe("bun version guard", () => { expect(result.status).toBe(1); expect(result.stderr).toContain("error: Bun version mismatch."); expect(result.stderr).toContain( - "expected (package.json packageManager): bun@1.3.14", + `expected (package.json packageManager): ${expectedPackageManager}`, ); expect(result.stderr).toContain( "installed (bun --version): bun@1.3.4", @@ -132,4 +160,59 @@ describe("bun version guard", () => { }, 30000, ); + + itIfFakeBunCanShadowPath( + "tries later Bun candidates when the PATH bun shim exits non-zero", + () => { + const fakeBinDir = createTempFixture("fake-bun-"); + const bunInstallDir = createTempFixture("bun-install-"); + const bunInstallBinDir = path.join(bunInstallDir, "bin"); + const bashFakeBinDir = toBashPath(fakeBinDir); + const realBun = toBashPath(resolveBunPath()); + mkdirSync(bunInstallBinDir); + + writeFileSync( + path.join(fakeBinDir, "bun"), + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + 'if [[ "${1:-}" == "--version" ]]; then', + " exit 1", + "fi", + "exit 42", + ].join("\n"), + { mode: 0o755 }, + ); + writeFileSync( + path.join(bunInstallBinDir, "bun"), + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + 'if [[ "${1:-}" == "--version" ]]; then', + ` echo "${expectedPackageManager.replace(/^bun@/, "")}"`, + " exit 0", + "fi", + 'exec "$REAL_BUN" "$@"', + ].join("\n"), + { mode: 0o755 }, + ); + + const result = runGuard({ + BUN_INSTALL: toBashPath(bunInstallDir), + PATH: `${bashFakeBinDir}:${bashSystemPath}:${process.env.PATH ?? ""}`, + REAL_BUN: realBun, + }); + + expect(result.status).toBe(0); + expect(result.stdout).toContain( + `Bun version OK: ${expectedPackageManager}`, + ); + expect(result.stderr).toBe(""); + }, + 30000, + ); }); + +// Pin-contract and CLI/symlink coverage lives in bun-pin-sync.test.ts so +// Windows `scripts/verify/unit-tests.mjs` still runs it. This file stays +// bash-spawn only because that runner excludes it on Windows. diff --git a/tests/unit/scripts/ci-integration-workflow.contract.test.ts b/tests/unit/scripts/ci-integration-workflow.contract.test.ts index da8fcf668..85378090b 100644 --- a/tests/unit/scripts/ci-integration-workflow.contract.test.ts +++ b/tests/unit/scripts/ci-integration-workflow.contract.test.ts @@ -126,6 +126,24 @@ describe("ci-integration workflow contract", () => { expect(workflow).not.toContain("run: bun run test:e2e --project=chromium"); }); + it("installs Playwright before smoke dev servers and proves demo auth", () => { + const testE2eSmoke = jobBlock(workflow, "test-e2e-smoke"); + const installAt = testE2eSmoke.indexOf("name: Install Playwright Chromium"); + const startDonorAt = testE2eSmoke.indexOf("name: Start donor app"); + const waitDonorAt = testE2eSmoke.indexOf( + "name: Wait for donor health endpoint", + ); + const startAdminAt = testE2eSmoke.indexOf("name: Start admin app"); + + expect(installAt).toBeGreaterThanOrEqual(0); + expect(startDonorAt).toBeGreaterThan(installAt); + expect(waitDonorAt).toBeGreaterThan(startDonorAt); + expect(startAdminAt).toBeGreaterThan(waitDonorAt); + expect(testE2eSmoke).toContain( + "http://127.0.0.1:3005/api/auth/demo-account", + ); + }); + it("keeps the blocking smoke job on the shared Bun install contract", () => { const smoke = jobBlock(workflow, "smoke"); const testE2eSmoke = jobBlock(workflow, "test-e2e-smoke"); diff --git a/tests/unit/scripts/preview-smoke-scope.test.ts b/tests/unit/scripts/preview-smoke-scope.test.ts index ff73df71b..bf9fe431e 100644 --- a/tests/unit/scripts/preview-smoke-scope.test.ts +++ b/tests/unit/scripts/preview-smoke-scope.test.ts @@ -25,6 +25,15 @@ describe("resolvePreviewSmokeScope", () => { expect(scope.scope).toBe("all"); }); + it("targets all surfaces when the Bun pin file changes", () => { + const scope = resolvePreviewSmokeScope([".bun-version"]); + + expect(scope.admin).toBe(true); + expect(scope.donor).toBe(true); + expect(scope.missionary).toBe(true); + expect(scope.scope).toBe("all"); + }); + it("targets all surfaces for smoke test and Playwright config changes", () => { const smokeSpec = resolvePreviewSmokeScope([ "tests/e2e/support-hub.smoke.spec.ts", diff --git a/tests/unit/scripts/vercel-build-controls.test.ts b/tests/unit/scripts/vercel-build-controls.test.ts index e6792f7eb..eba4df2eb 100644 --- a/tests/unit/scripts/vercel-build-controls.test.ts +++ b/tests/unit/scripts/vercel-build-controls.test.ts @@ -28,6 +28,17 @@ const localConfig = { }, }; +const runtimeSettings = { + id: adminProject.projectId, + name: "admin", + rootDirectory: "apps/admin", + nodeVersion: "24.x", + bunVersion: null, + enableAffectedProjectsDeployments: true, + previewDeploymentsDisabled: true, + resourceConfig: { buildQueue: { configuration: "WAIT_FOR_NAMESPACE_QUEUE" } }, +}; + describe("Vercel build controls verifier", () => { it("maps the three app projects to expected build-control commands", () => { expect(EXPECTED_PROJECTS).toEqual([ @@ -93,12 +104,120 @@ describe("Vercel build controls verifier", () => { ); }); + it("rejects bunVersion because that opts Vercel Functions off Node onto Bun", () => { + // https://vercel.com/changelog/bun-1-4-is-now-available-in-vercel-functions + // bunVersion is the Functions/Middleware runtime, not the install tool. + // Next.js on Bun also requires `bun run --bun next build`. Neither belongs + // in these Node 24 Next.js apps. + for (const bunVersion of ["1.4.x", "1.x"] as const) { + const checks = validateLocalVercelConfig({ + project: adminProject, + config: { + ...localConfig, + bunVersion, + }, + }); + + expect(checks).toContainEqual( + expect.objectContaining({ + ok: false, + label: "admin vercel.json omits bunVersion (Node Functions runtime)", + detail: bunVersion, + }), + ); + } + }); + + it("rejects bun --bun in Vercel install, build, and ignore commands", () => { + const cases = [ + { + override: { + installCommand: "bun --bun install --cwd ../.. --frozen-lockfile", + }, + detail: "bun --bun install --cwd ../.. --frozen-lockfile", + }, + { + override: { buildCommand: "cd ../.. && bun run --bun build:admin" }, + detail: "cd ../.. && bun run --bun build:admin", + }, + { + override: { + ignoreCommand: + "bun --bun ../../scripts/vercel/should-ignore-build.mjs admin", + }, + detail: "bun --bun ../../scripts/vercel/should-ignore-build.mjs admin", + }, + ] as const; + + for (const { override, detail } of cases) { + const checks = validateLocalVercelConfig({ + project: adminProject, + config: { + ...localConfig, + ...override, + }, + }); + + expect(checks).toContainEqual( + expect.objectContaining({ + ok: false, + label: "admin vercel.json commands stay off bun --bun", + detail, + }), + ); + } + }); + it("validates the ignored-build decision matrix", () => { expect(validateIgnoredBuildDecisionMatrix().every((item) => item.ok)).toBe( true, ); }); + it.each(["22.x", undefined, null])( + "rejects a live Node runtime outside Node 24: %s", + (nodeVersion) => { + const checks = validateVercelProjectSettings({ + project: adminProject, + settings: { ...runtimeSettings, nodeVersion }, + }); + expect(checks).toContainEqual( + expect.objectContaining({ + ok: false, + label: "admin Vercel Node runtime is 24.x", + }), + ); + }, + ); + + it.each(["1.4.x", "1.x", ""])( + "rejects a configured live Bun runtime: %s", + (bunVersion) => { + const checks = validateVercelProjectSettings({ + project: adminProject, + settings: { ...runtimeSettings, bunVersion }, + }); + expect(checks).toContainEqual( + expect.objectContaining({ + ok: false, + label: "admin Vercel Bun runtime is not configured", + }), + ); + }, + ); + + it.each([null, undefined])( + "accepts an unset live Bun runtime: %s", + (bunVersion) => { + expect( + validateVercelProjectSettings({ + project: adminProject, + settings: { ...runtimeSettings, bunVersion }, + }).every((check) => check.ok), + ).toBe(true); + }, + ); + it("validates live Vercel project settings without requiring command settings", () => { const checks = validateVercelProjectSettings({ project: adminProject, @@ -106,6 +225,8 @@ describe("Vercel build controls verifier", () => { id: adminProject.projectId, name: "admin", rootDirectory: "apps/admin", + nodeVersion: "24.x", + bunVersion: null, buildCommand: "bun run build", installCommand: "bun install --cwd ../.. --frozen-lockfile", enableAffectedProjectsDeployments: true, diff --git a/tests/unit/scripts/vercel-ignore-build.test.ts b/tests/unit/scripts/vercel-ignore-build.test.ts index c679665b3..62516bc02 100644 --- a/tests/unit/scripts/vercel-ignore-build.test.ts +++ b/tests/unit/scripts/vercel-ignore-build.test.ts @@ -63,6 +63,7 @@ describe("Vercel ignored-build helper", () => { "packages/api/src/profile/queries.ts", "packages/ui/components/button.tsx", "bun.lock", + ".bun-version", "package.json", "turbo.json", "scripts/resolve-monorepo-root.mjs", diff --git a/tests/unit/workflows/qa-smoke-preview-deploy.test.ts b/tests/unit/workflows/qa-smoke-preview-deploy.test.ts index 1891663c6..779ac90a2 100644 --- a/tests/unit/workflows/qa-smoke-preview-deploy.test.ts +++ b/tests/unit/workflows/qa-smoke-preview-deploy.test.ts @@ -92,7 +92,13 @@ describe("qa smoke preview deployment workflow", () => { }); it("uses the shared Bun version and portable install backend", () => { - expect(workflow).toContain('BUN_VERSION: "1.3.14"'); + const packageManager = ( + JSON.parse(readFileSync("package.json", "utf8")) as { + packageManager: string; + } + ).packageManager; + const bunVersion = packageManager.replace(/^bun@/, ""); + expect(workflow).toContain(`BUN_VERSION: "${bunVersion}"`); expect(workflow).toContain("bun-version: ${{ env.BUN_VERSION }}"); expect(workflow).toContain("bun ci --no-cache --backend=copyfile"); expect(workflow).not.toContain('bun-version: "1.3.4"');