Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

tell a cancelled CI run apart from a failed one, and retry it once (#7437)

[._.]/ Adam Eivye3d872106c9f
diff --git a/.github/workflows/ci-cancel-recovery.yml b/.github/workflows/ci-cancel-recovery.yml
new file mode 100644
index 0000000000..a09869cef8
--- /dev/null
+++ b/.github/workflows/ci-cancel-recovery.yml
@@ -0,0 +1,66 @@
+# Recovery for a CI run that was cancelled with no successor run (#7437).
+#
+# When several pull requests build at once, GitHub cancels in-flight runs that
+# nothing here asked it to cancel — no job failed, the in-workflow fail-fast
+# step never ran, and no newer run exists for the branch. The same SHA then
+# passes on the next attempt once the queue drains, so the fix is one automatic
+# re-dispatch rather than a human noticing and clicking "Re-run".
+#
+# SECURITY: `workflow_run` runs this workflow's DEFAULT-BRANCH copy with a
+# writable token, which is why it never checks out, builds, or executes the
+# pull request's head. The only PR-derived values it touches are the run
+# metadata passed as environment variables below, and the script uses them as
+# validated numbers and one encoded query parameter — never as a path, an
+# argument, or shell input.
+name: CI cancel recovery
+
+on:
+ workflow_run:
+ workflows: [CI]
+ types: [completed]
+
+permissions:
+ contents: read
+ actions: write
+
+# One recovery evaluation per run. Never `cancel-in-progress`: cancelling the
+# thing that recovers from cancellations is how this whole class of bug starts.
+concurrency:
+ group: ci-cancel-recovery-${{ github.event.workflow_run.id }}
+ cancel-in-progress: false
+
+jobs:
+ retry:
+ name: Re-dispatch a CI run cancelled with no successor
+ # The cheap guards run here so the common case (a run that concluded
+ # normally) costs no runner at all. The script re-checks all three, because
+ # it is also the unit under test and must not rely on the caller.
+ if: >-
+ github.event.workflow_run.conclusion == 'cancelled'
+ && github.event.workflow_run.event == 'pull_request'
+ && github.event.workflow_run.run_attempt == 1
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ persist-credentials: false
+
+ - name: Use Node.js 24.x
+ uses: actions/setup-node@v7
+ with:
+ node-version: 24.x
+
+ # No `npm ci`: the script imports Node builtins only, enforced by
+ # scripts/pre-install-entrypoints.test.js.
+ - name: Re-dispatch the cancelled run
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ CI_RUN_ID: ${{ github.event.workflow_run.id }}
+ CI_RUN_ATTEMPT: ${{ github.event.workflow_run.run_attempt }}
+ CI_RUN_NUMBER: ${{ github.event.workflow_run.run_number }}
+ CI_WORKFLOW_ID: ${{ github.event.workflow_run.workflow_id }}
+ CI_RUN_EVENT: ${{ github.event.workflow_run.event }}
+ CI_RUN_CONCLUSION: ${{ github.event.workflow_run.conclusion }}
+ CI_RUN_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
+ CI_RUN_HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
+ run: node scripts/ci-retry-cancelled-run.js
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index fa90acd0d2..c30e0304ad 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -683,30 +683,26 @@ jobs:
needs: [impact, server, client, database, windows-server]
runs-on: ubuntu-latest
steps:
+ # The gate needs the repo only for scripts/ci-gate-report.js, which
+ # imports Node builtins only — no dependency install, no setup-node.
+ - uses: actions/checkout@v7
+ with:
+ fetch-depth: 1
+ persist-credentials: false
+
+ # A CANCELLED run and a FAILED one are different events with different
+ # responses, and collapsing them sent readers hunting for a test failure
+ # that did not exist (#7437). Each CI_GATE_RESULT_<JOB> variable names one
+ # job; adding a job to the gate is one line here and no code change.
- name: Require every selected job to pass
env:
- IMPACT_RESULT: ${{ needs.impact.result }}
- SERVER_RESULT: ${{ needs.server.result }}
- CLIENT_RESULT: ${{ needs.client.result }}
- DATABASE_RESULT: ${{ needs.database.result }}
- WINDOWS_SERVER_RESULT: ${{ needs.windows-server.result }}
- run: |
- node -e '
- const results = {
- impact: process.env.IMPACT_RESULT,
- server: process.env.SERVER_RESULT,
- client: process.env.CLIENT_RESULT,
- database: process.env.DATABASE_RESULT,
- windows_server: process.env.WINDOWS_SERVER_RESULT,
- };
- const failed = Object.entries(results)
- .filter(([, result]) => !["success", "skipped"].includes(result));
- if (failed.length) {
- console.error("Selected CI jobs did not pass:", failed);
- process.exit(1);
- }
- console.log("CI gate passed:", results);
- '
+ CI_GATE_LABEL: CI Gate
+ CI_GATE_RESULT_IMPACT: ${{ needs.impact.result }}
+ CI_GATE_RESULT_SERVER: ${{ needs.server.result }}
+ CI_GATE_RESULT_CLIENT: ${{ needs.client.result }}
+ CI_GATE_RESULT_DATABASE: ${{ needs.database.result }}
+ CI_GATE_RESULT_WINDOWS_SERVER: ${{ needs.windows-server.result }}
+ run: node scripts/ci-gate-report.js
full-gate:
# A second check run published ONLY when the impact plan chose the complete
@@ -730,12 +726,15 @@ jobs:
needs: [impact, gate]
runs-on: ubuntu-latest
steps:
+ - uses: actions/checkout@v7
+ with:
+ fetch-depth: 1
+ persist-credentials: false
+
+ # Same reporter, one input: a cancelled aggregate gate must not read as a
+ # red complete suite on the release path either.
- name: Require the aggregate gate to have passed
env:
- GATE_RESULT: ${{ needs.gate.result }}
- run: |
- if [ "$GATE_RESULT" != "success" ]; then
- echo "The complete suite ran but CI Gate did not pass ($GATE_RESULT)."
- exit 1
- fi
- echo "Complete suite passed — this tree does not need re-testing on release."
+ CI_GATE_LABEL: Full CI Gate
+ CI_GATE_RESULT_GATE: ${{ needs.gate.result }}
+ run: node scripts/ci-gate-report.js
diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.md
index 55e7f603e6..7dca7c066b 100644
--- a/docs/GITHUB_ACTIONS.md
+++ b/docs/GITHUB_ACTIONS.md
@@ -330,8 +330,11 @@ own.
### Shallow checkouts
-No job clones full history. `actions/checkout` runs at `fetch-depth: 2`,
-which on a pull request is the merge ref plus both of its parents — and the
+No job clones full history. `actions/checkout` runs at `fetch-depth: 2`
+in every job that diffs against the base — the two gate jobs use `fetch-depth:
+1`, because they check out only to run `scripts/ci-gate-report.js` and never
+look at history. Depth 2 on a pull request is the merge ref plus both of its
+parents — and the
first parent *is* the base-branch commit the pull request is diffed against.
`scripts/ci-base-sha.js` reads it (`HEAD^1`) and exports `CI_BASE_SHA` for the
rest of the job, so the planner's `git diff <base>...HEAD` resolves without
@@ -379,7 +382,10 @@ The selected work is split across parallel jobs:
Linux. A full plan does not automatically mean a full *Windows* run — see
"What a full plan costs the Windows job" below.
- **CI Gate** — always reports one stable required-check result and fails if any
- selected job failed or was cancelled.
+ selected job failed or was cancelled. Both block, but the message distinguishes
+ them: `scripts/ci-gate-report.js` says *cancelled, not failed* and names the
+ cancelled jobs when nothing actually failed. See "External cancellation and
+ one automatic retry" below.
- **Full CI Gate** — published only when the plan chose the complete suite, and
mirrors `CI Gate`'s result. This is the check the release workflow looks for;
see "Reusing the release PR's CI run" below.
@@ -585,7 +591,8 @@ ones:
`cancelled` does not satisfy it, and a gate that never publishes leaves the
required context unreported, which also blocks.
- If the gate job does run, it accepts only `success` or `skipped` per job, so
- the failed leaf (or its own `cancelled` result) fails the gate.
+ the failed leaf (or its own `cancelled` result) fails the gate. It reports a
+ cancel and a failure differently — see the next section — but neither passes.
- `scripts/verify-ci-status.js` accepts a `Full CI Gate` only at
`conclusion === 'success'`, so a canceled run can never let a release skip
the full suite.
@@ -602,6 +609,39 @@ other canceling an older run when a newer commit arrives. Scheduled, manually
dispatched, and release-called runs skip this sibling cancellation so their
aggregate diagnostics and cache post-steps can complete normally.
+### External cancellation and one automatic retry
+
+Not every cancel comes from this repository. When several PRs build at once,
+GitHub itself cancels in-flight runs — no job fails, the fail-fast step above
+stays `skipped`, and **no successor run exists for the branch** (issue 7437).
+That last property is the whole diagnosis: a `cancel-in-progress` supersession
+always leaves a newer run for the same PR, and an external cancel leaves none.
+
+`.github/workflows/ci-cancel-recovery.yml` runs on `workflow_run` and
+re-dispatches such a run exactly once. `scripts/ci-retry-cancelled-run.js`
+retries only when every one of these holds:
+
+| Guard | Why |
+| --- | --- |
+| conclusion is `cancelled` | A failure is a failure. |
+| event is `pull_request` | Nightly, dispatch, and release-called runs are not ours to re-drive. |
+| `run_attempt == 1` | The retry budget. `POST /rerun` makes attempt 2, whose cancel sees attempt 2 and stops — one retry per run, and a PR run is one run per head SHA. |
+| no job concluded `failure`/`timed_out` | Fail-fast cancellation makes a genuinely red run *look* cancelled. Retrying it would re-run the suite on a broken tree. |
+| no newer run for the branch | That is a supersession; the newer run already covers this code. |
+
+Any API lookup that cannot be completed skips the retry rather than assuming a
+guard passed — a missed retry costs one manual re-run, a wrong one loops.
+
+Because the trigger is `workflow_run`, the recovery workflow runs the
+**default branch's** copy of itself with a writable `actions` token and never
+checks out, installs, or executes the pull request's head. The only PR-derived
+values it touches are validated run ids and one URL-encoded branch name.
+
+Reader-facing symptoms, the `gh` commands that tell an external cancel from a
+supersession, and the account-billing check that confirms the upstream cause
+are in [TROUBLESHOOTING.md](TROUBLESHOOTING.md) under "CI cancelled with no
+successor run".
+
### Impact-planner safety rules
- A directory feature such as `server/services/sprites/` selects tests carrying
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 298cec2867..5c0d9ad5aa 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -436,6 +436,67 @@ npm test -- lib/taskParser.test.js
npm run test:watch
```
+### CI cancelled with no successor run
+
+**Symptom**: A pull request's `CI Gate` / `Full CI Gate` goes red while several
+PRs are building at once. Opening the run shows no failing assertion — jobs
+report `##[error]The operation was canceled.` mid-step, often inside
+`actions/checkout`, and the in-workflow `Cancel sibling CI jobs after failure`
+step is `skipped` in every job. Re-running is usually cancelled the same way
+until the queue empties; the identical SHA then passes on an idle queue.
+
+**What it is not**: this is *not* `cancel-in-progress` doing its job. The
+concurrency group is per-PR (`.github/workflows/ci.yml`), and a legitimate
+supersession always leaves a **newer run** for the same PR. An external cancel
+leaves none. The leading cause is GitHub-side account enforcement — a
+concurrent-job limit or an Actions spending limit — cancelling in-flight runs
+once several PRs fan out and the Windows shards make each run expensive.
+
+**Tell the two apart** — list the runs for the branch and look for a successor:
+
+```bash
+# Every run for one PR branch, newest first. A supersession has a run NEWER
+# than the cancelled one; an external cancel does not.
+gh run list --branch "<head-branch>" --workflow CI \
+ --json databaseId,headSha,status,conclusion,createdAt,attempt
+
+# Did any job actually fail, or were they all cancelled?
+gh run view <run-id> --json jobs \
+ --jq '.jobs[] | {name, conclusion, startedAt, completedAt}'
+```
+
+All jobs `cancelled` or `success`, none `failure`, and no newer run for the
+branch → external cancel. One job `failure` → a real red run that
+`scripts/cancel-current-ci-run.js` then stopped on purpose.
+
+**Account-level confirmation** (needs a scope the unattended agent cannot
+grant itself — run it yourself):
+
+```bash
+gh auth refresh -s user
+gh api /users/<your-login>/settings/billing/actions
+```
+
+**What PortOS already does about it**:
+
+- The gate reports the difference. `scripts/ci-gate-report.js` prints
+ `this run was CANCELLED, not failed`, names the cancelled jobs, and points
+ back here — instead of the old undifferentiated "did not pass".
+- One automatic retry. `.github/workflows/ci-cancel-recovery.yml` watches for a
+ completed CI run and re-dispatches it exactly once when it was cancelled on a
+ pull request, **no job failed**, and **no newer run exists for the branch**.
+ The budget is the run attempt: `POST /rerun` produces attempt 2, and attempt
+ 2 is never retried. A supersession and a self-cancel after a real failure are
+ both skipped.
+
+If a PR is still stuck after that one retry, the queue was busy for longer than
+one attempt — re-run it by hand once the other runs have drained.
+
+One deliberate rough edge: a run **you** cancel by hand looks identical to an
+external cancel from the API, so it gets the same single retry. Push a new
+commit (or close the PR) rather than cancelling if you want the run to stay
+stopped.
+
## Known Issues
### GPU watchdog kernel panic during LoRA training
diff --git a/scripts/ci-gate-report.js b/scripts/ci-gate-report.js
new file mode 100644
index 0000000000..6843867c91
--- /dev/null
+++ b/scripts/ci-gate-report.js
@@ -0,0 +1,152 @@
+#!/usr/bin/env node
+
+/**
+ * The CI gate's verdict, with CANCELLED told apart from FAILED.
+ *
+ * The gate used to collapse every non-`success`/`skipped` needs-result into
+ * one "did not pass" line, so a run that GitHub cancelled out from under us
+ * read exactly like a red test suite (#7437). That sends the next reader
+ * hunting for a failing assertion that does not exist, and it hides the one
+ * fact that decides what to do next: whether anything actually failed.
+ *
+ * Three verdicts, not two:
+ * - pass — every selected job was `success` or `skipped`.
+ * - cancelled — at least one job was `cancelled` and NOTHING failed. The
+ * run was stopped externally (or superseded); there is no
+ * test failure to chase. Still non-zero: a cancelled run
+ * proves nothing and must not be merged.
+ * - failure — at least one job genuinely failed. Cancelled siblings are
+ * reported as collateral, because `Cancel sibling CI jobs
+ * after failure` cancels them on purpose.
+ *
+ * Reads `CI_GATE_RESULT_<JOB>` out of the environment rather than taking
+ * arguments, so adding a job to the gate is one workflow line and no code
+ * change. Builtins only — the gate job checks out the repo but never installs
+ * dependencies (scripts/pre-install-entrypoints.test.js enforces it).
+ */
+
+import { isDirectlyInvoked } from './lib/directInvocation.js';
+import { writeStepSummary } from './lib/githubOutput.js';
+
+const RESULT_ENV_PREFIX = 'CI_GATE_RESULT_';
+/** GitHub's `needs.<job>.result` values that do not block the gate. */
+const PASSING_RESULTS = new Set(['success', 'skipped']);
+const TROUBLESHOOTING_ANCHOR = '"CI cancelled with no successor run" in docs/TROUBLESHOOTING.md';
+
+/**
+ * Read the `CI_GATE_RESULT_<JOB>` variables into `{ jobId: result }`.
+ *
+ * `CI_GATE_RESULT_WINDOWS_SERVER` names the `windows-server` job: GitHub
+ * expression syntax cannot produce a hyphen in an env key, so the workflow
+ * spells it with an underscore and the job id is restored here.
+ *
+ * @param {NodeJS.ProcessEnv} [env]
+ * @returns {Array<{job: string, result: string}>} declaration order preserved
+ */
+export function collectGateResults(env = process.env) {
+ return Object.entries(env)
+ .filter(([key]) => key.startsWith(RESULT_ENV_PREFIX) && key.length > RESULT_ENV_PREFIX.length)
+ .map(([key, value]) => ({
+ job: key.slice(RESULT_ENV_PREFIX.length).toLowerCase().replace(/_/g, '-'),
+ // An unset `needs.<job>.result` arrives as the empty string. Naming it
+ // keeps it out of the "passed" bucket instead of silently vanishing.
+ result: typeof value === 'string' && value.trim() ? value.trim() : 'unknown',
+ }));
+}
+
+/**
+ * Classify gate results into a verdict plus the lines to print.
+ *
+ * @param {Array<{job: string, result: string}>} results
+ * @param {string} [label] - The gate's display name, for the message.
+ * @returns {{verdict: 'pass'|'cancelled'|'failure', lines: string[],
+ * cancelled: string[], failed: string[]}}
+ */
+export function summarizeGateResults(results, label = 'CI Gate') {
+ const passed = results.filter(({ result }) => PASSING_RESULTS.has(result));
+ const cancelled = results.filter(({ result }) => result === 'cancelled').map(({ job }) => job);
+ // Anything neither passing nor cancelled is a failure — `failure`, and also
+ // the `unknown` above. Defaulting an unrecognised result to "failed" is the
+ // safe direction: it blocks with a loud message instead of being waved
+ // through as collateral of a cancel.
+ const failed = results
+ .filter(({ result }) => !PASSING_RESULTS.has(result) && result !== 'cancelled')
+ .map(({ job, result }) => `${job}=${result}`);
+
+ const finished = passed.length
+ ? `Jobs that finished: ${passed.map(({ job, result }) => `${job}=${result}`).join(', ')}`
+ : 'No job reached a conclusion.';
+
+ if (failed.length) {
+ return {
+ verdict: 'failure',
+ cancelled,
+ failed,
+ lines: [
+ `❌ ${label}: selected CI jobs did not pass.`,
+ `Failed jobs: ${failed.join(', ')}`,
+ ...(cancelled.length
+ ? [`Cancelled alongside the failure (expected — the fail-fast step stops siblings): ${cancelled.join(', ')}`]
+ : []),
+ finished,
+ ],
+ };
+ }
+
+ if (cancelled.length) {
+ return {
+ verdict: 'cancelled',
+ cancelled,
+ failed,
+ lines: [
+ `🚫 ${label}: this run was CANCELLED, not failed — no job reported a failure.`,
+ `Cancelled jobs: ${cancelled.join(', ')}`,
+ finished,
+ 'Do not go looking for a broken test. Either a newer push superseded this run'
+ + ' (cancel-in-progress), or GitHub cancelled it externally while several runs'
+ + ' were in flight.',
+ `Telling those apart, and what to do about each: ${TROUBLESHOOTING_ANCHOR}`,
+ ],
+ };
+ }
+
+ return {
+ verdict: 'pass',
+ cancelled,
+ failed,
+ lines: [`✅ ${label} passed: ${results.map(({ job, result }) => `${job}=${result}`).join(', ') || 'no jobs selected'}`],
+ };
+}
+
+/**
+ * Print the verdict and report whether the gate passed.
+ *
+ * @param {object} [options]
+ * @param {NodeJS.ProcessEnv} [options.env]
+ * @param {{log?: Function, error?: Function}} [options.logger]
+ * @param {Function} [options.writeSummary] - injectable step-summary writer
+ * @returns {{verdict: string, ok: boolean, lines: string[]}}
+ */
+export function reportGate({
+ env = process.env,
+ logger = console,
+ writeSummary = writeStepSummary,
+} = {}) {
+ const label = typeof env.CI_GATE_LABEL === 'string' && env.CI_GATE_LABEL.trim()
+ ? env.CI_GATE_LABEL.trim()
+ : 'CI Gate';
+ const summary = summarizeGateResults(collectGateResults(env), label);
+ const write = summary.verdict === 'pass' ? logger.log : logger.error;
+ for (const line of summary.lines) write?.call(logger, line);
+ // Also on the run's summary page: the verdict has to be readable without
+ // expanding a step's log, which is exactly what nobody does before
+ // concluding "CI is red". Every value here is a job id or a GitHub result
+ // string, never event payload text.
+ writeSummary(`### ${summary.verdict === 'pass' ? '✅' : '🚫'} ${label}\n\n`
+ + summary.lines.map((line) => `- ${line}`).join('\n'), env);
+ return { verdict: summary.verdict, ok: summary.verdict === 'pass', lines: summary.lines };
+}
+
+if (isDirectlyInvoked(import.meta.url)) {
+ if (!reportGate().ok) process.exitCode = 1;
+}
diff --git a/scripts/ci-gate-report.test.js b/scripts/ci-gate-report.test.js
new file mode 100644
index 0000000000..b8991d2594
--- /dev/null
+++ b/scripts/ci-gate-report.test.js
@@ -0,0 +1,162 @@
+/**
+ * The gate's job is to say WHY the run is not mergeable. Before #7437 it said
+ * "did not pass" for a cancel and for a red suite alike, so these tests are
+ * about the distinction, not about the exit code: both still block.
+ */
+import { readFileSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+import { describe, expect, it } from 'vitest';
+
+import { collectGateResults, reportGate, summarizeGateResults } from './ci-gate-report.js';
+import { workflowJobs } from './lib/workflowJobs.js';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+const WORKFLOW = readFileSync(join(REPO_ROOT, '.github/workflows/ci.yml'), 'utf8');
+
+const results = (pairs) => Object.entries(pairs).map(([job, result]) => ({ job, result }));
+
+describe('collectGateResults', () => {
+ it('reads only the prefixed variables and restores hyphenated job ids', () => {
+ expect(collectGateResults({
+ CI_GATE_RESULT_SERVER: 'success',
+ CI_GATE_RESULT_WINDOWS_SERVER: 'cancelled',
+ CI_GATE_LABEL: 'CI Gate',
+ PATH: '/usr/bin',
+ })).toEqual([
+ { job: 'server', result: 'success' },
+ { job: 'windows-server', result: 'cancelled' },
+ ]);
+ });
+
+ it('names an unset result rather than dropping the job', () => {
+ // `needs.<job>.result` arrives empty when a job never reported. Dropping it
+ // would let the gate pass on a silently missing job.
+ expect(collectGateResults({ CI_GATE_RESULT_DATABASE: ' ' }))
+ .toEqual([{ job: 'database', result: 'unknown' }]);
+ });
+});
+
+describe('summarizeGateResults', () => {
+ it('passes when every job succeeded or was skipped', () => {
+ const summary = summarizeGateResults(results({ server: 'success', database: 'skipped' }));
+ expect(summary.verdict).toBe('pass');
+ expect(summary.lines.join('\n')).toContain('server=success');
+ });
+
+ it('reports a cancel with no failure as CANCELLED and names the cancelled jobs', () => {
+ const summary = summarizeGateResults(results({
+ impact: 'success',
+ server: 'cancelled',
+ client: 'cancelled',
+ database: 'success',
+ 'windows-server': 'cancelled',
+ }));
+
+ expect(summary.verdict).toBe('cancelled');
+ expect(summary.cancelled).toEqual(['server', 'client', 'windows-server']);
+ const text = summary.lines.join('\n');
+ expect(text).toContain('CANCELLED, not failed');
+ expect(text).toContain('no job reported a failure');
+ expect(text).toContain('Cancelled jobs: server, client, windows-server');
+ // The reader needs somewhere to go next, and the doc is the only place the
+ // external-vs-supersession distinction is written down.
+ expect(text).toContain('docs/TROUBLESHOOTING.md');
+ });
+
+ it('reports a real failure as a failure even when cancelled siblings outnumber it', () => {
+ // The repo cancels its own siblings from a failing job, so this shape is
+ // the NORMAL red run — calling it "cancelled" would be the worse mistake.
+ const summary = summarizeGateResults(results({
+ server: 'failure',
+ client: 'cancelled',
+ 'windows-server': 'cancelled',
+ }));
+
+ expect(summary.verdict).toBe('failure');
+ expect(summary.failed).toEqual(['server=failure']);
+ const text = summary.lines.join('\n');
+ expect(text).toContain('Failed jobs: server=failure');
+ expect(text).not.toContain('CANCELLED, not failed');
+ expect(text).toContain('client, windows-server');
+ });
+
+ it('treats an unrecognised result as a failure, not as collateral of a cancel', () => {
+ const summary = summarizeGateResults(results({ server: 'unknown', client: 'cancelled' }));
+ expect(summary.verdict).toBe('failure');
+ expect(summary.failed).toEqual(['server=unknown']);
+ });
+
+ it('uses the supplied gate label so the two gates are distinguishable', () => {
+ const summary = summarizeGateResults(results({ gate: 'cancelled' }), 'Full CI Gate');
+ expect(summary.lines[0]).toContain('Full CI Gate');
+ });
+});
+
+describe('reportGate', () => {
+ const silentLogger = { log: () => {}, error: () => {} };
+ const capture = () => {
+ const logged = [];
+ const errored = [];
+ return { logged, errored, logger: { log: (l) => logged.push(l), error: (l) => errored.push(l) } };
+ };
+
+ it('writes a pass to stdout and reports ok', () => {
+ const { logged, errored, logger } = capture();
+ const outcome = reportGate({ env: { CI_GATE_RESULT_SERVER: 'success' }, logger, writeSummary: () => {} });
+
+ expect(outcome).toMatchObject({ verdict: 'pass', ok: true });
+ expect(logged.join('\n')).toContain('CI Gate passed');
+ expect(errored).toEqual([]);
+ });
+
+ it('publishes the verdict to the run summary, not only the step log', () => {
+ // Nobody expands a step log before concluding "CI is red"; the summary page
+ // is where the cancelled-vs-failed distinction actually gets read.
+ const written = [];
+ reportGate({
+ env: { CI_GATE_RESULT_SERVER: 'cancelled' },
+ logger: silentLogger,
+ writeSummary: (markdown) => written.push(markdown),
+ });
+
+ expect(written).toHaveLength(1);
+ expect(written[0]).toContain('CI Gate');
+ expect(written[0]).toContain('CANCELLED, not failed');
+ });
+
+ it('writes a cancel to stderr and still blocks', () => {
+ const { logged, errored, logger } = capture();
+ const outcome = reportGate({ env: { CI_GATE_RESULT_SERVER: 'cancelled' }, logger, writeSummary: () => {} });
+
+ expect(outcome).toMatchObject({ verdict: 'cancelled', ok: false });
+ expect(errored.join('\n')).toContain('CANCELLED');
+ expect(logged).toEqual([]);
+ });
+});
+
+describe('ci.yml gate wiring', () => {
+ const jobs = workflowJobs(WORKFLOW);
+
+ it.each(['gate', 'full-gate'])('%s runs the reporter instead of an inline script', (id) => {
+ expect(jobs[id]).toContain('run: node scripts/ci-gate-report.js');
+ // The inline `node -e` the reporter replaced could not be tested at all.
+ expect(jobs[id]).not.toMatch(/node -e/);
+ expect(jobs[id]).toMatch(/CI_GATE_LABEL:/);
+ // Reachable only with a checkout, and the gate has no elevated-token work.
+ expect(jobs[id]).toContain('persist-credentials: false');
+ });
+
+ it('feeds the aggregate gate every job it waits on', () => {
+ // A job added to `needs:` without its CI_GATE_RESULT_ line would be waited
+ // for and then never checked — the silent hole this asserts away.
+ const needs = jobs.gate.match(/needs: \[([^\]]+)\]/)[1]
+ .split(',')
+ .map((name) => name.trim());
+ expect(needs).toContain('windows-server');
+ for (const name of needs) {
+ expect(jobs.gate, name).toContain(`CI_GATE_RESULT_${name.toUpperCase().replace(/-/g, '_')}:`);
+ }
+ });
+});
diff --git a/scripts/ci-retry-cancelled-run.js b/scripts/ci-retry-cancelled-run.js
new file mode 100644
index 0000000000..1820a36ecc
--- /dev/null
+++ b/scripts/ci-retry-cancelled-run.js
@@ -0,0 +1,269 @@
+#!/usr/bin/env node
+
+/**
+ * Re-dispatch a CI run that was cancelled with NO successor run — once.
+ *
+ * When several PRs build at the same time, GitHub cancels in-flight runs that
+ * nothing in this repository asked it to cancel: no job failed, the in-workflow
+ * `Cancel sibling CI jobs after failure` step never ran, and no newer run
+ * exists for the branch. The PR is then blocked behind a gate that reports a
+ * cancel as if the tests were red (#7437). The same SHA passes on the next
+ * attempt once the queue drains, so one automatic re-dispatch clears it.
+ *
+ * Every guard below exists to keep that from becoming a retry loop or from
+ * re-running work somebody deliberately stopped:
+ *
+ * 1. `cancelled` conclusion only — a failure is a failure.
+ * 2. `pull_request` runs only — schedules and dispatches retry on their own
+ * terms, and a `workflow_dispatch` re-run would re-enter this path.
+ * 3. `run_attempt == 1` only. `POST /rerun` re-runs the SAME run id as
+ * attempt 2, so this is the retry budget: attempt 2's cancel sees
+ * attempt 2 and stops. One retry per run, and a PR run is one run per
+ * head SHA, so one retry per SHA.
+ * 4. No job may have concluded `failure`/`timed_out`. This repository
+ * cancels its own run from a failing job (scripts/cancel-current-ci-run.js),
+ * which makes the RUN read `cancelled` while a job really did fail —
+ * retrying that would re-run the whole suite on a genuine red.
+ * 5. No newer run may exist for the same branch. That is what a legitimate
+ * `cancel-in-progress` supersession looks like, and the newer run is
+ * already testing the code this one would have tested.
+ *
+ * An API call that cannot be completed is NOT treated as "guard passed": every
+ * lookup failure returns without re-dispatching, because the cost of missing a
+ * retry is one manual re-run and the cost of a wrong retry is a runaway loop.
+ *
+ * The workflow that runs this is triggered by `workflow_run`, so it checks out
+ * the DEFAULT branch — never the pull request's head. Nothing here executes,
+ * imports, or interpolates repository content from the PR.
+ *
+ * Builtins only: the workflow runs it straight from a checkout with no
+ * dependency install (scripts/pre-install-entrypoints.test.js enforces it).
+ */
+
+import { isDirectlyInvoked } from './lib/directInvocation.js';
+import { writeStepSummary } from './lib/githubOutput.js';
+
+const GITHUB_API_VERSION = '2022-11-28';
+const GITHUB_API_BASE = 'https://api.github.com';
+const REQUEST_TIMEOUT_MS = 15_000;
+/** ~1500 jobs. A bound, not an expectation — CI runs about fifteen. */
+const MAX_JOB_PAGES = 15;
+const JOBS_PER_PAGE = 100;
+/** Newest-first; a successor, if one exists, is at the top of this list. */
+const SIBLING_RUNS_PER_PAGE = 100;
+/** A job conclusion that means something really broke, not that it was stopped. */
+const FAILING_CONCLUSIONS = new Set(['failure', 'timed_out']);
+
+function apiBaseFrom(configuredApiUrl) {
+ if (!configuredApiUrl) return GITHUB_API_BASE;
+ let parsed;
+ try {
+ parsed = new URL(configuredApiUrl);
+ } catch {
+ return null;
+ }
+ if (parsed.protocol !== 'https:' || parsed.username || parsed.password
+ || parsed.search || parsed.hash) {
+ return null;
+ }
+ return configuredApiUrl.replace(/\/+$/, '');
+}
+
+/**
+ * Validate and normalise the run this invocation may retry.
+ *
+ * Every field comes from the `workflow_run` payload, and `headBranch` is
+ * attacker-controlled on a fork PR — it is only ever used as an encoded query
+ * parameter, never interpolated into a path or a shell.
+ *
+ * @param {NodeJS.ProcessEnv} env
+ * @returns {object|null}
+ */
+export function retryTargetFromEnv(env) {
+ const str = (key) => (typeof env[key] === 'string' ? env[key].trim() : '');
+ const repository = str('GITHUB_REPOSITORY');
+ const token = str('GITHUB_TOKEN');
+ const runId = str('CI_RUN_ID');
+ const runAttempt = str('CI_RUN_ATTEMPT');
+ const runNumber = str('CI_RUN_NUMBER');
+ const workflowId = str('CI_WORKFLOW_ID');
+ const headBranch = str('CI_RUN_HEAD_BRANCH');
+
+ if (!/^[^/\s]+\/[^/\s]+$/.test(repository) || !token) return null;
+ if (![runId, runAttempt, runNumber, workflowId].every((value) => /^\d+$/.test(value))) return null;
+ if (!headBranch) return null;
+
+ const apiBase = apiBaseFrom(str('GITHUB_API_URL'));
+ if (!apiBase) return null;
+
+ const [owner, repo] = repository.split('/');
+ return {
+ token,
+ repoPath: `${apiBase}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`,
+ runId,
+ runAttempt: Number(runAttempt),
+ runNumber: Number(runNumber),
+ workflowId,
+ headBranch,
+ headSha: str('CI_RUN_HEAD_SHA'),
+ conclusion: str('CI_RUN_CONCLUSION'),
+ event: str('CI_RUN_EVENT'),
+ };
+}
+
+function githubRequest(fetchImpl, url, token, init = {}) {
+ return fetchImpl(url, {
+ ...init,
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${token}`,
+ 'X-GitHub-Api-Version': GITHUB_API_VERSION,
+ },
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ });
+}
+
+/** Parsed body, or null for any transport, status, or parse failure. */
+async function readJson(fetchImpl, url, token, logger) {
+ try {
+ const response = await githubRequest(fetchImpl, url, token);
+ if (!response?.ok) return null;
+ return await response.json();
+ } catch (error) {
+ logger?.error?.(`⚠️ GitHub API request failed: ${error?.message || 'network request failed'}`);
+ return null;
+ }
+}
+
+/**
+ * Every job of the cancelled attempt, or null when the listing is incomplete.
+ * Null is deliberately distinct from `[]`: "we could not see the jobs" must
+ * never read as "no job failed".
+ */
+async function fetchAttemptJobs(fetchImpl, target, logger) {
+ const jobs = [];
+ for (let page = 1; page <= MAX_JOB_PAGES; page += 1) {
+ const url = `${target.repoPath}/actions/runs/${target.runId}/attempts/${target.runAttempt}`
+ + `/jobs?per_page=${JOBS_PER_PAGE}&page=${page}`;
+ const body = await readJson(fetchImpl, url, target.token, logger);
+ if (!body || !Array.isArray(body.jobs)) return null;
+ jobs.push(...body.jobs);
+ const total = Number(body.total_count);
+ // An absent/garbage total_count cannot certify completeness, so the only
+ // way to finish is to have reached a real one. A short or empty page with
+ // jobs still outstanding is a truncated listing, not the end.
+ if (Number.isFinite(total) && jobs.length >= total) return jobs;
+ if (body.jobs.length === 0) return null;
+ }
+ return null;
+}
+
+/**
+ * The run number of the newest sibling run, or null when the listing failed.
+ * `run_number` increases monotonically per workflow, so it orders runs without
+ * trusting timestamps that can tie at second resolution.
+ */
+async function fetchNewestSiblingRunNumber(fetchImpl, target, logger) {
+ const url = `${target.repoPath}/actions/workflows/${encodeURIComponent(target.workflowId)}/runs`
+ + `?event=pull_request&per_page=${SIBLING_RUNS_PER_PAGE}`
+ + `&branch=${encodeURIComponent(target.headBranch)}`;
+ const body = await readJson(fetchImpl, url, target.token, logger);
+ if (!body || !Array.isArray(body.workflow_runs)) return null;
+ return body.workflow_runs
+ .filter((run) => String(run?.id) !== target.runId)
+ .reduce((newest, run) => Math.max(newest, Number(run?.run_number) || 0), 0);
+}
+
+/**
+ * Decide whether the cancelled run deserves one re-dispatch, and do it.
+ *
+ * @param {object} [options]
+ * @param {NodeJS.ProcessEnv} [options.env]
+ * @param {typeof fetch} [options.fetchImpl]
+ * @param {{log?: Function, error?: Function}} [options.logger]
+ * @returns {Promise<{outcome: 'requested'|'skipped'|'unavailable', reason?: string, status?: number}>}
+ */
+export async function retryCancelledCiRun({
+ env = process.env,
+ fetchImpl = globalThis.fetch,
+ logger = console,
+ writeSummary = writeStepSummary,
+} = {}) {
+ // Every return goes through here so "why was my run not retried?" is
+ // answerable from the recovery run's summary page. Fixed reason codes and
+ // the numeric run id only — never the branch name or any other payload text.
+ const finish = (result) => {
+ writeSummary(`### CI cancel recovery: ${result.outcome}\n\n`
+ + `- run: ${/^\d+$/.test(String(env.CI_RUN_ID ?? '')) ? env.CI_RUN_ID : 'unidentified'}\n`
+ + `- reason: ${result.reason || 're-dispatched'}`, env);
+ return result;
+ };
+ const target = retryTargetFromEnv(env);
+ if (!target) {
+ logger.error?.('⚠️ CI retry skipped: the workflow_run environment is incomplete or malformed');
+ return finish({ outcome: 'skipped', reason: 'invalid-environment' });
+ }
+ if (typeof fetchImpl !== 'function') {
+ logger.error?.('⚠️ CI retry unavailable: fetch is not available');
+ return finish({ outcome: 'unavailable', reason: 'fetch-unavailable' });
+ }
+
+ if (target.conclusion !== 'cancelled') {
+ logger.log?.(`ℹ️ CI retry skipped: run ${target.runId} concluded ${target.conclusion || 'unknown'}, not cancelled`);
+ return finish({ outcome: 'skipped', reason: 'not-cancelled' });
+ }
+ if (target.event !== 'pull_request') {
+ logger.log?.(`ℹ️ CI retry skipped: run ${target.runId} was triggered by ${target.event || 'an unknown event'}, not a pull request`);
+ return finish({ outcome: 'skipped', reason: 'not-a-pull-request' });
+ }
+ if (target.runAttempt !== 1) {
+ logger.log?.(`ℹ️ CI retry skipped: run ${target.runId} is already attempt ${target.runAttempt} — one retry per run`);
+ return finish({ outcome: 'skipped', reason: 'retry-budget-exhausted' });
+ }
+
+ const jobs = await fetchAttemptJobs(fetchImpl, target, logger);
+ if (!jobs) {
+ logger.error?.(`⚠️ CI retry skipped: could not list the jobs of run ${target.runId}`);
+ return finish({ outcome: 'unavailable', reason: 'jobs-unavailable' });
+ }
+ const failedJobs = jobs
+ .filter((job) => FAILING_CONCLUSIONS.has(job?.conclusion))
+ .map((job) => job?.name || 'unnamed job');
+ if (failedJobs.length) {
+ logger.log?.(`ℹ️ CI retry skipped: run ${target.runId} cancelled after a real failure (${failedJobs.join(', ')})`);
+ return finish({ outcome: 'skipped', reason: 'job-failed' });
+ }
+
+ const newestSibling = await fetchNewestSiblingRunNumber(fetchImpl, target, logger);
+ if (newestSibling === null) {
+ logger.error?.(`⚠️ CI retry skipped: could not list sibling runs for ${target.headBranch}`);
+ return finish({ outcome: 'unavailable', reason: 'sibling-runs-unavailable' });
+ }
+ if (newestSibling > target.runNumber) {
+ logger.log?.(`ℹ️ CI retry skipped: run ${target.runId} was superseded by run #${newestSibling} on the same pull request`);
+ return finish({ outcome: 'skipped', reason: 'superseded' });
+ }
+
+ const response = await githubRequest(
+ fetchImpl,
+ `${target.repoPath}/actions/runs/${target.runId}/rerun`,
+ target.token,
+ { method: 'POST' },
+ ).catch((error) => {
+ logger.error?.(`⚠️ CI retry request failed: ${error?.message || 'network request failed'}`);
+ return null;
+ });
+ const status = Number(response?.status) || 0;
+ if (response && ((status >= 200 && status < 300) || response.ok === true)) {
+ logger.log?.(`🔁 Re-dispatched CI run ${target.runId} (${target.headSha.slice(0, 7) || 'unknown sha'}): cancelled with no successor run and no failing job`);
+ return finish({ outcome: 'requested', status });
+ }
+ logger.error?.(`⚠️ Could not re-dispatch CI run ${target.runId}: GitHub API returned ${status || 'an unknown status'}`);
+ return finish({ outcome: 'unavailable', status, reason: 'rerun-rejected' });
+}
+
+if (isDirectlyInvoked(import.meta.url)) {
+ // Never fail the recovery workflow: a retry that could not happen must not
+ // publish a red check of its own on top of the cancelled run.
+ await retryCancelledCiRun();
+}
diff --git a/scripts/ci-retry-cancelled-run.test.js b/scripts/ci-retry-cancelled-run.test.js
new file mode 100644
index 0000000000..71cbee6daf
--- /dev/null
+++ b/scripts/ci-retry-cancelled-run.test.js
@@ -0,0 +1,239 @@
+/**
+ * Every test here is about a guard that must NOT fire a retry. The retry
+ * itself is one API call; the risk is re-running the suite on a genuine red,
+ * looping forever, or fighting a legitimate `cancel-in-progress` supersession.
+ */
+import { readFileSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { retryCancelledCiRun, retryTargetFromEnv } from './ci-retry-cancelled-run.js';
+import { workflowJobs } from './lib/workflowJobs.js';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+const RECOVERY_WORKFLOW = readFileSync(
+ join(REPO_ROOT, '.github/workflows/ci-cancel-recovery.yml'),
+ 'utf8',
+);
+
+const BASE_ENV = {
+ GITHUB_REPOSITORY: 'example-owner/example-repo',
+ GITHUB_TOKEN: 'token-value',
+ CI_RUN_ID: '4242',
+ CI_RUN_ATTEMPT: '1',
+ CI_RUN_NUMBER: '900',
+ CI_WORKFLOW_ID: '77',
+ CI_RUN_EVENT: 'pull_request',
+ CI_RUN_CONCLUSION: 'cancelled',
+ CI_RUN_HEAD_BRANCH: 'claim/issue-1',
+ CI_RUN_HEAD_SHA: 'c'.repeat(40),
+};
+
+const json = (body) => ({ ok: true, status: 200, json: async () => body });
+
+/**
+ * A fetch stub routed by URL shape. `jobs`/`runs` default to the clean
+ * external-cancel case so each test overrides only what it is about.
+ */
+function stubFetch({ jobs = [], runs = [], rerunStatus = 201 } = {}) {
+ const calls = [];
+ const impl = vi.fn(async (url, init = {}) => {
+ calls.push({ url, method: init.method || 'GET' });
+ if (url.includes('/jobs?')) return json({ total_count: jobs.length, jobs });
+ if (url.includes('/runs?')) return json({ total_count: runs.length, workflow_runs: runs });
+ if (url.endsWith('/rerun')) return { ok: rerunStatus < 300, status: rerunStatus };
+ throw new Error(`unexpected url ${url}`);
+ });
+ return { impl, calls, rerunRequested: () => calls.some((c) => c.url.endsWith('/rerun')) };
+}
+
+const silent = { log: () => {}, error: () => {} };
+const noSummary = () => {};
+const run = (env, fetchStub) => retryCancelledCiRun({
+ env, fetchImpl: fetchStub.impl, logger: silent, writeSummary: noSummary,
+});
+
+describe('retryTargetFromEnv', () => {
+ it('accepts a well-formed workflow_run environment', () => {
+ const target = retryTargetFromEnv(BASE_ENV);
+ expect(target).toMatchObject({ runId: '4242', runAttempt: 1, runNumber: 900, workflowId: '77' });
+ expect(target.repoPath).toBe('https://api.github.com/repos/example-owner/example-repo');
+ });
+
+ it.each([
+ ['a non-numeric run id', { CI_RUN_ID: '4242; rm -rf /' }],
+ ['a missing token', { GITHUB_TOKEN: '' }],
+ ['a malformed repository', { GITHUB_REPOSITORY: 'example-owner' }],
+ ['an empty head branch', { CI_RUN_HEAD_BRANCH: '' }],
+ ['a non-https API base', { GITHUB_API_URL: 'http://api.example.com' }],
+ ])('rejects %s', (_label, override) => {
+ expect(retryTargetFromEnv({ ...BASE_ENV, ...override })).toBeNull();
+ });
+
+ it('encodes the branch name into the query, never into a path', async () => {
+ // The head branch is attacker-controlled on a fork PR.
+ const fetchStub = stubFetch();
+ await run({ ...BASE_ENV, CI_RUN_HEAD_BRANCH: 'feat/../../evil?x=1' }, fetchStub);
+
+ const listing = fetchStub.calls.find((c) => c.url.includes('/runs?'));
+ expect(listing.url).toContain('branch=feat%2F..%2F..%2Fevil%3Fx%3D1');
+ expect(listing.url).not.toContain('/evil');
+ });
+});
+
+describe('retryCancelledCiRun guards', () => {
+ it('re-dispatches a cancelled pull-request run with no failing job and no successor', async () => {
+ const fetchStub = stubFetch({
+ jobs: [{ name: 'DB tests', conclusion: 'success' }, { name: 'Client', conclusion: 'cancelled' }],
+ runs: [{ id: 4242, run_number: 900 }],
+ });
+
+ await expect(run(BASE_ENV, fetchStub)).resolves.toMatchObject({ outcome: 'requested' });
+ expect(fetchStub.rerunRequested()).toBe(true);
+ });
+
+ it('never retries a run that is already attempt 2 — the retry budget', async () => {
+ const fetchStub = stubFetch();
+ await expect(run({ ...BASE_ENV, CI_RUN_ATTEMPT: '2' }, fetchStub))
+ .resolves.toMatchObject({ outcome: 'skipped', reason: 'retry-budget-exhausted' });
+ expect(fetchStub.impl).not.toHaveBeenCalled();
+ });
+
+ it('never retries a legitimate cancel-in-progress supersession', async () => {
+ const fetchStub = stubFetch({ runs: [{ id: 5000, run_number: 901 }, { id: 4242, run_number: 900 }] });
+ await expect(run(BASE_ENV, fetchStub))
+ .resolves.toMatchObject({ outcome: 'skipped', reason: 'superseded' });
+ expect(fetchStub.rerunRequested()).toBe(false);
+ });
+
+ it('never retries a run this repo cancelled itself after a job failed', async () => {
+ // scripts/cancel-current-ci-run.js makes the RUN read `cancelled` while a
+ // job really failed. Retrying that re-runs the whole suite on a red tree.
+ const fetchStub = stubFetch({
+ jobs: [{ name: 'Server tests', conclusion: 'failure' }, { name: 'Client', conclusion: 'cancelled' }],
+ });
+ await expect(run(BASE_ENV, fetchStub))
+ .resolves.toMatchObject({ outcome: 'skipped', reason: 'job-failed' });
+ expect(fetchStub.rerunRequested()).toBe(false);
+ });
+
+ it('treats a timed-out job as a failure too', async () => {
+ const fetchStub = stubFetch({ jobs: [{ name: 'Windows', conclusion: 'timed_out' }] });
+ await expect(run(BASE_ENV, fetchStub))
+ .resolves.toMatchObject({ outcome: 'skipped', reason: 'job-failed' });
+ });
+
+ it.each([
+ ['a run that did not end cancelled', { CI_RUN_CONCLUSION: 'failure' }, 'not-cancelled'],
+ ['a nightly or dispatched run', { CI_RUN_EVENT: 'schedule' }, 'not-a-pull-request'],
+ ['a malformed environment', { CI_RUN_ID: 'not-a-number' }, 'invalid-environment'],
+ ])('skips %s', async (_label, override, reason) => {
+ const fetchStub = stubFetch();
+ await expect(run({ ...BASE_ENV, ...override }, fetchStub))
+ .resolves.toMatchObject({ outcome: 'skipped', reason });
+ expect(fetchStub.impl).not.toHaveBeenCalled();
+ });
+
+ it('does not retry when the job listing cannot be read', async () => {
+ // "We could not see the jobs" must never read as "no job failed".
+ const impl = vi.fn(async (url) => (url.includes('/jobs?')
+ ? { ok: false, status: 502 }
+ : json({ workflow_runs: [] })));
+ await expect(retryCancelledCiRun({ env: BASE_ENV, fetchImpl: impl, logger: silent, writeSummary: noSummary }))
+ .resolves.toMatchObject({ outcome: 'unavailable', reason: 'jobs-unavailable' });
+ expect(impl.mock.calls.some(([url]) => url.endsWith('/rerun'))).toBe(false);
+ });
+
+ it('does not retry when the job listing is truncated', async () => {
+ // total_count outruns the page: a failing job could be on the page we
+ // never received.
+ const impl = vi.fn(async (url) => (url.includes('/jobs?')
+ ? json({ total_count: 40, jobs: [] })
+ : json({ workflow_runs: [] })));
+ await expect(retryCancelledCiRun({ env: BASE_ENV, fetchImpl: impl, logger: silent, writeSummary: noSummary }))
+ .resolves.toMatchObject({ outcome: 'unavailable', reason: 'jobs-unavailable' });
+ });
+
+ it('does not retry when the sibling-run listing cannot be read', async () => {
+ const impl = vi.fn(async (url) => (url.includes('/runs?')
+ ? { ok: false, status: 403 }
+ : json({ total_count: 0, jobs: [] })));
+ await expect(retryCancelledCiRun({ env: BASE_ENV, fetchImpl: impl, logger: silent, writeSummary: noSummary }))
+ .resolves.toMatchObject({ outcome: 'unavailable', reason: 'sibling-runs-unavailable' });
+ });
+
+ it('survives a network failure without throwing', async () => {
+ const impl = vi.fn(async () => { throw new Error('socket hang up'); });
+ await expect(retryCancelledCiRun({ env: BASE_ENV, fetchImpl: impl, logger: silent, writeSummary: noSummary }))
+ .resolves.toMatchObject({ outcome: 'unavailable' });
+ });
+
+ it('records why it did not retry on the recovery run summary', async () => {
+ // "Why wasn't my run retried?" has to be answerable without reading logs,
+ // and the summary must never echo the attacker-controlled branch name.
+ const written = [];
+ const fetchStub = stubFetch({ runs: [{ id: 5000, run_number: 901 }] });
+ await retryCancelledCiRun({
+ env: { ...BASE_ENV, CI_RUN_HEAD_BRANCH: 'evil <img src=x>' },
+ fetchImpl: fetchStub.impl,
+ logger: silent,
+ writeSummary: (markdown) => written.push(markdown),
+ });
+
+ expect(written).toHaveLength(1);
+ expect(written[0]).toContain('reason: superseded');
+ expect(written[0]).toContain('run: 4242');
+ expect(written[0]).not.toContain('evil');
+ });
+
+ it('reports a rejected rerun rather than claiming success', async () => {
+ const fetchStub = stubFetch({ rerunStatus: 403 });
+ await expect(run(BASE_ENV, fetchStub))
+ .resolves.toMatchObject({ outcome: 'unavailable', reason: 'rerun-rejected', status: 403 });
+ });
+});
+
+describe('ci-cancel-recovery.yml wiring', () => {
+ const jobs = workflowJobs(RECOVERY_WORKFLOW);
+
+ it('triggers on a completed CI run and nothing else', () => {
+ expect(RECOVERY_WORKFLOW).toMatch(/on:\n {2}workflow_run:\n {4}workflows: \[CI\]\n {4}types: \[completed\]/);
+ // A `pull_request` trigger here would run with the PR's own code.
+ expect(RECOVERY_WORKFLOW).not.toMatch(/^\s{2}pull_request:/m);
+ });
+
+ it('pre-filters on the same three cheap guards the script re-checks', () => {
+ for (const guard of [
+ "github.event.workflow_run.conclusion == 'cancelled'",
+ "github.event.workflow_run.event == 'pull_request'",
+ 'github.event.workflow_run.run_attempt == 1',
+ ]) {
+ expect(jobs.retry).toContain(guard);
+ }
+ });
+
+ it('passes the run identity the script validates', () => {
+ for (const key of ['CI_RUN_ID', 'CI_RUN_ATTEMPT', 'CI_RUN_NUMBER', 'CI_WORKFLOW_ID',
+ 'CI_RUN_EVENT', 'CI_RUN_CONCLUSION', 'CI_RUN_HEAD_BRANCH', 'CI_RUN_HEAD_SHA']) {
+ expect(jobs.retry, key).toContain(`${key}: \${{ github.event.workflow_run.`);
+ }
+ expect(jobs.retry).toContain('run: node scripts/ci-retry-cancelled-run.js');
+ });
+
+ it('never checks out or builds the pull request head with its writable token', () => {
+ // workflow_run runs the default-branch copy; checking out the PR head here
+ // would hand `actions: write` to code from a fork.
+ expect(jobs.retry).toContain('persist-credentials: false');
+ expect(jobs.retry).not.toMatch(/ref:\s*\$\{\{/);
+ // `run:` lines only — a prose comment may mention npm, a step may not.
+ const commands = jobs.retry.split('\n').filter((line) => /^\s+run:/.test(line));
+ expect(commands).toEqual([' run: node scripts/ci-retry-cancelled-run.js']);
+ });
+
+ it('grants write only to actions, and never cancels its own recovery', () => {
+ expect(RECOVERY_WORKFLOW).toMatch(/permissions:\n {2}contents: read\n {2}actions: write\n/);
+ expect(RECOVERY_WORKFLOW).toContain('cancel-in-progress: false');
+ });
+});
diff --git a/scripts/lib/githubOutput.js b/scripts/lib/githubOutput.js
index 9112bedbb3..75eef33ad6 100644
--- a/scripts/lib/githubOutput.js
+++ b/scripts/lib/githubOutput.js
@@ -44,3 +44,21 @@ export function writeStepOutput(name, value) {
export function writeStepEnv(name, value) {
appendCommandFile('GITHUB_ENV', name, value);
}
+
+/**
+ * Append a markdown block to $GITHUB_STEP_SUMMARY, or do nothing outside
+ * Actions.
+ *
+ * Unlike the `name=value` files above, the summary is free-form markdown:
+ * newlines are content, not a delimiter, so they are preserved rather than
+ * collapsed. That makes the caller responsible for what it renders — pass
+ * fixed prose and values you control, never raw event payload text.
+ *
+ * @param {string} markdown - block to append; a trailing newline is added
+ * @param {NodeJS.ProcessEnv} [env] - injectable for tests
+ */
+export function writeStepSummary(markdown, env = process.env) {
+ const path = env.GITHUB_STEP_SUMMARY;
+ if (!path) return;
+ appendFileSync(path, `${markdown}\n`);
+}
diff --git a/scripts/lib/githubOutput.test.js b/scripts/lib/githubOutput.test.js
index 4ed704f72a..b250c7de38 100644
--- a/scripts/lib/githubOutput.test.js
+++ b/scripts/lib/githubOutput.test.js
@@ -4,7 +4,7 @@ import { join } from 'path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { writeStepEnv, writeStepOutput } from './githubOutput.js';
+import { writeStepEnv, writeStepOutput, writeStepSummary } from './githubOutput.js';
describe('writeStepOutput', () => {
let outputPath;
@@ -90,3 +90,26 @@ describe('writeStepEnv', () => {
expect(readFileSync(envPath, 'utf8')).toBe('');
});
});
+
+describe('writeStepSummary', () => {
+ let summaryPath;
+
+ beforeEach(() => {
+ summaryPath = join(mkdtempSync(join(tmpdir(), 'gh-summary-')), 'summary.md');
+ writeFileSync(summaryPath, '');
+ });
+
+ it('appends the markdown block verbatim, newlines and all', () => {
+ // The key/value writers collapse newlines because a newline forges a second
+ // entry there. In markdown a newline is content, and collapsing it would
+ // run a multi-line verdict into one unreadable line.
+ writeStepSummary('### Verdict\n\n- one\n- two', { GITHUB_STEP_SUMMARY: summaryPath });
+
+ expect(readFileSync(summaryPath, 'utf8')).toBe('### Verdict\n\n- one\n- two\n');
+ });
+
+ it('does nothing outside GitHub Actions', () => {
+ expect(() => writeStepSummary('### Verdict', {})).not.toThrow();
+ expect(readFileSync(summaryPath, 'utf8')).toBe('');
+ });
+});
diff --git a/scripts/pre-install-entrypoints.test.js b/scripts/pre-install-entrypoints.test.js
index 3e17d3d721..e53e5de058 100644
--- a/scripts/pre-install-entrypoints.test.js
+++ b/scripts/pre-install-entrypoints.test.js
@@ -45,8 +45,19 @@ const PRE_INSTALL_ENTRYPOINTS = [
*
* `cancel-current-ci-run.js` is here because it runs from an `if: failure()`
* workflow step that may fire before or during a failed dependency install.
+ *
+ * `ci-gate-report.js` runs on the two gate jobs, which check out the repo for
+ * this one script and deliberately install nothing; `ci-retry-cancelled-run.js`
+ * is the whole body of the `workflow_run` recovery workflow, which does the
+ * same. Both would otherwise be one careless import away from making the
+ * required check — or the thing that recovers a cancelled one — unloadable.
*/
-const BARE_CHECKOUT_SCRIPTS = ['scripts/cancel-current-ci-run.js', 'scripts/doctor.js'];
+const BARE_CHECKOUT_SCRIPTS = [
+ 'scripts/cancel-current-ci-run.js',
+ 'scripts/ci-gate-report.js',
+ 'scripts/ci-retry-cancelled-run.js',
+ 'scripts/doctor.js',
+];
const BUILTINS = new Set(builtinModules);
const isBuiltin = (specifier) => BUILTINS.has(specifier.replace(/^node:/, ''));