Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
ci: Linux on one Boat VM inside ci.yml, and Windows only where a change can break it
milind-sonie9a8f53332a5
diff --git a/.github/workflows/boat.yml b/.github/workflows/boat.ymldeleted file mode 100644index f4a440dbc6..0000000000--- a/.github/workflows/boat.yml+++ /dev/null@@ -1,69 +0,0 @@-# Linux checks on Boat (https://docs.boat.dev/ci), so pull requests get results without waiting for GitHub's hosted-# runners. The same split as ci.yml's Linux leg (scripts/ci-scope.mjs: 8 shards, every e2e file, one file at a time per-# shard, so one VM per shard): lint and typecheck on one boat-large VM, each vitest shard on its own boat-large VM (8 vCPU, 16 GB: GitHub's-# ubuntu-latest has 16 GB, and typecheck runs out of heap on 8 GB).-# Runs only while the repository variable BOAT_CI is "on", and only for this repository's own branches (a fork's pull-# request never runs on Boat; Boat also refuses runs by anyone outside its allow-list). ci.yml is unchanged.-name: Boat--on:- pull_request:- push:- branches: [main]--concurrency:- group: boat-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.ref }}- cancel-in-progress: ${{ github.event_name == 'pull_request' }}--permissions:- contents: read--jobs:- static:- name: Lint and typecheck (Boat)- if: vars.BOAT_CI == 'on' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository)- runs-on: boat-large- timeout-minutes: 20- steps:- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- - uses: pnpm/action-setup@ff378ebe6b225b0680b81c1ad4498ae0d1d3a5e3 # v6.0.10- - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0- with:- node-version: 24- cache: pnpm- - run: pnpm install --frozen-lockfile- - run: pnpm lint- - run: pnpm typecheck- env:- NODE_OPTIONS: --max-old-space-size=12288-- vitest:- name: Linux vitest (Boat, shard ${{ matrix.shard }}/8)- if: vars.BOAT_CI == 'on' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository)- runs-on: boat-large- timeout-minutes: 30- strategy:- fail-fast: false- matrix:- shard: [1, 2, 3, 4, 5, 6, 7, 8]- steps:- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- - uses: pnpm/action-setup@ff378ebe6b225b0680b81c1ad4498ae0d1d3a5e3 # v6.0.10- - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0- with:- node-version: 24- cache: pnpm- - run: pnpm install --frozen-lockfile- - name: vitest shard ${{ matrix.shard }}/8 (every e2e file, as ci.yml's Linux shards)- env:- OMB_VITEST_E2E: all- OMB_VITEST_RETRY_LOG: ${{ runner.temp }}/vitest-retries.jsonl- run: pnpm exec vitest run --shard=${{ matrix.shard }}/8 --reporter=default --reporter=github-actions- - name: Retried tests- if: always()- env:- OMB_VITEST_RETRY_LOG: ${{ runner.temp }}/vitest-retries.jsonl- run: node scripts/testing/ci-retry-summary.mjs- - name: Node tests (broker, Electron main)- if: matrix.shard == 1- run: pnpm broker:test && pnpm test:electrondiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1d21181592..d918071ec0 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1,3 +1,11 @@+# Boat (https://docs.boat.dev/ci): while the repository variable BOAT_CI is "on", a run from this repository's own+# branches (a push to main, a pull request, a merge group) that the repository owner both authored and started does its+# Linux work on one 16 vCPU Boat VM, one Boat start per run: the static job runs on boat-xlarge and, after its checks,+# runs the Linux vitest shards, behavior evals and the Linux packaged server smoke side by side+# (scripts/ci-linux-lanes.mjs) instead of as GitHub-hosted jobs. Boat runs a public repository's job only for the users+# on its allow-list (`boat ci public`), and a job it refuses waits for a runner that never comes, so every other run, a+# fork's, the nightly and manual runs (the release lane among them), and every run while BOAT_CI is anything else run on+# GitHub's runners exactly as before. `boat ci` and the dashboard's CI on Boat VMs tab list the Boat jobs (docs/ci.md).name: CIon:@@ -41,14 +49,26 @@ jobs:# platform, and every smoke reports on its own. One final `CI` check# aggregates the required jobs (see docs/ci.md for ruleset migration).static:- name: typecheck + lint- runs-on: ubuntu-latest- timeout-minutes: 15+ name: >-+ ${{ vars.BOAT_CI == 'on' && contains(fromJSON('["push", "pull_request", "merge_group"]'), github.event_name)+ && github.actor == github.repository_owner && github.triggering_actor == github.repository_owner+ && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository+ && github.event.pull_request.user.login == github.repository_owner)+ && 'typecheck + lint + Linux tests (Boat)' || 'typecheck + lint' }}+ runs-on: >-+ ${{ vars.BOAT_CI == 'on' && contains(fromJSON('["push", "pull_request", "merge_group"]'), github.event_name)+ && github.actor == github.repository_owner && github.triggering_actor == github.repository_owner+ && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository+ && github.event.pull_request.user.login == github.repository_owner)+ && 'boat-xlarge' || 'ubuntu-latest' }}+ timeout-minutes: ${{ vars.BOAT_CI == 'on' && 45 || 15 }}permissions:contents: read# ci-scope reads whether the commit before a push got its own green run,# and whether the pushed commit already passed the merge queueactions: read+ # and a pull request's labels as they are when the run starts+ pull-requests: readoutputs:jobs: ${{ steps.scope.outputs.jobs }}vitest_os: ${{ steps.scope.outputs.vitest_os }}@@ -70,10 +90,11 @@ jobs:id: scopeenv:GH_TOKEN: ${{ github.token }}+ OMB_CI_LINUX_IN_STATIC: ${{ runner.environment == 'self-hosted' }}run: node scripts/ci-scope.mjs- run: pnpm install --frozen-lockfile- name: Verify CI selection and documentation references- run: pnpm exec vitest run scripts/ci-scope.test.ts scripts/ci-workflow.test.ts scripts/testing/verification-docs.test.ts+ run: pnpm exec vitest run scripts/ci-scope.test.ts scripts/ci-linux-lanes.test.ts scripts/ci-workflow.test.ts scripts/testing/verification-docs.test.ts- name: Validate locale catalogsrun: pnpm i18n:check- run: pnpm lint@@ -86,18 +107,56 @@ jobs:- name: production UI buildif: steps.scope.outputs.build == 'true'run: pnpm exec vite build+ # The rest runs only on a Boat VM, where ci-scope moved the Linux jobs' work into this job.+ - name: Remove what Boat installs and GitHub's runners lack+ if: steps.scope.outputs.linux_lanes+ # The server starts an engine it finds on PATH: Boat's Hermes then downloads its own Python, Node and tools+ # into each test's home, about nine seconds for every test that adds a bot. A Team Cloud runs its turns in a+ # bubblewrap box wherever bwrap works: here, once the step below drops the capability bwrap refuses to start+ # with, and never on a GitHub runner.+ run: sudo rm -f /usr/bin/bwrap /usr/local/bin/{agent,claude,codex,cua-driver,cursor-agent,hermes,hermes-acp,hermes-agent,kimi,openclaw,opencode,pi,prime-agent,vibe,vibe-acp}+ - name: Prepare Electron test runtime+ if: steps.scope.outputs.linux_lanes+ run: node --input-type=commonjs -e "require('electron')"+ - name: Linux tests (vitest shards, behavior evals, packaged server), side by side+ if: steps.scope.outputs.linux_lanes+ env:+ OMB_CI_LINUX_LANES: ${{ steps.scope.outputs.linux_lanes }}+ # Boat's image sets en_US.UTF-8, whose collation is Intl's default; GitHub's runners use C.UTF-8 and UTC.+ LANG: C.UTF-8+ LC_ALL: C.UTF-8+ TZ: UTC+ # Boat's runner gives every process cap_dac_read_search as an ambient capability, so a test can still read a+ # file it set to mode 000, and Boat's desktop sets DISPLAY. GitHub's runners have neither.+ shell: setpriv --inh-caps=-all --ambient-caps=-all -- env -u DISPLAY -u XAUTHORITY bash --noprofile --norc -eo pipefail {0}+ run: node scripts/ci-linux-lanes.mjs+ - name: Report flaky tests that needed a retry+ if: ${{ !cancelled() && steps.scope.outputs.linux_lanes }}+ env:+ OMB_VITEST_RETRY_LOG: ${{ runner.temp }}/vitest-retries.jsonl+ run: node scripts/testing/ci-retry-summary.mjs+ - name: Upload eval run reports on failure+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ if: failure() && steps.scope.outputs.linux_lanes+ with:+ name: behavior-evals-reports-${{ github.sha }}-${{ github.run_attempt }}+ path: evals/reports/runs/+ if-no-files-found: warn+ retention-days: 7vitest:# Admit the expensive runner fan-out only after the quick checks pass.# A failing preflight still fails the required gates; nothing is waived.needs: staticif: contains(needs.static.outputs.jobs, '"vitest"')- # scripts/ci-scope.mjs picks the platforms and their shards: PRs run Linux- # and Windows (the account runs only five macOS jobs at a time), main- # pushes and merge groups Linux, and the full lane (nightly, manual runs,- # the release lane) all three. A pull request that+ # scripts/ci-scope.mjs picks the platforms and their shards: PRs run Linux,+ # and Windows only when their change can break Windows or they carry the+ # windows label (the account runs only five macOS jobs at a time), main+ # pushes and merge groups Linux and Windows, and the full lane (nightly,+ # manual runs, the release lane) all three. A pull request that# cannot affect a platform's results leaves it out, and one that changes- # only translations runs the locale tests alone. Linux runs every file;+ # only translations runs the locale tests alone. On a Boat VM the static+ # job runs the Linux entries itself. Linux runs every file;# Windows and macOS run every file but the e2e files that test only OMB's# own logic (OMB_VITEST_E2E=host, scripts/testing/host-e2e.ts). The split# is deterministic, so a failure names the same shard on every run, and@@ -589,10 +648,10 @@ jobs:if: contains(needs.static.outputs.jobs, '"browser-driver"')# Advisory, outside the CI gate until it has run green for a while: the# omb-cdp S4 conformance suites and the new browser's checklist and viewer- # suites on the runner's own Google Chrome (PRs run Linux and Windows, the- # full lane all three; pushes to main and merge groups leave it out), then- # on Linux inside the server image's runtime as a non-root- # user. Every S4 suite also fails when its trace holds Runtime.enable or+ # suites on the runner's own Google Chrome (PRs run Linux, and Windows+ # where the vitest shards do; the full lane all three; pushes to main and+ # merge groups leave it out), then on Linux inside the server image's+ # runtime as a non-root user. Every S4 suite also fails when its trace holds Runtime.enable or# another forbidden CDP method (docs/ci.md).name: browser driver S4 (${{ matrix.os }})strategy:diff --git a/docs/ci.md b/docs/ci.mdindex 30eb634913..0935b40f0e 100644--- a/docs/ci.md+++ b/docs/ci.md@@ -13,8 +13,8 @@ too) into areas, and runs only the jobs some area can affect:| docs | `*.md` at the root, everything under `docs/` and `apps/docs/`, `.github/FUNDING.yml` | lint, the docs tests (the three vitest files that read the docs) on Linux || locales | `src/locales/*.json` except `en.json`, `src/locales/*.test.ts` | the build, the locale tests: every `src/` test and `scripts/generate-locale.test.mjs` in two Linux shards, with the Electron node tests || web | the rest of `src/`, `public/`, the root `*-preview.html` pages | the build, the eight Linux shards, the renderer smoke |-| script tests | `scripts/**/*.test.*` | the Linux and Windows shards, the renderer smoke, browser identity |-| server | `server/`, `shared/`, `enterprise/`, `companion/`, `evals/`, `skills/`, `deploy/`, the composio broker, the Dockerfile, and the renderer files the server or a smoke loads | the build, Linux and Windows shards, behavior evals, packaged server, open-source edition, the macOS smokes, renderer smoke, browser identity, browser driver, Linux package |+| script tests | `scripts/**/*.test.*` | the Linux shards (and Windows', see Windows), the renderer smoke, browser identity |+| server | `server/`, `shared/`, `enterprise/`, `companion/`, `evals/`, `skills/`, `deploy/`, the composio broker, the Dockerfile, and the renderer files the server or a smoke loads | the build, Linux shards (and Windows', see Windows), behavior evals, packaged server, open-source edition, the macOS smokes, renderer smoke, browser identity, browser driver, Linux package || desktop | `electron/`, `build/`, `electron-builder.yml`, `index.html` | the same as server || control plane | `cloudflare/control-plane/` | the control-plane job || everything | anything else: `.github/` workflows, `package.json`, the lockfile and workspace, tsconfig, vite and vitest config, `third_party/`, `scripts/` code, unknown paths | every job |@@ -46,15 +46,15 @@ sets (`laneOf` in `scripts/ci-scope.mjs`):| Event | Lane | What runs || --- | --- | --- |-| `pull_request` | its areas | the table above, with Linux and Windows shards |-| `push` to main, `merge_group` | main | static (typecheck, lint, the build), the eight Linux shards with the Electron node tests, the macOS smokes job, behavior evals, the Linux packaged server smoke, the open-source edition, the control plane, the renderer smoke and Linux browser identity |+| `pull_request` | its areas | the table above, with Linux shards, and Windows jobs only for a change that can break Windows (Windows below) |+| `push` to main, `merge_group` | main | static (typecheck, lint, the build), the eight Linux and eight Windows shards with the Electron node tests, the macOS smokes job, behavior evals, the Linux and Windows packaged server smokes, the open-source edition, the control plane, the renderer smoke and Linux and Windows browser identity || `schedule` (nightly, 21:17 UTC), `workflow_dispatch` (manual runs, the release branch's CI that `prepare-release.yml` starts, and the release lane) | full | every job on every platform: also the Windows and macOS shards, the Windows packaged server and Windows CUA smokes, Windows and macOS browser identity, the browser driver on all three, the Linux package and the Linux ARM64 installer |-The main lane keeps to runners that do not hold main up: Linux, and one macOS-job. The Windows and macOS shards, and every smoke that needs a Windows or a-second macOS runner, wait for the night or a release. A change that breaks-only Windows or macOS shows up in its own PR (PRs still run the Windows shards-wherever a change can affect them), in the nightly run, or in the release+The main lane runs Linux, Windows and one macOS job. The macOS shards, the+Windows CUA smoke and every smoke that needs a second macOS runner wait for+the night or a release. A change that breaks only Windows shows up in its own+PR when it can (Windows below), and otherwise in main's run after it merges; a+change that breaks only macOS shows up in the nightly run or in the releaselane, which only an emergency `ship_without_ci` release skips.- A push to main is scoped by its own commits (`before..after`): docs only@@ -143,13 +143,48 @@ seven (four Vitest shards, two smokes, the iOS job with its hour-longsimulator suite). With 25 open PRs the macOS jobs waited a median of six and ahalf hours. Now:-- A PR runs the Vitest shards on Ubuntu and Windows, a push to main or a merge- group on Ubuntu; the full lane adds four macOS shards, which run the host e2e- files only. Only a couple of test blocks are macOS-only.+- A PR runs the Vitest shards on Ubuntu (and Windows where its change can+ break Windows), a push to main or a merge group on Ubuntu and Windows; the+ full lane adds four macOS shards, which run the host e2e files only. Only a+ couple of test blocks are macOS-only.- Every PR's, push's and merge group's macOS checks are one job: thepackaged-server smoke and the Electron smokes.- `ci-stop-closed.yml` cancels a PR's CI run when the PR is merged or closed. PR runs share a group named by the PR number (`ci-pr-<n>`), never by `github.ref`: a merged PR's closed event reports the base branch as `github.ref`, which made every merge cancel main's CI (fixed Oct 3 2026).+## Windows++Windows runners are slow to get and a Windows shard takes as long as a Linux+one, so a pull request runs the Windows jobs (the eight shards, the packaged+server smoke, browser identity, the browser driver and, for a change that can+affect anything, the CUA smoke) only when its change can break Windows first+(`windowsReason` in `scripts/ci-scope.mjs`):++- the PR carries the `windows` label;+- a path names Windows (`win`, `win32`, `windows`, `nsis`, `powershell` as a+ word of the path, `.ps1`, `.cmd`, `.bat`, `.exe`), or is the desktop app and+ its installer (`electron/`, `build/`, `electron-builder.yml`), the+ dependencies (`package.json`, the lockfile and workspace, `.npmrc`,+ `third_party/`), `.gitattributes`, `vite.config.ts`, a script that builds,+ bundles, prepares, packages, stages or smokes the app, or what decides how+ the Windows shards run (`ci.yml`, `ci-scope.mjs`, the host e2e list, the+ shard weights, the retry list and runner, `server/testing/host-timeout.ts`);+- it changes one of the e2e files the Windows shards also run+ (`scripts/testing/host-e2e.ts`);+- an added or removed line of its code (not docs or translations) names+ Windows: `win32`, `Windows`, `windows-latest`, PowerShell, `cmd.exe`,+ `.exe`, `path.win32`, `USERPROFILE`, `APPDATA`, `LOCALAPPDATA`, `PATHEXT`,+ `ComSpec`, `windowsHide` or `windowsVerbatimArguments`.++The static job's log says which one (`CI scope: Windows runs for …`). Every+other PR leaves Windows to main's push run after it merges, the nightly run and+the release lane. Over October 2026's last 300 merges this ran Windows on 37%+of PRs instead of 81%.++To run Windows on any PR, add the `windows` label, then re-run the CI workflow+(or push): the static job reads the PR's labels when it runs. Adding the label+alone starts nothing, because a run for every label change would cancel the+PR's running checks.+## Browser driver (S4)`browser driver S4 (<os>)` runs the omb-cdp conformance suites@@ -184,8 +219,9 @@ answered by an upload, a dropdown list drawn by the viewer, a download servedto it, the page's cursor and copied text).- The job uses the runner's installed Google Chrome (`OMB_CDP_E2E=1`) on the- same platforms as the vitest shards: Linux and Windows on PRs, all three in- the full lane. Pushes to main and merge groups leave it out. Linux runs+ same platforms as the vitest shards: Linux, and Windows where a PR runs it,+ on PRs, all three in the full lane. Pushes to main and merge groups leave it+ out. Linux runsunder Xvfb so the headed-identity case has a display.- On Linux it then builds the server image's `runtime` stage and runs thesuites inside it as a non-root user against the image's Chrome for@@ -226,8 +262,8 @@ and the release lane among them) by their event and branch.(`scripts/release-ci.mjs`, overlapping the platform builds). A run counts onlywhen its `CI` gate passed and every platform's every vitest shard ran andpassed. A scoped run (docs- or version-only, vitest skipped) is never proof,-and neither is a partial one: a push to main or a merge group runs Linux's-shards only. The script accepts, in order:+and neither is a partial one: a push to main or a merge group runs Linux's and+Windows' shards only. The script accepts, in order:1. a finished full run on the release commit itself;2. a finished full run on any commit with the same git tree: the all-OS manual@@ -284,6 +320,52 @@ The packaged-server smoke asks the OS for free ports (listen on port 0)instead of picking them at random: a random pick inside a range Windowsreserves failed with `listen EACCES 127.0.0.1:497xx`.+## Linux on Boat++GitHub runs a limited number of jobs at once for the whole account, and each+PR's run used to be about thirty of them, so with twenty agents opening PRs a+run waited hours for runners. While the repository variable **`BOAT_CI`** is+`on`, a run's Linux work goes to one [Boat](https://docs.boat.dev/ci) VM+instead (Settings → Secrets and variables → Actions → Variables; anything but+`on` switches it off, and CI runs as it always has).++- **Which runs.** A push to main, a merge group, and a PR whose branch is in+ this repository, when the repository owner authored the PR and both pushed+ and started the run (`github.actor`, `github.triggering_actor`). Boat runs a+ public repository's job only for the users on its allow-list+ (`boat ci public milind-soni on --users "milind-soni"`), and a job it+ refuses waits for a runner that never comes, so every other run stays on+ GitHub: forks, teammates, bots, re-runs by anyone else, the nightly run and+ manual runs (the release lane needs every platform's shards by name). To+ give a teammate Boat too, add them to Boat's list and to the condition in+ `ci.yml`'s `static` job.+- **What changes.** `static` runs on `boat-xlarge` (16 vCPU, 32 GB) and is+ named "typecheck + lint + Linux tests (Boat)". After its usual checks it+ runs the Linux vitest shards, behavior evals and the Linux packaged server+ smoke side by side as lanes of that VM (`scripts/ci-linux-lanes.mjs`, the+ same commands as their GitHub jobs), and prints each lane's log in a group+ when it ends. `ci-scope.mjs` leaves those jobs out of the selection, so the+ `CI` gate reads them as skipped by design and `static`'s result covers+ them. The Windows jobs, the macOS smokes, the advisory Linux jobs (open-source+ edition, control plane, renderer smoke, browser identity and driver, Linux+ package, ARM installer) and the `CI` gate stay on GitHub's runners.+- **The VM made like a GitHub runner.** Boat's runner gives its processes+ `cap_dac_read_search`, and its image has a desktop (`DISPLAY`), the+ coding agents (Claude, Codex, Hermes, …) and a working `bwrap`. The lanes run+ under `setpriv` without the capability, with `DISPLAY` unset, `C.UTF-8` and+ UTC, and the step before them deletes the agents and `bwrap`. Otherwise+ permission tests read files set to mode 000, the server starts Boat's+ Hermes in every test home, and Team Cloud turns run in boxes they never get+ on GitHub.+- **Cost.** One Boat start per run, and the account's daily start limit is+ shared with customers' Cloud computers: keep it to one job. The Linux leg+ takes about 20 minutes.+- **Where to look.** `boat ci` (setup, problems, the last jobs), `boat ci job+ <job id>` and `boat ci logs <job id> --follow`, or the CI on Boat VMs tab+ of the Boat dashboard. The job id is the GitHub job's id.+- **If Boat is down.** Set `BOAT_CI` to `off`: new runs go back to GitHub's+ runners. A queued Boat job does not move; cancel the run and re-run it.+## Required checkThe `main-ci-gate` ruleset requires the single `CI` check (it replaced thediff --git a/scripts/ci-linux-lanes.mjs b/scripts/ci-linux-lanes.mjsnew file mode 100644index 0000000000..18189775b1--- /dev/null+++ b/scripts/ci-linux-lanes.mjs@@ -0,0 +1,105 @@+import { spawn } from "node:child_process";+import { appendFileSync, mkdirSync, openSync, readFileSync } from "node:fs";+import { join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++// The Linux jobs' work as lanes of one machine: when the static job runs on a Boat VM (ci.yml, BOAT_CI), the vitest+// job's Linux shards, behavior evals and the Linux packaged server smoke run there as processes side by side, each+// lane its commands in order. ci-workflow.test.ts holds every command equal to the job step it stands for.++/** The vitest job's two steps for one Linux matrix entry, with the step's environment. */+export function vitestLane(entry, retryLog) {+ return {+ name: `vitest (ubuntu-latest, ${entry.part})`,+ env: { OMB_VITEST_RETRY_LOG: retryLog, OMB_VITEST_E2E: entry.e2e, OMB_VITEST_SUBSET: entry.files },+ commands: [+ `pnpm exec vitest run ${entry.files} --shard=${entry.shard}/${entry.shards} --reporter=default --reporter=github-actions`,+ ...(entry.node_tests ? ["pnpm broker:test && pnpm test:electron"] : []),+ ],+ };+}++export const EVALS_LANE = {+ name: "behavior evals (offline tiers 1-3)",+ env: {},+ commands: [+ "pnpm exec tsc -p evals/tsconfig.json",+ "pnpm exec vitest run --config evals/vitest.config.ts --reporter=default --reporter=github-actions",+ "pnpm eval",+ "pnpm eval --golden",+ `output="$(pnpm eval --live 2>&1)"+printf '%s\\n' "$output"+printf '%s\\n' "$output" | grep -q "live tier skipped"+`,+ ],+};++export const PACKAGED_SERVER_LANE = { name: "packaged server smoke (ubuntu-latest)", env: {}, commands: ["pnpm test:packaged-server"] };++/** Every lane of ci-scope's `linux_lanes` plan. */+export function lanesFor(plan, retryLog) {+ return [+ ...plan.vitest.map((entry) => vitestLane(entry, retryLog)),+ ...(plan.evals ? [EVALS_LANE] : []),+ ...(plan.packaged_server ? [PACKAGED_SERVER_LANE] : []),+ ];+}++const minutes = (ms) => `${Math.floor(ms / 60_000)}m${String(Math.round((ms % 60_000) / 1000)).padStart(2, "0")}s`;++/** Runs the lanes at once and prints each one's log whole when it ends. Resolves to the lanes that failed. */+export async function runLanes(lanes, { dir, timeoutMs, heartbeatMs = 60_000, log = console.log, summary = () => {} }) {+ mkdirSync(dir, { recursive: true });+ const started = Date.now();+ const rows = [];+ const running = new Map();+ const finished = lanes.map((lane, index) => new Promise((done) => {+ const file = join(dir, `${index + 1}.log`);+ const out = openSync(file, "w");+ const child = spawn("bash", ["-eo", "pipefail", "-c", lane.commands.join("\n")], {+ env: { ...process.env, ...lane.env }, stdio: ["ignore", out, out], detached: true,+ });+ running.set(lane.name, child);+ // Each lane has its own process group, so a timeout or a cancelled job ends its servers and fake CLIs too.+ const timer = setTimeout(() => {+ log(`::error title=${lane.name}::still running after ${minutes(timeoutMs)}, so it was stopped`);+ try { process.kill(-child.pid, "SIGKILL"); } catch { /* already gone */ }+ }, timeoutMs);+ child.on("close", (code, signal) => {+ clearTimeout(timer);+ running.delete(lane.name);+ const took = minutes(Date.now() - started);+ const verdict = code === 0 ? "passed" : `FAILED (${signal ?? `exit ${code}`})`;+ log(`::group::${lane.name}: ${verdict} after ${took}`);+ log(readFileSync(file, "utf8").trimEnd());+ log("::endgroup::");+ if (code !== 0) log(`::error title=${lane.name}::${verdict}; its log is in the group of that name`);+ rows.push({ name: lane.name, verdict, took });+ done(code === 0 ? null : lane.name);+ });+ }));+ const heartbeat = setInterval(() => log(`${minutes(Date.now() - started)}: still running ${[...running.keys()].join(", ")}`), heartbeatMs);+ const stop = () => { for (const child of running.values()) try { process.kill(-child.pid, "SIGKILL"); } catch { /* already gone */ } };+ process.once("SIGTERM", stop);+ process.once("SIGINT", stop);+ const failed = (await Promise.all(finished)).filter(Boolean);+ clearInterval(heartbeat);+ process.off("SIGTERM", stop);+ process.off("SIGINT", stop);+ summary(["| Linux lane | Result | Time |", "|---|---|---|", ...rows.map((row) => `| ${row.name} | ${row.verdict} | ${row.took} |`), ""].join("\n"));+ return failed;+}++if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const plan = JSON.parse(process.env.OMB_CI_LINUX_LANES ?? "");+ const temp = process.env.RUNNER_TEMP ?? "/tmp";+ const failed = await runLanes(lanesFor(plan, join(temp, "vitest-retries.jsonl")), {+ dir: join(temp, "linux-lanes"),+ timeoutMs: Number(process.env.OMB_CI_LANE_TIMEOUT_MINUTES ?? 30) * 60_000,+ summary: (markdown) => process.env.GITHUB_STEP_SUMMARY && appendFileSync(process.env.GITHUB_STEP_SUMMARY, markdown),+ });+ if (failed.length) {+ console.log(`\n${failed.length} Linux lane(s) failed: ${failed.join(", ")}`);+ process.exit(1);+ }+}diff --git a/scripts/ci-linux-lanes.test.ts b/scripts/ci-linux-lanes.test.tsnew file mode 100644index 0000000000..3e1dc9ece1--- /dev/null+++ b/scripts/ci-linux-lanes.test.ts@@ -0,0 +1,61 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { EVALS_LANE, lanesFor, PACKAGED_SERVER_LANE, runLanes, vitestLane } from "./ci-linux-lanes.mjs";+import { vitestMatrix } from "./ci-scope.mjs";++const temporaryDirectories: string[] = [];+afterEach(() => {+ for (const directory of temporaryDirectories.splice(0)) rmSync(directory, { recursive: true, force: true });+});++function scratch() {+ const directory = mkdtempSync(join(tmpdir(), "omb-ci-lanes-"));+ temporaryDirectories.push(directory);+ return directory;+}++describe("Linux lanes", () => {+ it("gives every Linux shard its own lane, the node tests only on the first, then evals and the packaged server", () => {+ const shards = vitestMatrix(["ubuntu-latest"]).include;+ const lanes = lanesFor({ vitest: shards, evals: true, packaged_server: true }, "/t/retries.jsonl");+ expect(lanes.map((lane) => lane.name)).toEqual([+ ...shards.map((entry) => `vitest (ubuntu-latest, ${entry.part})`), EVALS_LANE.name, PACKAGED_SERVER_LANE.name,+ ]);+ expect(lanes[0]).toEqual({+ name: "vitest (ubuntu-latest, shard 1/8)",+ env: { OMB_VITEST_RETRY_LOG: "/t/retries.jsonl", OMB_VITEST_E2E: "all", OMB_VITEST_SUBSET: "" },+ commands: ["pnpm exec vitest run --shard=1/8 --reporter=default --reporter=github-actions", "pnpm broker:test && pnpm test:electron"],+ });+ expect(lanes.slice(1, 8).every((lane) => lane.commands.length === 1)).toBe(true);+ });++ it("runs a subset's files and leaves out what the plan leaves out", () => {+ const entry = { os: "ubuntu-latest", part: "docs tests", shard: 1, shards: 1, files: "a.test.ts b.test.ts", e2e: "all", node_tests: false };+ expect(lanesFor({ vitest: [entry], evals: false, packaged_server: false }, "/r")).toEqual([vitestLane(entry, "/r")]);+ expect(vitestLane(entry, "/r").commands).toEqual(["pnpm exec vitest run a.test.ts b.test.ts --shard=1/1 --reporter=default --reporter=github-actions"]);+ expect(lanesFor({ vitest: [], evals: true, packaged_server: false }, "/r")).toEqual([EVALS_LANE]);+ });++ it("runs lanes at once, prints each log whole when it ends, and names every lane that failed or ran out of time", async () => {+ const lines: string[] = [];+ let summary = "";+ const failed = await runLanes([+ { name: "slow pass", env: { WORD: "late" }, commands: ["sleep 0.6", "echo \"$WORD one\"", "echo two"] },+ { name: "quick fail", env: {}, commands: ["echo before", "exit 3", "echo never"] },+ { name: "hang", env: {}, commands: ["echo hanging", "sleep 30"] },+ ], { dir: scratch(), timeoutMs: 1_500, heartbeatMs: 250, log: (line) => lines.push(line), summary: (text) => { summary = text; } });+ expect(failed.sort()).toEqual(["hang", "quick fail"]);+ const groups = lines.filter((line) => line.startsWith("::group::"));+ expect(groups[0]).toMatch(/^::group::quick fail: FAILED \(exit 3\) after 0m0\ds$/);+ expect(groups[1]).toMatch(/^::group::slow pass: passed after 0m0\ds$/);+ expect(groups[2]).toMatch(/^::group::hang: FAILED \(SIGKILL\) after 0m0[12]s$/);+ expect(lines[lines.indexOf(groups[1]) + 1]).toBe("late one\ntwo");+ expect(lines[lines.indexOf(groups[0]) + 1]).toBe("before");+ expect(lines).toContain("::error title=hang::still running after 0m02s, so it was stopped");+ expect(lines.some((line) => /still running .*hang/.test(line))).toBe(true);+ expect(summary).toContain("| quick fail | FAILED (exit 3) |");+ expect(summary).toContain("| slow pass | passed |");+ });+});diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex 245dad7f26..68218bdb41 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -83,12 +83,15 @@ export function areaOf(file) {export const FULL_SCOPE = { areas: ["everything"], checks: [...EVERY_CHECK].sort() };-/** A push to main and a merge group: the build, every test file on Linux, the macOS smokes and the Linux checks no- * longer than a shard. The Windows and macOS shards and smokes, the Linux package, the browser driver and the ARM- * installer run in the full lane only: nightly, manual runs and the release lane. */+/** A push to main and a merge group: the build, every test file on Linux and the Windows shards, the macOS smokes and+ * the Linux checks no longer than a shard. The macOS shards, the Windows CUA smoke, the Linux package, the browser driver+ * and the ARM installer run in the full lane only: nightly, manual runs and the release lane. */export const MAIN_SCOPE = {areas: ["main"],- checks: ["behavior-evals", "browser-identity", "build", "control-plane", "electron-smokes", "foss", "linux-tests", "packaged-server", "ui-smoke"],+ checks: [+ "behavior-evals", "browser-identity", "build", "control-plane", "electron-smokes", "foss", "host-tests", "linux-tests", "packaged-server",+ "ui-smoke",+ ],};/** A push whose commit already passed the CI gate in the merge queue: only the control-plane checks the broker deploy needs. */@@ -101,6 +104,43 @@ export function selectCiScope(files) {return { areas, checks: [...new Set(areas.flatMap((area) => AREA_CHECKS[area]))].sort() };}+/** The pull request label that runs the Windows jobs whatever the change. */+export const WINDOWS_LABEL = "windows";++/** Paths whose change can break Windows first: Windows by name, the desktop app and its installer, the dependencies,+ * the scripts that build, package or smoke the app, and what decides how the Windows shards run. */+export const WINDOWS_PATH = new RegExp([+ String.raw`(?:^|[/._-])(?:win|win32|win64|windows|nsis|powershell|pwsh)(?:[/._-]|$)`,+ String.raw`\.(?:ps1|psm1|psd1|cmd|bat|exe|msi|nsh|nsi)$`,+ String.raw`^(?:electron|build|third_party)/`,+ String.raw`^(?:electron-builder\.yml|package\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|\.npmrc|\.gitattributes|vite\.config\.ts)$`,+ String.raw`^\.github/workflows/ci\.yml$|^scripts/ci-scope\.mjs$`,+ String.raw`^scripts/testing/(?:host-e2e\.ts|duration-sequencer\.ts|vitest-shard-weights\.json|ci-retry-[^/]+)$|^server/testing/host-timeout\.ts$`,+ String.raw`^scripts/(?:build|bundle|prepare|package|smoke|after-pack|stage)[^/]*$`,+].join("|"), "i");++/** A changed line of code that names Windows or one of its APIs. */+export const WINDOWS_TEXT = new RegExp([+ String.raw`\bwin32\b|\bWindows\b|\bwindows-latest\b|[Pp]ower[Ss]hell|\bpwsh\b|\bcmd\.exe\b|\.exe\b|\bpath\.win32\b`,+ String.raw`\b(?:USERPROFILE|LOCALAPPDATA|APPDATA|PATHEXT|ComSpec)\b|\bwindows(?:Hide|VerbatimArguments)\b`,+].join("|"));++/** Why a pull request runs the Windows jobs, or null when nothing in it is Windows-sensitive: its label, a path above,+ * an e2e file the Windows shards also run (`hostE2e`), or a changed line in `lines` (`git diff -U0` of its code). */+export function windowsReason({ files, labels = [], hostE2e = [], lines = () => [] }) {+ if (labels.includes(WINDOWS_LABEL)) return `the "${WINDOWS_LABEL}" label`;+ const file = files.find((path) => WINDOWS_PATH.test(path) || hostE2e.includes(path));+ if (file) return file;+ let changed;+ try {+ changed = lines();+ } catch (error) {+ return `a change whose lines could not be read (${error.message})`;+ }+ const line = changed.find((text) => /^[+-](?![+-]{2} )/.test(text) && WINDOWS_TEXT.test(text));+ return line ? `the changed line ${JSON.stringify(line.slice(0, 80))}` : null;+}+/** True when two package.json texts differ only in the top-level "version"* (the release bump, prepare-release.yml). Anything else that changed, a* reordered key included, or text that is not a JSON object, is false. */@@ -135,11 +175,12 @@ export function selectPushScope(files, show) {// macOS runners are the scarce ones (five at a time for the whole account),// and only a couple of test blocks are macOS-only, so a PR runs the suite on-// Linux and Windows, and a push to main or a merge group on Linux. The full lane-// adds macOS. A PR that can affect the macOS smokes still runs them.+// Linux, and on Windows only when its change can break Windows (windowsReason);+// a push to main and a merge group run Linux and Windows. The full lane adds+// macOS. A PR that can affect the macOS smokes still runs them.export const ALL_OS = ["macos-latest", "ubuntu-latest", "windows-latest"];-const PR_OS = ["ubuntu-latest", "windows-latest"];-const MAIN_OS = ["ubuntu-latest"];+export const LINUX_OS = ["ubuntu-latest"];+export const WINDOWS_OS = ["ubuntu-latest", "windows-latest"];/** Events whose runs test every platform: the nightly run, manual runs and the release lane (a manual run). */export const FULL_LANE_EVENTS = ["schedule", "workflow_dispatch"];@@ -180,7 +221,8 @@ export function ciOutputs({ checks }, oses) {});}}- const jobs = SELECTABLE_JOBS.filter((job) => (job === "vitest" ? include.length > 0 : checks.includes(job)));+ const jobs = SELECTABLE_JOBS.filter((job) => (job === "vitest" ? include.length > 0+ : job === "windows-cua" ? checks.includes(job) && oses.includes("windows-latest") : checks.includes(job)));return {build: checks.includes("build"),jobs,@@ -192,6 +234,29 @@ export function ciOutputs({ checks }, oses) {};}+/** The outputs for a static job that does the Linux work itself (on a Boat VM, `OMB_CI_LINUX_IN_STATIC`): the Linux+ * vitest entries, behavior evals and the Linux packaged server smoke become `linux_lanes`+ * (scripts/ci-linux-lanes.mjs), and the jobs left with nothing to run drop out of the selection. */+export function moveLinuxIntoStatic(outputs) {+ const vitest = outputs.jobs.includes("vitest") ? outputs.vitest_matrix.include : [];+ const others = vitest.filter((entry) => entry.os !== "ubuntu-latest");+ const packagedOs = outputs.packaged_server_os.filter((os) => os !== "ubuntu-latest");+ const packaged = outputs.jobs.includes("packaged-server");+ return {+ ...outputs,+ jobs: outputs.jobs.filter((job) => job !== "behavior-evals" && !(job === "vitest" && others.length === 0)+ && !(job === "packaged-server" && packagedOs.length === 0)),+ // A job that drops out keeps its old matrix: GitHub refuses an empty one, even for a skipped job.+ vitest_matrix: others.length > 0 ? { include: others } : outputs.vitest_matrix,+ packaged_server_os: packaged && packagedOs.length > 0 ? packagedOs : outputs.packaged_server_os,+ linux_lanes: {+ vitest: vitest.filter((entry) => entry.os === "ubuntu-latest"),+ evals: outputs.jobs.includes("behavior-evals"),+ packaged_server: packaged && outputs.packaged_server_os.includes("ubuntu-latest"),+ },+ };+}+const SHA = /^[a-f\d]{40}(?:[a-f\d]{24})?$/i;const git = (args) => execFileSync("git", args, { encoding: "utf8", timeout: 30_000, stdio: ["ignore", "pipe", "pipe"] });@@ -203,6 +268,13 @@ function changedFiles(range) {return diff.slice(0, -1).split("\0");}+/** The added and removed lines of a range's code, docs and translations left out. */+function changedCodeLines(range) {+ return execFileSync("git", [+ "diff", "-U0", "--no-renames", "--no-color", "--no-ext-diff", range, "--", ".", ":(exclude)*.md", ":(exclude)docs/**", ":(exclude)src/locales/**",+ ], { encoding: "utf8", timeout: 30_000, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] }).split("\n");+}+async function github(path) {const { GH_TOKEN, GITHUB_REPOSITORY, GITHUB_API_URL = "https://api.github.com" } = process.env;if (!GH_TOKEN || !GITHUB_REPOSITORY) throw new Error("GH_TOKEN and GITHUB_REPOSITORY are needed to read CI runs");@@ -216,6 +288,19 @@ async function github(path) {const ciRuns = async (sha) => (await github(`/actions/workflows/ci.yml/runs?head_sha=${sha}&per_page=100`)).workflow_runs;+/** A pull request's labels as they are now, so a label added after the push counts when the run is re-run; the+ * event's own list when GitHub cannot be read. */+async function pullRequestLabels(pr) {+ const fromEvent = (Array.isArray(pr?.labels) ? pr.labels : []).map((label) => label?.name).filter((name) => typeof name === "string");+ if (!Number.isSafeInteger(pr?.number) || !process.env.GH_TOKEN || !process.env.GITHUB_REPOSITORY) return fromEvent;+ try {+ return (await github(`/issues/${pr.number}/labels?per_page=100`)).map((label) => label.name);+ } catch (error) {+ console.warn(`CI scope: reading the pull request's labels from its event (${error.message})`);+ return fromEvent;+ }+}+/** Did the commit before this push get a green CI run of its own? Main keeps* one run going and one waiting, and a push replaces the waiting run: if the* previous commit's run was replaced, its changes were never tested, so this@@ -238,7 +323,7 @@ async function passedMergeQueue(sha) {if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {const lane = laneOf(process.env.GITHUB_EVENT_NAME);let scope = lane === "main" ? MAIN_SCOPE : FULL_SCOPE;- let vitestOs = lane === "main" ? MAIN_OS : ALL_OS;+ let vitestOs = lane === "main" ? WINDOWS_OS : ALL_OS;if (lane === "pr") {try {const { pull_request: pr } = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, "utf8"));@@ -247,8 +332,20 @@ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.urif (![base, head].every((sha) => typeof sha === "string" && SHA.test(sha))) {throw new Error("Missing or invalid pull request commit SHAs");}- scope = selectCiScope(changedFiles(`${base}...${head}`));- vitestOs = PR_OS;+ const files = changedFiles(`${base}...${head}`);+ scope = selectCiScope(files);+ vitestOs = LINUX_OS;+ if (scope.checks.includes("host-tests")) {+ const why = windowsReason({+ files,+ labels: await pullRequestLabels(pr),+ hostE2e: Object.keys((await import("./testing/host-e2e.ts")).HOST_E2E),+ lines: () => changedCodeLines(`${base}...${head}`),+ });+ if (why) vitestOs = WINDOWS_OS;+ console.log(why ? `CI scope: Windows runs for ${why}`+ : `CI scope: nothing here can break Windows first, so its jobs wait for main (label the PR "${WINDOWS_LABEL}" and re-run to run them)`);+ }} catch (error) {console.warn(`CI scope: using all checks because the pull request diff is unavailable: ${error.message}`);}@@ -273,8 +370,13 @@ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.urconsole.warn(`CI scope: using main's checks because the push diff or its CI is unavailable: ${error.message}`);}}- const outputs = ciOutputs(scope, vitestOs);+ const linuxInStatic = process.env.OMB_CI_LINUX_IN_STATIC === "true";+ const outputs = linuxInStatic ? moveLinuxIntoStatic(ciOutputs(scope, vitestOs)) : ciOutputs(scope, vitestOs);console.log(`CI scope: ${scope.areas.join(", ")} -> ${outputs.jobs.join(", ") || "static checks only"}`);+ if (linuxInStatic) {+ const { vitest, evals, packaged_server: packaged } = outputs.linux_lanes;+ console.log(`CI scope: this job runs ${vitest.length} Linux vitest lane(s)${evals ? ", behavior evals" : ""}${packaged ? ", the packaged server smoke" : ""}`);+ }appendFileSync(process.env.GITHUB_OUTPUT,Object.entries(outputs).map(([key, value]) => `${key}=${typeof value === "boolean" ? value : JSON.stringify(value)}\n`).join(""),diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 0f7a7750d0..e0fa45fee1 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -8,15 +8,18 @@ import { fileURLToPath } from "node:url";import { afterEach, describe, expect, it } from "vitest";import { parse } from "yaml";import {- ALL_OS, AREA_CHECKS, ciOutputs, FULL_LANE_EVENTS, FULL_SCOPE, laneOf, MAIN_SCOPE, QUEUED_SCOPE, SELECTABLE_JOBS, selectCiScope,- selectPushScope, SRC_OUTSIDE_RENDERER, versionOnlyPackageJson, VITEST_SUBSETS, vitestMatrix,+ ALL_OS, AREA_CHECKS, ciOutputs, FULL_LANE_EVENTS, FULL_SCOPE, laneOf, LINUX_OS, MAIN_SCOPE, moveLinuxIntoStatic, QUEUED_SCOPE, SELECTABLE_JOBS,+ selectCiScope,+ selectPushScope, SRC_OUTSIDE_RENDERER, versionOnlyPackageJson, VITEST_SUBSETS, vitestMatrix, WINDOWS_LABEL, WINDOWS_OS, windowsReason,} from "./ci-scope.mjs";+import { HOST_E2E } from "./testing/host-e2e.ts";const ROOT = fileURLToPath(new URL("..", import.meta.url));const script = fileURLToPath(new URL("./ci-scope.mjs", import.meta.url));const ALL = ["macos-latest", "ubuntu-latest", "windows-latest"];const PR = ["ubuntu-latest", "windows-latest"];-const MAIN = ["ubuntu-latest"];+const LINUX = ["ubuntu-latest"];+const MAIN = ["ubuntu-latest", "windows-latest"];const SERVER_JOBS = ["vitest", "behavior-evals", "packaged-server", "electron-smokes", "foss", "ui-smoke", "browser-identity", "package-linux", "browser-driver"];const temporaryDirectories: string[] = [];afterEach(() => {@@ -65,7 +68,7 @@ function outputs(text: string) {const packaged = (oses: string[]) => oses.filter((os) => os !== "macos-latest");const everything = (oses: string[]) => ({ build: true, jobs: SELECTABLE_JOBS, vitest_os: oses, packaged_server_os: packaged(oses), vitest_matrix: vitestMatrix(oses) });const staticOnly = (oses: string[], build: boolean) => ({ build, jobs: [], vitest_os: oses, packaged_server_os: packaged(oses), vitest_matrix: vitestMatrix(oses) });-/** What a push to main and a merge group run: Linux's shards, the macOS smokes and the short Linux checks. */+/** What a push to main and a merge group run: Linux's and Windows' shards, the macOS smokes and the short Linux checks. */const MAIN_JOBS = ["vitest", "behavior-evals", "packaged-server", "electron-smokes", "foss", "control-plane", "ui-smoke", "browser-identity"];const mainLane = () => ({ build: true, jobs: MAIN_JOBS, vitest_os: MAIN, packaged_server_os: MAIN, vitest_matrix: vitestMatrix(MAIN) });@@ -198,15 +201,26 @@ describe("CI outputs", () => {expect(new Set(windows.map((entry: { os: string }) => entry.os))).toEqual(new Set(["macos-latest", "windows-latest"]));});- it("runs Linux's every shard, the macOS smokes and the short Linux checks for main, and nothing on Windows", () => {+ it("runs Linux's and Windows' every shard, the macOS smokes and the short Linux checks for main", () => {const out = ciOutputs(MAIN_SCOPE, MAIN);expect(out).toEqual(mainLane());- expect(out.vitest_matrix.include).toHaveLength(8);- expect(out.jobs).not.toEqual(expect.arrayContaining(["windows-cua"]));+ expect(out.vitest_matrix.include.map((entry: { os: string }) => entry.os)).toEqual([...Array(8).fill("ubuntu-latest"), ...Array(8).fill("windows-latest")]);+ expect(out.packaged_server_os).toEqual(MAIN);for (const job of ["windows-cua", "package-linux", "browser-driver", "cloudflared-linux-arm64"]) expect(out.jobs, job).not.toContain(job);expect(MAIN_SCOPE.checks.every((check) => FULL_SCOPE.checks.includes(check))).toBe(true);});+ it("leaves every Windows job out where the run's platforms leave Windows out", () => {+ const out = ciOutputs(FULL_SCOPE, LINUX);+ expect(out.jobs).toEqual(SELECTABLE_JOBS.filter((job) => job !== "windows-cua"));+ expect(out.vitest_matrix).toEqual(vitestMatrix(LINUX));+ expect(out.packaged_server_os).toEqual(LINUX);+ expect(out.vitest_os).toEqual(LINUX);+ expect(ciOutputs(FULL_SCOPE, WINDOWS_OS).jobs).toContain("windows-cua");+ expect(LINUX_OS).toEqual(LINUX);+ expect(WINDOWS_OS).toEqual(PR);+ });+it("runs only the broker's control-plane checks for a commit the merge queue already tested", () => {expect(ciOutputs(QUEUED_SCOPE, MAIN)).toEqual({ ...staticOnly(MAIN, false), jobs: ["control-plane"] });});@@ -221,6 +235,101 @@ describe("CI outputs", () => {});});+describe("the Linux work in the static job, on a Boat VM", () => {+ const linuxShards = vitestMatrix(LINUX).include;++ it("runs a server change's Linux shards, behavior evals and packaged server there, and no Linux job", () => {+ const out = moveLinuxIntoStatic(ciOutputs(selectCiScope(["server/index.ts"]), LINUX));+ expect(out.jobs).toEqual(SERVER_JOBS.filter((job) => !["vitest", "behavior-evals", "packaged-server"].includes(job)));+ expect(out.linux_lanes).toEqual({ vitest: linuxShards, evals: true, packaged_server: true });+ expect(out.vitest_matrix).toEqual(vitestMatrix(LINUX));+ expect(out.vitest_os).toEqual(LINUX);+ });++ it("keeps the Windows shards and packaged server as jobs", () => {+ const out = moveLinuxIntoStatic(ciOutputs(FULL_SCOPE, PR));+ expect(out.jobs).toEqual(SELECTABLE_JOBS.filter((job) => job !== "behavior-evals"));+ expect(out.vitest_matrix).toEqual(vitestMatrix(["windows-latest"]));+ expect(out.packaged_server_os).toEqual(["windows-latest"]);+ expect(out.linux_lanes).toEqual({ vitest: linuxShards, evals: true, packaged_server: true });+ expect(moveLinuxIntoStatic(ciOutputs(MAIN_SCOPE, MAIN)).jobs).toEqual(MAIN_JOBS.filter((job) => job !== "behavior-evals"));+ });++ it("runs a docs or translation change's subset there, and nothing when nothing is selected", () => {+ const docs = moveLinuxIntoStatic(ciOutputs({ checks: ["docs-tests"] }, LINUX));+ expect(docs.jobs).toEqual([]);+ expect(docs.linux_lanes).toEqual({ vitest: ciOutputs({ checks: ["docs-tests"] }, LINUX).vitest_matrix.include, evals: false, packaged_server: false });+ expect(moveLinuxIntoStatic(ciOutputs({ checks: [] }, LINUX))).toEqual({+ ...staticOnly(LINUX, false), linux_lanes: { vitest: [], evals: false, packaged_server: false },+ });+ });++ it("does it only when the static job is told it runs on Boat", () => {+ const { directory, git, base } = fixture("src/App.tsx");+ writeFileSync(join(directory, "src/App.tsx"), "changed\n");+ git("commit", "--quiet", "-am", "renderer");+ const eventPath = join(directory, "event.json");+ const outputPath = join(directory, "output.txt");+ writeFileSync(eventPath, JSON.stringify({ pull_request: { base: { sha: base }, head: { sha: git("rev-parse", "HEAD") } } }));+ const result = spawnSync(process.execPath, [script], {+ cwd: directory, encoding: "utf8", timeout: 5_000,+ env: { ...process.env, GITHUB_EVENT_NAME: "pull_request", GITHUB_EVENT_PATH: eventPath, GITHUB_OUTPUT: outputPath, OMB_CI_LINUX_IN_STATIC: "true" },+ });+ expect(result.status, result.stderr).toBe(0);+ expect(outputs(readFileSync(outputPath, "utf8"))).toEqual(moveLinuxIntoStatic(ciOutputs(selectCiScope(["src/App.tsx"]), LINUX)));+ expect(result.stdout).toContain("this job runs 8 Linux vitest lane(s)");+ });+});++describe("Windows on a pull request", () => {+ const reason = (files: string[], lines: string[] = [], labels: string[] = []) =>+ windowsReason({ files, labels, hostE2e: Object.keys(HOST_E2E), lines: () => lines });++ it("runs for the windows label whatever changed", () => {+ expect(WINDOWS_LABEL).toBe("windows");+ expect(reason(["docs/guide.md"], [], ["bug", "windows"])).toBe('the "windows" label');+ expect(reason(["server/index.ts"], [], ["Windows-ish"])).toBeNull();+ });++ it.each([+ "electron/main.mjs", "build/installer.nsh", "electron-builder.yml", "maus.ps1", "scripts/build-cua-win.mjs",+ "scripts/smoke-cua-win-embedded.mjs", "server/win32-paths.ts", "server/shell/windows.ts", "server/foo.win32.test.ts",+ ".github/workflows/package-win.yml", "package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", ".gitattributes", "vite.config.ts",+ "third_party/browser/agent-browser-windows-stdio.patch", ".github/workflows/ci.yml", "scripts/ci-scope.mjs",+ "scripts/testing/host-e2e.ts", "scripts/testing/vitest-shard-weights.json", "server/testing/host-timeout.ts",+ "scripts/prepare-cloudflared.mjs", "scripts/after-pack.mjs", ...Object.keys(HOST_E2E),+ ])("runs for %s", (file) => {+ expect(reason(["src/App.tsx", file])).toBe(file);+ });++ it.each([+ "server/index.ts", "src/components/WindowFrame.tsx", "server/darwin.ts", "server/twin.ts", "scripts/verify-sidebar.ts",+ "scripts/testing/rail-preview.tsx", "scripts/control-omb.ts", ".github/workflows/boat.yml", "tsconfig.json", "server/delta-context.e2e.test.ts",+ ])("waits for main for %s alone", (file) => {+ expect(reason([file])).toBeNull();+ });++ it.each([+ ['+ if (process.platform === "win32") return;'], ["- // Windows keeps a running process's folder"], ["+ const shell = \"powershell.exe\";"],+ ["+ join(env.USERPROFILE, x)"], ["+ spawn(cmd, args, { windowsHide: true })"], ["+ path.win32.join(a, b)"], ["+ runs-on: windows-latest"],+ ])("runs for a changed line %j", (line) => {+ expect(reason(["server/index.ts"], ["diff --git a/server/index.ts b/server/index.ts", line])).toBe(`the changed line ${JSON.stringify(line)}`);+ });++ it("reads only added and removed lines, not file headers or a window", () => {+ expect(reason(["server/index.ts"], [+ "--- a/server/Windows.ts", "+++ b/server/Windows.ts", "@@ -1 +1 @@ Windows", " Windows context", "+const frame = window.open(url);",+ "- new BrowserWindow()", "+// two windows side by side",+ ])).toBeNull();+ });++ it("reads the lines only when no label or path decided, and runs Windows when they cannot be read", () => {+ const unread = () => { throw new Error("diff too large"); };+ expect(windowsReason({ files: ["electron/main.mjs"], lines: unread })).toBe("electron/main.mjs");+ expect(windowsReason({ files: ["server/index.ts"], lines: unread })).toBe("a change whose lines could not be read (diff too large)");+ });+});+/** Relative imports, `@/` included, that load code when run; `import type` loads nothing. */const IMPORT = /(?:^|[^\w$.])(?:import|export)\s+(?!type\b)(?:[^"'`;]*?\sfrom\s*)?["']([^"']+)["']|(?:^|[^\w$.])(?:import|require)\s*\(\s*["']([^"']+)["']\s*\)/gm;const CODE = /\.[cm]?[jt]sx?$/;@@ -331,7 +440,7 @@ describe("CI scope CLI", () => {const { output, stderr } = run(directory, "pull_request", {pull_request: { base: { sha: base }, head: { sha: git("rev-parse", "HEAD") } },});- expect(output).toEqual(ciOutputs({ checks: ["docs-tests"] }, PR));+ expect(output).toEqual(ciOutputs({ checks: ["docs-tests"] }, LINUX));expect(output).toMatchObject({ build: false, jobs: ["vitest"] });expect(stderr).toBe("");});@@ -348,7 +457,7 @@ describe("CI scope CLI", () => {const { output, stderr } = run(directory, "pull_request", {pull_request: { base: { sha: base }, head: { sha: git("rev-parse", "HEAD") } },});- expect(output).toEqual(ciOutputs({ checks: ["docs-tests"] }, PR));+ expect(output).toEqual(ciOutputs({ checks: ["docs-tests"] }, LINUX));expect(output).toMatchObject({ build: false, jobs: ["vitest"] });expect(stderr).toBe("");});@@ -362,7 +471,8 @@ describe("CI scope CLI", () => {const { output, stderr } = run(directory, "pull_request", {pull_request: { base: { sha: base }, head: { sha: git("rev-parse", "HEAD") } },});- expect(output).toEqual({ build: true, jobs: SERVER_JOBS, vitest_os: PR, packaged_server_os: PR, vitest_matrix: vitestMatrix(PR) });+ // A server change that cannot break Windows first: its Windows jobs wait for main.+ expect(output).toEqual({ build: true, jobs: SERVER_JOBS, vitest_os: LINUX, packaged_server_os: LINUX, vitest_matrix: vitestMatrix(LINUX) });expect(stderr).toBe("");});@@ -374,7 +484,7 @@ describe("CI scope CLI", () => {const { output, stderr } = run(directory, "pull_request", {pull_request: { base: { sha: base }, head: { sha: git("rev-parse", "HEAD") } },});- expect(output).toEqual(ciOutputs(selectCiScope([source]), PR));+ expect(output).toEqual(ciOutputs(selectCiScope([source]), LINUX));expect(output.jobs).toEqual(jobs);expect(output.vitest_matrix.include.filter((entry: { files: string }) => !entry.files).map((entry: { os: string }) => entry.os)).toEqual(oses.flatMap((os) => Array(8).fill(os)));@@ -390,7 +500,7 @@ describe("CI scope CLI", () => {const { output } = run(directory, "pull_request", {pull_request: { base: { sha: base }, head: { sha: git("rev-parse", "HEAD") } },});- expect(output).toEqual(ciOutputs({ checks: AREA_CHECKS.web }, PR));+ expect(output).toEqual(ciOutputs({ checks: AREA_CHECKS.web }, LINUX));});it.each(["missing", "invalid", "unavailable", "empty"])("falls back loudly for a %s diff", (kind) => {@@ -604,3 +714,103 @@ describe("CI scope CLI on a push to main", () => {expect(stderr).toContain("using main's checks");});});++describe("CI scope CLI on a pull request's Windows jobs", () => {+ function serverChange(content: string, file = "server/paths.ts") {+ const { directory, git, base } = fixture(file);+ writeFileSync(join(directory, file), content);+ git("commit", "--quiet", "-am", "change");+ return { directory, payload: { pull_request: { number: 7, base: { sha: base }, head: { sha: git("rev-parse", "HEAD") } } } };+ }++ /** A GitHub that answers one pull request's labels, or fails with `status`. */+ async function fakeLabelsApi(labels: string[], status = 200) {+ const requests: string[] = [];+ const server = createServer((request, response) => {+ requests.push(`${request.method} ${request.url} ${request.headers.authorization}`);+ response.statusCode = status;+ response.setHeader("content-type", "application/json");+ response.end(JSON.stringify(status === 200 ? labels.map((name) => ({ name })) : { message: "nope" }));+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ return { env: { GITHUB_API_URL: url, GH_TOKEN: "t", GITHUB_REPOSITORY: "o/r" }, requests, close: () => new Promise((resolve) => server.close(resolve)) };+ }++ async function runPullRequest(directory: string, payload: unknown, env: Record<string, string> = {}) {+ const eventPath = join(directory, "event.json");+ const outputPath = join(directory, "output.txt");+ writeFileSync(eventPath, JSON.stringify(payload));+ const childEnv: NodeJS.ProcessEnv = { ...process.env, GITHUB_EVENT_NAME: "pull_request", GITHUB_EVENT_PATH: eventPath, GITHUB_OUTPUT: outputPath, ...env };+ if (!env.GH_TOKEN) delete childEnv.GH_TOKEN;+ const { stdout, stderr } = await new Promise<{ stdout: string; stderr: string }>((resolve, reject) => {+ execFile(process.execPath, [script], { cwd: directory, env: childEnv, encoding: "utf8", timeout: 10_000 },+ (error, out, err) => (error ? reject(new Error(`${error.message}\n${err}`)) : resolve({ stdout: out, stderr: err })));+ });+ return { output: outputs(readFileSync(outputPath, "utf8")), stdout, stderr };+ }++ const serverJobs = (oses: string[]) => ({ build: true, jobs: SERVER_JOBS, vitest_os: oses, packaged_server_os: oses, vitest_matrix: vitestMatrix(oses) });++ it("runs the Windows jobs for a changed line that names Windows, and says why", async () => {+ const { directory, payload } = serverChange('if (process.platform === "win32") quote();\n');+ const { output, stdout, stderr } = await runPullRequest(directory, payload);+ expect(output).toEqual(serverJobs(PR));+ expect(stdout).toContain('Windows runs for the changed line "+if (process.platform === \\"win32\\") quote();"');+ expect(stderr).toBe("");+ });++ it("leaves the Windows jobs to main for a change that cannot break Windows first, and says how to run them", async () => {+ const { directory, payload } = serverChange("export const greeting = \"hello\";\n");+ const { output, stdout, stderr } = await runPullRequest(directory, payload);+ expect(output).toEqual(serverJobs(LINUX));+ expect(stdout).toContain('label the PR "windows" and re-run');+ expect(stderr).toBe("");+ });++ it("runs the Windows jobs for the desktop app", async () => {+ const { directory, payload } = serverChange("app\n", "electron/main.mjs");+ expect((await runPullRequest(directory, payload)).output).toEqual(serverJobs(PR));+ });++ it("runs the Windows jobs for the label the pull request has now, so a re-run after labelling runs them", async () => {+ const { directory, payload } = serverChange("export const greeting = \"hello\";\n");+ const api = await fakeLabelsApi(["bug", "windows"]);+ try {+ const { output, stderr } = await runPullRequest(directory, payload, api.env);+ expect(output).toEqual(serverJobs(PR));+ expect(stderr).toBe("");+ expect(api.requests).toEqual(["GET /repos/o/r/issues/7/labels?per_page=100 Bearer t"]);+ } finally {+ await api.close();+ }+ });++ it("falls back to the labels in the event when GitHub cannot answer", async () => {+ const { directory, payload } = serverChange("export const greeting = \"hello\";\n");+ const api = await fakeLabelsApi([], 502);+ try {+ const labelled = { pull_request: { ...payload.pull_request, labels: [{ name: "windows" }] } };+ const { output, stderr } = await runPullRequest(directory, labelled, api.env);+ expect(output).toEqual(serverJobs(PR));+ expect(stderr).toContain("reading the pull request's labels from its event (HTTP 502");+ } finally {+ await api.close();+ }+ });++ it("asks GitHub for no labels when the change selects no Windows job", async () => {+ const { directory, git, base } = fixture("src/App.tsx");+ writeFileSync(join(directory, "src/App.tsx"), "if (navigator.platform === \"win32\") {}\n");+ git("commit", "--quiet", "-am", "renderer");+ const api = await fakeLabelsApi(["windows"]);+ try {+ const payload = { pull_request: { number: 7, base: { sha: base }, head: { sha: git("rev-parse", "HEAD") } } };+ const { output } = await runPullRequest(directory, payload, api.env);+ expect(output).toEqual(ciOutputs(selectCiScope(["src/App.tsx"]), LINUX));+ expect(api.requests).toEqual([]);+ } finally {+ await api.close();+ }+ });+});diff --git a/scripts/ci-workflow.test.ts b/scripts/ci-workflow.test.tsindex 4640a30689..3730463c32 100644--- a/scripts/ci-workflow.test.ts+++ b/scripts/ci-workflow.test.ts@@ -1,8 +1,10 @@import { spawnSync } from "node:child_process";-import { readFileSync } from "node:fs";+import { readdirSync, readFileSync } from "node:fs";import { describe, expect, it } from "vitest";import { parse } from "yaml";+import { EVALS_LANE, PACKAGED_SERVER_LANE, vitestLane } from "./ci-linux-lanes.mjs";import { SELECTABLE_JOBS, vitestMatrix } from "./ci-scope.mjs";+import { interpolate } from "./testing/github-expression.ts";const workflow = parse(readFileSync(new URL("../.github/workflows/ci.yml", import.meta.url), "utf8"));const requiredRuntimeJobs = ["vitest", "behavior-evals", "packaged-server", "windows-cua", "electron-smokes"];@@ -155,12 +157,13 @@ describe("CI concurrency", () => {expect(sparse.sort()).toEqual(["scripts/release-ci.mjs", ...imports].sort());});- it("lets push scoping read the previous commit's CI, and nothing more", () => {+ it("lets the scope read the previous commit's CI and a pull request's labels, and nothing more", () => {// ci-scope.mjs runs a push's docs- or version-only diff without the runtime- // jobs only when the commit before it has its own green run.- expect(workflow.jobs.static.permissions).toEqual({ contents: "read", actions: "read" });+ // jobs only when the commit before it has its own green run, and a PR's+ // Windows jobs when it carries the windows label.+ expect(workflow.jobs.static.permissions).toEqual({ contents: "read", actions: "read", "pull-requests": "read" });const scope = workflow.jobs.static.steps.find((step: { id?: string }) => step.id === "scope");- expect(scope.env).toEqual({ GH_TOKEN: "${{ github.token }}" });+ expect(scope.env).toEqual({ GH_TOKEN: "${{ github.token }}", OMB_CI_LINUX_IN_STATIC: "${{ runner.environment == 'self-hosted' }}" });for (const [name, job] of Object.entries(workflow.jobs) as [string, { permissions?: unknown }][]) {if (name !== "static") expect(job.permissions, name).toBeUndefined();}@@ -223,15 +226,15 @@ describe("CI concurrency", () => {vitest_matrix: "${{ steps.scope.outputs.vitest_matrix }}",packaged_server_os: "${{ steps.scope.outputs.packaged_server_os }}",});- // Only these three static steps depend on the scope's build flag; the rest always run.- const built = (workflow.jobs.static.steps as { if?: string; run?: string }[]).filter((step) => step.if !== undefined);+ // Only these three static steps depend on the scope's build flag; the rest always run, or run only on Boat.+ const built = (workflow.jobs.static.steps as { if?: string; run?: string }[]).filter((step) => step.if?.includes("outputs.build"));expect(built.map((step) => [step.if, step.run])).toEqual([["steps.scope.outputs.build == 'true'", "pnpm typecheck"],["steps.scope.outputs.build == 'true'", "pnpm check:electron"],["steps.scope.outputs.build == 'true'", "pnpm exec vite build"],]);expect(workflow.jobs.static.steps.some((step: { run?: string }) =>- step.run === "pnpm exec vitest run scripts/ci-scope.test.ts scripts/ci-workflow.test.ts scripts/testing/verification-docs.test.ts",+ step.run === "pnpm exec vitest run scripts/ci-scope.test.ts scripts/ci-linux-lanes.test.ts scripts/ci-workflow.test.ts scripts/testing/verification-docs.test.ts",)).toBe(true);for (const [name, job] of Object.entries(workflow.jobs) as [string, { needs?: string | string[]; if?: string }][]) {if (["static", "gate"].includes(name)) continue;@@ -280,3 +283,92 @@ describe("CI concurrency", () => {expect(commands).toContain("pnpm exec vitest run server/shared-computers.e2e.test.ts");});});++type Step = { id?: string; name?: string; if?: string; run?: string; uses?: string; shell?: string; env?: Record<string, string> };++/** The contexts a run's static job is routed by: a pull request from `author`, a push, a merge group or a scheduled run. */+function runContext({ boat = "on", event = "pull_request", actor = "milind-soni", triggering = actor, author = actor, head = "milind-soni/OpenMausBot" }: {+ boat?: string | null; event?: string; actor?: string; triggering?: string; author?: string; head?: string | null;+} = {}) {+ return {+ vars: boat === null ? {} : { BOAT_CI: boat },+ github: {+ event_name: event, actor, triggering_actor: triggering, repository: "milind-soni/OpenMausBot", repository_owner: "milind-soni",+ event: event === "pull_request" ? { pull_request: { user: { login: author }, head: { repo: head === null ? null : { full_name: head } } } } : {},+ },+ };+}++describe("CI on Boat", () => {+ const routed = (context: ReturnType<typeof runContext>) => ({+ runsOn: interpolate(workflow.jobs.static["runs-on"], context),+ name: interpolate(workflow.jobs.static.name, context),+ timeout: interpolate(String(workflow.jobs.static["timeout-minutes"]), context),+ });+ const boat = { runsOn: "boat-xlarge", name: "typecheck + lint + Linux tests (Boat)", timeout: 45 };+ const github = (timeout: number) => ({ runsOn: "ubuntu-latest", name: "typecheck + lint", timeout });++ it.each([+ ["the owner's pull request", {}],+ ["the owner's push to main", { event: "push" }],+ ["a merge group the owner queued", { event: "merge_group" }],+ ])("runs the static job, with the Linux work, on one Boat VM for %s", (_, run) => {+ expect(routed(runContext(run))).toEqual(boat);+ });++ it.each([+ ["while BOAT_CI is not set", { boat: null }, 15],+ ["while BOAT_CI is off", { boat: "off" }, 15],+ ["for a fork's pull request", { head: "someone/OpenMausBot", author: "someone", actor: "someone" }, 45],+ ["for a fork's pull request the owner started", { head: "someone/OpenMausBot", author: "someone" }, 45],+ ["for a deleted fork's pull request", { head: null }, 45],+ ["for a teammate's pull request on this repository", { author: "teammate", actor: "teammate" }, 45],+ ["for the owner's pull request that a teammate pushed to", { actor: "teammate" }, 45],+ ["for the owner's pull request that a teammate re-ran", { triggering: "teammate" }, 45],+ ["for a push a bot made", { event: "push", actor: "github-actions[bot]" }, 45],+ ["for the nightly run", { event: "schedule" }, 45],+ ["for a manual run, the release lane among them", { event: "workflow_dispatch" }, 45],+ ])("keeps every job on GitHub's runners %s", (_, run, timeout) => {+ expect(routed(runContext(run))).toEqual(github(timeout));+ });++ it("does the Linux work in the static job only where ci-scope moved it there, without Boat's extra rights or desktop", () => {+ const steps = workflow.jobs.static.steps as Step[];+ const boatOnly = steps.slice(steps.findIndex((step) => step.name === "production UI build") + 1);+ expect(boatOnly.map((step) => step.if)).toEqual([+ "steps.scope.outputs.linux_lanes", "steps.scope.outputs.linux_lanes", "steps.scope.outputs.linux_lanes",+ "${{ !cancelled() && steps.scope.outputs.linux_lanes }}", "failure() && steps.scope.outputs.linux_lanes",+ ]);+ const lanes = boatOnly.find((step) => step.run === "node scripts/ci-linux-lanes.mjs")!;+ expect(lanes.env).toMatchObject({ OMB_CI_LINUX_LANES: "${{ steps.scope.outputs.linux_lanes }}", LANG: "C.UTF-8", LC_ALL: "C.UTF-8", TZ: "UTC" });+ expect(lanes.shell).toBe("setpriv --inh-caps=-all --ambient-caps=-all -- env -u DISPLAY -u XAUTHORITY bash --noprofile --norc -eo pipefail {0}");+ expect(boatOnly.find((step) => step.run?.startsWith("sudo rm -f "))!.run).toContain("/usr/bin/bwrap");+ // The same report and artifact as the vitest and behavior-evals jobs.+ const report = (workflow.jobs.vitest.steps as Step[]).find((step) => step.run === "node scripts/testing/ci-retry-summary.mjs")!;+ expect(boatOnly.find((step) => step.run === "node scripts/testing/ci-retry-summary.mjs")!.env).toEqual(report.env);+ const upload = (workflow.jobs["behavior-evals"].steps as Step[]).find((step) => step.uses?.startsWith("actions/upload-artifact@"))!;+ expect(boatOnly.at(-1)).toEqual({ ...upload, if: "failure() && steps.scope.outputs.linux_lanes" });+ });++ it("runs on Boat exactly the commands the Linux jobs run on GitHub's runners", () => {+ const steps = (job: string) => workflow.jobs[job].steps as Step[];+ const work = (job: string) => steps(job).filter((step) => step.run && step.run !== "pnpm install --frozen-lockfile").map((step) => step.run);+ for (const entry of vitestMatrix(["ubuntu-latest"]).include.slice(0, 2)) {+ const context = { matrix: entry, runner: { temp: "/t" } };+ const tests = steps("vitest").find((step) => step.name === "Run tests")!;+ const units = steps("vitest").find((step) => step.name === "Broker and Electron unit tests")!;+ const lane = vitestLane(entry, "/t/vitest-retries.jsonl");+ expect(lane.commands).toEqual([interpolate(tests.run!, context), ...(entry.node_tests ? [units.run] : [])]);+ expect(lane.env).toEqual(Object.fromEntries(Object.entries(tests.env!).map(([key, value]) => [key, interpolate(value, context)])));+ }+ expect(EVALS_LANE.commands).toEqual(work("behavior-evals"));+ expect(PACKAGED_SERVER_LANE.commands).toEqual(work("packaged-server"));+ });++ it("starts Boat VMs from no other workflow", () => {+ const directory = new URL("../.github/workflows/", import.meta.url);+ const onBoat = readdirSync(directory).filter((file) => /\.ya?ml$/.test(file))+ .filter((file) => /runs-on:[^\n]*boat|'boat(?:-\w+)?'/.test(readFileSync(new URL(file, directory), "utf8")));+ expect(onBoat).toEqual(["ci.yml"]);+ });+});diff --git a/scripts/release-ci.mjs b/scripts/release-ci.mjsindex be4e620c00..d3509c65b7 100644--- a/scripts/release-ci.mjs+++ b/scripts/release-ci.mjs@@ -2,7 +2,7 @@// platform's vitest shards run, on the commit itself, on a commit with the same// tree, or (for a version-only bump) on its parent.//-// A push to main or a merge group runs Linux's shards only, so the release+// A push to main or a merge group runs no macOS shards, so the release// commit's own run proves nothing; CI then starts on a `release-ci/v<version>`// branch no merge on main can touch, as a manual run of every platform. A main// run is never re-run in place: the re-run would join main's group and cancel@@ -28,7 +28,7 @@ const neverStarted = (job) => !(job.steps ?? []).some((step) => step.conclusion* What one finished CI run proves.* - "green": the gate passed and every platform's every vitest shard ran and passed.* - "partial": the gate passed and every vitest job that ran passed, but not every platform's shards ran (a push to- * main or a merge group runs Linux's only).+ * main or a merge group runs no macOS shards).* - "scoped": the gate passed but vitest did not run (docs- or version-only).* - "runner-lost": the gate failed, and every other failed job never started.* - "red": the gate failed for any other reason.diff --git a/scripts/testing/github-expression.ts b/scripts/testing/github-expression.tsnew file mode 100644index 0000000000..9d0e7661fa--- /dev/null+++ b/scripts/testing/github-expression.ts@@ -0,0 +1,94 @@+// GitHub Actions' expression language, the part ci.yml uses: literals, property paths, ! == != && || and+// parentheses, contains(), fromJSON() and format(). As GitHub evaluates them: && and || return an operand, string+// comparison ignores case, and a missing property is null.+type Value = string | number | boolean | null | Value[] | { [key: string]: Value };++const TOKEN = /\s*(?:('(?:[^']|'')*')|(\d+(?:\.\d+)?)|(==|!=|&&|\|\||[!().,[\]])|([A-Za-z_][\w-]*))/y;++function tokenize(source: string): string[] {+ const tokens: string[] = [];+ TOKEN.lastIndex = 0;+ while (TOKEN.lastIndex < source.length) {+ if (/^\s*$/.test(source.slice(TOKEN.lastIndex))) break;+ const match = TOKEN.exec(source);+ if (!match) throw new Error(`cannot read the expression at ${JSON.stringify(source.slice(TOKEN.lastIndex))}`);+ tokens.push(match[0].trim());+ }+ return tokens;+}++const truthy = (value: Value): boolean => !(value === null || value === false || value === 0 || value === "");+const equal = (a: Value, b: Value): boolean => typeof a === "string" && typeof b === "string" ? a.toLowerCase() === b.toLowerCase() : a === b;+const text = (value: Value): string => (value === null ? "" : typeof value === "object" ? JSON.stringify(value) : String(value));++const FUNCTIONS: Record<string, (...args: Value[]) => Value> = {+ contains: (search, item) => Array.isArray(search) ? search.some((entry) => equal(entry, item))+ : text(search).toLowerCase().includes(text(item).toLowerCase()),+ fromJSON: (json) => JSON.parse(text(json)) as Value,+ format: (template, ...args) => text(template).replace(/\{(\d+)\}/g, (_, index: string) => text(args[Number(index)] ?? null)),+};++/** The value of one expression (without its `${{ }}`) in `context`. */+export function evaluate(expression: string, context: Record<string, Value>): Value {+ const tokens = tokenize(expression);+ let at = 0;+ const peek = () => tokens[at];+ const take = (expected?: string) => {+ const token = tokens[at++];+ if (expected !== undefined && token !== expected) throw new Error(`expected ${expected}, read ${token}`);+ return token;+ };+ const or = (): Value => {+ let left = and();+ while (peek() === "||") { take(); const right = and(); left = truthy(left) ? left : right; }+ return left;+ };+ const and = (): Value => {+ let left = comparison();+ while (peek() === "&&") { take(); const right = comparison(); left = truthy(left) ? right : left; }+ return left;+ };+ const comparison = (): Value => {+ let left = unary();+ while (peek() === "==" || peek() === "!=") { const op = take(); const right = unary(); left = op === "==" ? equal(left, right) : !equal(left, right); }+ return left;+ };+ const unary = (): Value => {+ if (peek() !== "!") return primary();+ take();+ return !truthy(unary());+ };+ const primary = (): Value => {+ const token = take();+ if (token === "(") { const value = or(); take(")"); return value; }+ if (token.startsWith("'")) return token.slice(1, -1).replace(/''/g, "'");+ if (/^\d/.test(token)) return Number(token);+ if (token === "true" || token === "false") return token === "true";+ if (token === "null") return null;+ if (peek() === "(") {+ take("(");+ const args: Value[] = [];+ while (peek() !== ")") { args.push(or()); if (peek() === ",") take(","); }+ take(")");+ const fn = FUNCTIONS[token];+ if (!fn) throw new Error(`no function ${token}`);+ return fn(...args);+ }+ let value: Value = context[token] ?? null;+ while (peek() === "." || peek() === "[") {+ const key = take() === "." ? take() : (() => { const index = or(); take("]"); return text(index); })();+ value = value !== null && typeof value === "object" ? (value as Record<string, Value>)[key] ?? null : null;+ }+ return value;+ };+ const value = or();+ if (at !== tokens.length) throw new Error(`unread tokens from ${tokens[at]}`);+ return value;+}++/** A workflow value with `${{ }}` in it, as GitHub fills it in: one whole expression keeps its type. */+export function interpolate(source: string, context: Record<string, Value>): Value {+ const whole = /^\s*\$\{\{([\s\S]*)\}\}\s*$/.exec(source);+ if (whole && !whole[1].includes("}}")) return evaluate(whole[1], context);+ return source.replace(/\$\{\{([\s\S]*?)\}\}/g, (_, inner: string) => text(evaluate(inner, context)));+}