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

address review: share the Actions API helper, sparse gate checkouts, and stop overclaiming what the gate can report

[._.]/ Adam Eivy961fbeaa5b13
diff --git a/.github/workflows/ci-cancel-recovery.yml b/.github/workflows/ci-cancel-recovery.yml
index a09869cef8..cb29a3a749 100644
--- a/.github/workflows/ci-cancel-recovery.yml
+++ b/.github/workflows/ci-cancel-recovery.yml
@@ -41,17 +41,16 @@ jobs:
&& github.event.workflow_run.run_attempt == 1
runs-on: ubuntu-latest
steps:
+ # No `setup-node` and no `npm ci`: the script imports Node builtins
+ # only (enforced by scripts/pre-install-entrypoints.test.js) and every
+ # hosted runner already ships a Node new enough for it — the same
+ # pattern the `impact` job in ci.yml uses. Sparse, because the whole
+ # value of this workflow is how fast it re-dispatches.
- uses: actions/checkout@v7
with:
+ sparse-checkout: scripts
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 }}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c30e0304ad..62e30447e8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -685,9 +685,14 @@ jobs:
steps:
# The gate needs the repo only for scripts/ci-gate-report.js, which
# imports Node builtins only — no dependency install, no setup-node.
+ # `sparse-checkout` switches the fetch to a blob:none partial clone, so
+ # this costs ~1.7 MB and ~1k files instead of ~20 MB and ~8.4k — and the
+ # gate is the fan-in job every required check waits on. Cone mode always
+ # includes the repo root, which is where package.json ("type": "module")
+ # has to come from for the script to load as ESM.
- uses: actions/checkout@v7
with:
- fetch-depth: 1
+ sparse-checkout: scripts
persist-credentials: false
# A CANCELLED run and a FAILED one are different events with different
@@ -728,7 +733,7 @@ jobs:
steps:
- uses: actions/checkout@v7
with:
- fetch-depth: 1
+ sparse-checkout: scripts
persist-credentials: false
# Same reporter, one input: a cancelled aggregate gate must not read as a
diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.md
index 7dca7c066b..fbedd6bc2b 100644
--- a/docs/GITHUB_ACTIONS.md
+++ b/docs/GITHUB_ACTIONS.md
@@ -384,8 +384,9 @@ The selected work is split across parallel jobs:
- **CI Gate** — always reports one stable required-check result and fails if any
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.
+ cancelled jobs when nothing actually failed — as far as the gate job itself
+ runs, which a run-wide cancel prevents. 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.
@@ -632,6 +633,29 @@ retries only when every one of these holds:
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.
+**Why the failing-job guard reads the jobs' own conclusions** rather than a
+marker written by the fail-fast step: a marker fails OPEN. It would be written
+by a job that is already failing, on a run about to be cancelled out from under
+it, so a lost write makes a red run look externally cancelled — and get
+retried. Reading conclusions fails CLOSED: an unreadable listing is
+`jobs-unavailable` and skips the retry. Do not "simplify" this into a marker.
+The ambiguity itself is the price of cancelling the run on first failure rather
+than letting the remaining jobs fail naturally; that trade buys the 30-second
+fail-fast above and is not on the table.
+
+**This is also the only layer that can explain a run-wide cancel.** `if:
+always()` on the gate defeats an upstream failure, not a cancellation of the
+whole run — so in the external-cancel case the gate is cancelled too and never
+prints its verdict. The recovery run is a separate run, so it survives; its
+step summary records which guard applied. Publishing that back onto the pull
+request as a neutral check run is issue #7438.
+
+Two known limits, both filed: the retry fires immediately, which is while the
+queue that caused the cancel is still full (#7439), and a retry re-runs the
+whole suite — Windows shards included — so if the cause is the spending limit
+then recovery spends more of it. Reducing the billable minutes of a full run is
+the complementary root-cause lever (#7440).
+
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
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 5c0d9ad5aa..ee921dca37 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -448,9 +448,13 @@ 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.
+leaves none.
+
+**The likely cause is the Actions spending limit, not the concurrent-job cap.**
+Exceeding the job cap makes GitHub *queue* runs; cancelling in-flight runs is
+the spending-limit behaviour. So the billing reading below is the primary
+diagnostic, not a footnote. Full runs are expensive because the three Windows
+shards bill at a 2× minute multiplier.
**Tell the two apart** — list the runs for the branch and look for a successor:
@@ -479,15 +483,27 @@ 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.
+ both skipped, and the recovery run's own summary page states which of those
+ applied. This is the layer that explains a run-wide cancel, because it is the
+ only one that survives it.
+- The gate reports the difference **when the gate itself runs**.
+ `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". Note the limit: `if: always()` defeats an
+ upstream failure, not a run-wide cancellation, so in the full external-cancel
+ case the gate job is cancelled too and prints nothing. It covers a partial
+ cancel; the recovery run covers the rest.
+
+**A caveat worth knowing**: the retry re-runs the whole suite, Windows shards
+included, so if the cause really is the spending limit then recovery spends
+more of it. That is the same cost as the manual re-run it replaces, but it
+means recovery is not a substitute for reducing billable minutes — tracked in
+issue #7440.
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.
diff --git a/scripts/cancel-current-ci-run.js b/scripts/cancel-current-ci-run.js
index 1951cba449..7d73b9be79 100644
--- a/scripts/cancel-current-ci-run.js
+++ b/scripts/cancel-current-ci-run.js
@@ -13,47 +13,18 @@
*/
import { isDirectlyInvoked } from './lib/directInvocation.js';
+import { githubRequest, isSuccess, repoApiPath } from './lib/githubActionsApi.js';
-const GITHUB_API_VERSION = '2022-11-28';
-const GITHUB_API_BASE = 'https://api.github.com';
const CANCELLATION_TIMEOUT_MS = 10_000;
function targetFromEnv(env) {
- const repository = typeof env.GITHUB_REPOSITORY === 'string'
- ? env.GITHUB_REPOSITORY.trim()
- : '';
- const runId = typeof env.GITHUB_RUN_ID === 'string'
- ? env.GITHUB_RUN_ID.trim()
- : '';
+ const runId = typeof env.GITHUB_RUN_ID === 'string' ? env.GITHUB_RUN_ID.trim() : '';
const token = typeof env.GITHUB_TOKEN === 'string' ? env.GITHUB_TOKEN.trim() : '';
- const configuredApiUrl = typeof env.GITHUB_API_URL === 'string'
- ? env.GITHUB_API_URL.trim()
- : '';
+ const repoPath = repoApiPath(env);
- if (!/^[^/\s]+\/[^/\s]+$/.test(repository) || !/^\d+$/.test(runId) || !token) {
- return null;
- }
-
- let apiBase = GITHUB_API_BASE;
- if (configuredApiUrl) {
- let parsedApiUrl;
- try {
- parsedApiUrl = new URL(configuredApiUrl);
- } catch {
- return null;
- }
- if (parsedApiUrl.protocol !== 'https:' || parsedApiUrl.username || parsedApiUrl.password
- || parsedApiUrl.search || parsedApiUrl.hash) {
- return null;
- }
- apiBase = configuredApiUrl.replace(/\/+$/, '');
- }
+ if (!repoPath || !/^\d+$/.test(runId) || !token) return null;
- const [owner, repo] = repository.split('/');
- return {
- token,
- url: `${apiBase}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/actions/runs/${runId}/cancel`,
- };
+ return { token, url: `${repoPath}/actions/runs/${runId}/cancel` };
}
/**
@@ -82,18 +53,13 @@ export async function cancelCurrentCiRun({
}
try {
- const response = await fetchImpl(target.url, {
+ const response = await githubRequest(fetchImpl, target.url, target.token, {
method: 'POST',
- headers: {
- Accept: 'application/vnd.github+json',
- Authorization: `Bearer ${target.token}`,
- 'X-GitHub-Api-Version': GITHUB_API_VERSION,
- },
- signal: AbortSignal.timeout(CANCELLATION_TIMEOUT_MS),
+ timeoutMs: CANCELLATION_TIMEOUT_MS,
});
const status = Number(response?.status) || 0;
- if ((status >= 200 && status < 300) || response?.ok === true) {
+ if (isSuccess(response)) {
logger.log?.('🛑 Requested cancellation of the current CI run');
return { outcome: 'requested', status };
}
diff --git a/scripts/ci-gate-report.js b/scripts/ci-gate-report.js
index 6843867c91..4222dc531e 100644
--- a/scripts/ci-gate-report.js
+++ b/scripts/ci-gate-report.js
@@ -4,25 +4,28 @@
* 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
+ * one "did not pass" line, so a job that GitHub cancelled out from under us
+ * read exactly like a red test suite (issue 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.
+ * - cancelled — at least one job was `cancelled` and NOTHING failed. 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.
*
+ * Scope, so the next reader is not misled: this runs only when the GATE job
+ * itself runs. A run-wide cancellation takes the gate with it, and then the
+ * explanation comes from the recovery workflow instead — see "External
+ * cancellation and one automatic retry" in docs/GITHUB_ACTIONS.md.
+ *
* 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).
+ * change.
*/
import { isDirectlyInvoked } from './lib/directInvocation.js';
@@ -31,10 +34,13 @@ 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 DEFAULT_LABEL = 'CI Gate';
const TROUBLESHOOTING_ANCHOR = '"CI cancelled with no successor run" in docs/TROUBLESHOOTING.md';
+const pair = ({ job, result }) => `${job}=${result}`;
+
/**
- * Read the `CI_GATE_RESULT_<JOB>` variables into `{ jobId: result }`.
+ * Read the `CI_GATE_RESULT_<JOB>` variables into `[{ job, 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
@@ -50,7 +56,7 @@ export function collectGateResults(env = process.env) {
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',
+ result: (typeof value === 'string' && value.trim()) || 'unknown',
}));
}
@@ -59,10 +65,9 @@ export function collectGateResults(env = process.env) {
*
* @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[]}}
+ * @returns {{verdict: 'pass'|'cancelled'|'failure', lines: string[]}}
*/
-export function summarizeGateResults(results, label = 'CI Gate') {
+export function summarizeGateResults(results, label = DEFAULT_LABEL) {
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
@@ -71,24 +76,21 @@ export function summarizeGateResults(results, label = 'CI Gate') {
// 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.';
+ .map(pair);
+ const finished = () => (passed.length
+ ? `Jobs that finished: ${passed.map(pair).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,
+ finished(),
],
};
}
@@ -96,12 +98,10 @@ export function summarizeGateResults(results, label = 'CI Gate') {
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,
+ 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.',
@@ -112,14 +112,13 @@ export function summarizeGateResults(results, label = 'CI Gate') {
return {
verdict: 'pass',
- cancelled,
- failed,
- lines: [`✅ ${label} passed: ${results.map(({ job, result }) => `${job}=${result}`).join(', ') || 'no jobs selected'}`],
+ lines: [`✅ ${label} passed: ${results.map(pair).join(', ') || 'no jobs selected'}`],
};
}
/**
- * Print the verdict and report whether the gate passed.
+ * Print the verdict — to the step log and to the run summary — and report
+ * whether the gate passed.
*
* @param {object} [options]
* @param {NodeJS.ProcessEnv} [options.env]
@@ -132,19 +131,16 @@ export function reportGate({
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 };
+ const label = env.CI_GATE_LABEL?.trim() || DEFAULT_LABEL;
+ const { verdict, lines } = summarizeGateResults(collectGateResults(env), label);
+ const ok = verdict === 'pass';
+
+ for (const line of lines) (ok ? logger.log : logger.error)?.call(logger, line);
+ // The summary page too: nobody expands a step log before concluding "CI is
+ // red". Every value here is a job id or a GitHub result string, never event
+ // payload text.
+ writeSummary(`### ${ok ? '✅' : '🚫'} ${label}\n\n${lines.map((line) => `- ${line}`).join('\n')}`, env);
+ return { verdict, ok, lines };
}
if (isDirectlyInvoked(import.meta.url)) {
diff --git a/scripts/ci-gate-report.test.js b/scripts/ci-gate-report.test.js
index b8991d2594..120f919852 100644
--- a/scripts/ci-gate-report.test.js
+++ b/scripts/ci-gate-report.test.js
@@ -1,7 +1,7 @@
/**
- * 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.
+ * The gate's job is to say WHY the run is not mergeable. Before issue 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';
@@ -55,11 +55,11 @@ describe('summarizeGateResults', () => {
}));
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');
+ expect(summary.lines).toContain('Cancelled jobs: server, client, windows-server');
+ expect(summary.lines).toContain('Jobs that finished: impact=success, database=success');
// 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');
@@ -75,17 +75,15 @@ describe('summarizeGateResults', () => {
}));
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');
+ expect(summary.lines).toContain('Failed jobs: server=failure');
+ expect(summary.lines.join('\n')).not.toContain('CANCELLED, not failed');
+ expect(summary.lines.join('\n')).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']);
+ expect(summary.lines).toContain('Failed jobs: server=unknown');
});
it('uses the supplied gate label so the two gates are distinguishable', () => {
@@ -95,44 +93,44 @@ describe('summarizeGateResults', () => {
});
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) } };
+ const summaries = [];
+ return {
+ logged,
+ errored,
+ summaries,
+ logger: { log: (l) => logged.push(l), error: (l) => errored.push(l) },
+ writeSummary: (markdown) => summaries.push(markdown),
+ };
};
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: () => {} });
+ const { logged, errored, ...sinks } = capture();
+ const outcome = reportGate({ env: { CI_GATE_RESULT_SERVER: 'success' }, ...sinks });
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({
+ it('writes a cancel to stderr AND to the run summary, and still blocks', () => {
+ // Nobody expands a step log before concluding "CI is red", so the summary
+ // page carries the same verdict.
+ const { logged, errored, summaries, ...sinks } = capture();
+ const outcome = reportGate({
env: { CI_GATE_RESULT_SERVER: 'cancelled' },
- logger: silentLogger,
- writeSummary: (markdown) => written.push(markdown),
+ logger: sinks.logger,
+ writeSummary: sinks.writeSummary,
});
- 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([]);
+ expect(summaries).toHaveLength(1);
+ expect(summaries[0]).toContain('CI Gate');
+ expect(summaries[0]).toContain('CANCELLED, not failed');
});
});
@@ -141,11 +139,13 @@ describe('ci.yml gate wiring', () => {
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');
+ // The reporter and its two imports all live under scripts/; a full-tree
+ // checkout on the fan-in job every required check waits on is ~12x the
+ // download for nothing.
+ expect(jobs[id]).toContain('sparse-checkout: scripts');
});
it('feeds the aggregate gate every job it waits on', () => {
diff --git a/scripts/ci-retry-cancelled-run.js b/scripts/ci-retry-cancelled-run.js
index 1820a36ecc..a678010d97 100644
--- a/scripts/ci-retry-cancelled-run.js
+++ b/scripts/ci-retry-cancelled-run.js
@@ -7,26 +7,19 @@
* 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
+ * cancel as if the tests were red (issue 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:
+ * Five guards keep that from becoming a retry loop or from re-running work
+ * somebody deliberately stopped — the reasoning for each is the table under
+ * "External cancellation and one automatic retry" in docs/GITHUB_ACTIONS.md.
+ * The two least obvious, stated here because the code alone does not show them:
*
- * 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.
+ * - `run_attempt === 1` IS the retry budget. `POST /rerun` re-runs the same
+ * run id as attempt 2, so attempt 2's cancel sees attempt 2 and stops.
+ * - 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.
*
* 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
@@ -35,40 +28,21 @@
* 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 { githubRequest, isSuccess, repoApiPath } from './lib/githubActionsApi.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;
+/** Newest-first; a successor, if one exists, is within the first few. */
+const SIBLING_RUNS_PER_PAGE = 5;
/** 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.
*
@@ -81,25 +55,20 @@ function apiBaseFrom(configuredApiUrl) {
*/
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');
+ const repoPath = repoApiPath(env);
- if (!/^[^/\s]+\/[^/\s]+$/.test(repository) || !token) return null;
+ if (!repoPath || !token || !headBranch) 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)}`,
+ repoPath,
runId,
runAttempt: Number(runAttempt),
runNumber: Number(runNumber),
@@ -111,23 +80,14 @@ export function retryTargetFromEnv(env) {
};
}
-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),
- });
-}
+const request = (fetchImpl, url, token, init) =>
+ githubRequest(fetchImpl, url, token, { timeoutMs: REQUEST_TIMEOUT_MS, ...init });
/** 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;
+ const response = await request(fetchImpl, url, token);
+ if (!isSuccess(response)) return null;
return await response.json();
} catch (error) {
logger?.error?.(`⚠️ GitHub API request failed: ${error?.message || 'network request failed'}`);
@@ -149,10 +109,10 @@ async function fetchAttemptJobs(fetchImpl, target, 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;
+ // Only a real total can certify that the listing is complete.
+ if (!Number.isFinite(total)) return null;
+ if (jobs.length >= total) return jobs;
+ // Checked last, so `total: 0` still returns the legitimately empty list.
if (body.jobs.length === 0) return null;
}
return null;
@@ -160,8 +120,9 @@ async function fetchAttemptJobs(fetchImpl, target, logger) {
/**
* 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.
+ * `run_number` increases monotonically per workflow, so taking the maximum
+ * orders runs without trusting either the page order or timestamps that can
+ * tie at second resolution.
*/
async function fetchNewestSiblingRunNumber(fetchImpl, target, logger) {
const url = `${target.repoPath}/actions/workflows/${encodeURIComponent(target.workflowId)}/runs`
@@ -181,6 +142,7 @@ async function fetchNewestSiblingRunNumber(fetchImpl, target, logger) {
* @param {NodeJS.ProcessEnv} [options.env]
* @param {typeof fetch} [options.fetchImpl]
* @param {{log?: Function, error?: Function}} [options.logger]
+ * @param {Function} [options.writeSummary] - injectable step-summary writer
* @returns {Promise<{outcome: 'requested'|'skipped'|'unavailable', reason?: string, status?: number}>}
*/
export async function retryCancelledCiRun({
@@ -189,62 +151,67 @@ export async function retryCancelledCiRun({
logger = console,
writeSummary = writeStepSummary,
} = {}) {
- // Every return goes through here so "why was my run not retried?" is
+ const runLabel = /^\d+$/.test(String(env.CI_RUN_ID ?? '')) ? env.CI_RUN_ID : 'unidentified';
+ // Every exit 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) => {
+ // `level` is a parameter rather than derived from `outcome`: an invalid
+ // environment is a `skipped` outcome that still deserves stderr.
+ const done = (level, message, result) => {
+ logger[level]?.(message);
writeSummary(`### CI cancel recovery: ${result.outcome}\n\n`
- + `- run: ${/^\d+$/.test(String(env.CI_RUN_ID ?? '')) ? env.CI_RUN_ID : 'unidentified'}\n`
+ + `- run: ${runLabel}\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' });
+ return done('error', '⚠️ CI retry skipped: the workflow_run environment is incomplete or malformed',
+ { 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' });
+ return done('error', '⚠️ CI retry unavailable: fetch is not available',
+ { 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' });
+ return done('log', `ℹ️ CI retry skipped: run ${target.runId} concluded ${target.conclusion || 'unknown'}, not cancelled`,
+ { 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' });
+ return done('log', `ℹ️ CI retry skipped: run ${target.runId} was triggered by ${target.event || 'an unknown event'}, not a pull request`,
+ { 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' });
+ return done('log', `ℹ️ CI retry skipped: run ${target.runId} is already attempt ${target.runAttempt} — one retry per run`,
+ { 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' });
+ return done('error', `⚠️ CI retry skipped: could not list the jobs of run ${target.runId}`,
+ { 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' });
+ return done('log', `ℹ️ CI retry skipped: run ${target.runId} cancelled after a real failure (${failedJobs.join(', ')})`,
+ { 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' });
+ return done('error', `⚠️ CI retry skipped: could not list sibling runs for run ${target.runId}`,
+ { 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' });
+ return done('log', `ℹ️ CI retry skipped: run ${target.runId} was superseded by run #${newestSibling} on the same pull request`,
+ { outcome: 'skipped', reason: 'superseded' });
}
- const response = await githubRequest(
+ const response = await request(
fetchImpl,
`${target.repoPath}/actions/runs/${target.runId}/rerun`,
target.token,
@@ -253,13 +220,13 @@ export async function retryCancelledCiRun({
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 });
+ if (isSuccess(response)) {
+ return done('log', `🔁 Re-dispatched CI run ${target.runId} (${target.headSha.slice(0, 7) || 'unknown sha'}): cancelled with no successor run and no failing job`,
+ { outcome: 'requested', status: Number(response.status) || 0 });
}
- 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' });
+ const status = Number(response?.status) || 0;
+ return done('error', `⚠️ Could not re-dispatch CI run ${target.runId}: GitHub API returned ${status || 'an unknown status'}`,
+ { outcome: 'unavailable', status, reason: 'rerun-rejected' });
}
if (isDirectlyInvoked(import.meta.url)) {
diff --git a/scripts/ci-retry-cancelled-run.test.js b/scripts/ci-retry-cancelled-run.test.js
index 71cbee6daf..0c6d44aaf5 100644
--- a/scripts/ci-retry-cancelled-run.test.js
+++ b/scripts/ci-retry-cancelled-run.test.js
@@ -2,6 +2,9 @@
* 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.
+ *
+ * The API-base and repository validation live in lib/githubActionsApi.test.js,
+ * shared with scripts/cancel-current-ci-run.js.
*/
import { readFileSync } from 'fs';
import { dirname, join } from 'path';
@@ -71,16 +74,6 @@ describe('retryTargetFromEnv', () => {
])('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', () => {
@@ -108,22 +101,19 @@ describe('retryCancelledCiRun guards', () => {
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(['failure', 'timed_out'])(
+ 'never retries a run whose job concluded %s — this repo self-cancels on a real red',
+ async (conclusion) => {
+ // 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 }, { name: 'Client', conclusion: 'cancelled' }],
+ });
+ await expect(run(BASE_ENV, fetchStub))
+ .resolves.toMatchObject({ outcome: 'skipped', reason: 'job-failed' });
+ expect(fetchStub.rerunRequested()).toBe(false);
+ },
+ );
it.each([
['a run that did not end cancelled', { CI_RUN_CONCLUSION: 'failure' }, 'not-cancelled'],
@@ -136,13 +126,24 @@ describe('retryCancelledCiRun guards', () => {
expect(fetchStub.impl).not.toHaveBeenCalled();
});
+ 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');
+ });
+
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' });
+ 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);
});
@@ -152,22 +153,31 @@ describe('retryCancelledCiRun guards', () => {
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' });
+ 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' });
+ 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' });
+ await expect(retryCancelledCiRun({
+ env: BASE_ENV, fetchImpl: impl, logger: silent, writeSummary: noSummary,
+ })).resolves.toMatchObject({ outcome: 'unavailable' });
+ });
+
+ 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 });
});
it('records why it did not retry on the recovery run summary', async () => {
@@ -187,12 +197,6 @@ describe('retryCancelledCiRun guards', () => {
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', () => {
@@ -219,7 +223,6 @@ describe('ci-cancel-recovery.yml wiring', () => {
'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', () => {
@@ -232,6 +235,14 @@ describe('ci-cancel-recovery.yml wiring', () => {
expect(commands).toEqual([' run: node scripts/ci-retry-cancelled-run.js']);
});
+ it('re-dispatches from a sparse checkout with no dependency install', () => {
+ // Latency is the whole point of this workflow: a full-tree checkout plus
+ // setup-node would roughly double its time-to-re-dispatch, and the script
+ // imports Node builtins only.
+ expect(jobs.retry).toContain('sparse-checkout: scripts');
+ expect(jobs.retry).not.toContain('actions/setup-node');
+ });
+
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/githubActionsApi.js b/scripts/lib/githubActionsApi.js
new file mode 100644
index 0000000000..6933bd7455
--- /dev/null
+++ b/scripts/lib/githubActionsApi.js
@@ -0,0 +1,94 @@
+/**
+ * Shared GitHub Actions REST plumbing for the CI gates in `scripts/`.
+ *
+ * Extracted because two scripts now talk to the Actions API from inside a
+ * workflow — `cancel-current-ci-run.js` and `ci-retry-cancelled-run.js` — and
+ * the piece they share is a SECURITY check, not boilerplate: `resolveApiBase`
+ * decides which host a step-scoped `GITHUB_TOKEN` is sent to. Two copies of
+ * that meant a hardening fix could land on one and silently miss the other.
+ *
+ * ZERO external dependencies — see githubOutput.js.
+ */
+
+export const GITHUB_API_VERSION = '2022-11-28';
+const PUBLIC_API_BASE = 'https://api.github.com';
+/** `owner/repo`, rejecting anything with a slash or whitespace in a segment. */
+const REPOSITORY_PATTERN = /^[^/\s]+\/[^/\s]+$/;
+const DEFAULT_TIMEOUT_MS = 10_000;
+
+const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');
+
+/**
+ * The API origin to send the token to, or null to send it nowhere.
+ *
+ * An unset `GITHUB_API_URL` means github.com. A set one must be a plain
+ * https origin: no embedded credentials (which would travel in the request
+ * line), and no query or fragment (which would be silently dropped once a
+ * path is appended, so the caller would not be talking to the URL it read).
+ *
+ * @param {string} [configuredApiUrl] - raw `GITHUB_API_URL`
+ * @returns {string|null} base with no trailing slash
+ */
+export function resolveApiBase(configuredApiUrl) {
+ const raw = trimmed(configuredApiUrl);
+ if (!raw) return PUBLIC_API_BASE;
+ const parsed = URL.parse(raw);
+ if (!parsed || parsed.protocol !== 'https:' || parsed.username || parsed.password
+ || parsed.search || parsed.hash) {
+ return null;
+ }
+ return raw.replace(/\/+$/, '');
+}
+
+/**
+ * `<base>/repos/<owner>/<repo>` from the Actions environment, or null.
+ *
+ * The repository is read only from `GITHUB_REPOSITORY`; no caller passes a
+ * target in, so a pull request cannot redirect a request at another repo.
+ *
+ * @param {NodeJS.ProcessEnv} env
+ * @returns {string|null}
+ */
+export function repoApiPath(env) {
+ const repository = trimmed(env.GITHUB_REPOSITORY);
+ if (!REPOSITORY_PATTERN.test(repository)) return null;
+ const apiBase = resolveApiBase(env.GITHUB_API_URL);
+ if (!apiBase) return null;
+ const [owner, repo] = repository.split('/');
+ return `${apiBase}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
+}
+
+/**
+ * One authenticated Actions API call with the standard headers and a timeout.
+ *
+ * @param {typeof fetch} fetchImpl
+ * @param {string} url
+ * @param {string} token
+ * @param {{method?: string, timeoutMs?: number}} [options]
+ * @returns {Promise<Response>}
+ */
+export function githubRequest(fetchImpl, url, token, { timeoutMs = DEFAULT_TIMEOUT_MS, ...init } = {}) {
+ return fetchImpl(url, {
+ ...init,
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${token}`,
+ 'X-GitHub-Api-Version': GITHUB_API_VERSION,
+ },
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+}
+
+/**
+ * True for a 2xx response.
+ *
+ * Belt and braces: a real `Response` sets `ok` from the status, but these
+ * callers inject `fetchImpl`, so a stub that reports only one of the two
+ * still reads correctly.
+ *
+ * @param {{status?: number, ok?: boolean}} [response]
+ */
+export function isSuccess(response) {
+ const status = Number(response?.status) || 0;
+ return (status >= 200 && status < 300) || response?.ok === true;
+}
diff --git a/scripts/lib/githubActionsApi.test.js b/scripts/lib/githubActionsApi.test.js
new file mode 100644
index 0000000000..2cc73c52cc
--- /dev/null
+++ b/scripts/lib/githubActionsApi.test.js
@@ -0,0 +1,87 @@
+/**
+ * `resolveApiBase` decides which host a step-scoped `GITHUB_TOKEN` is sent to,
+ * so these are the tests that used to live — in duplicate — in each calling
+ * script's suite.
+ */
+import { describe, expect, it, vi } from 'vitest';
+
+import { githubRequest, isSuccess, repoApiPath, resolveApiBase } from './githubActionsApi.js';
+
+describe('resolveApiBase', () => {
+ it('defaults to the public API when GITHUB_API_URL is absent', () => {
+ expect(resolveApiBase(undefined)).toBe('https://api.github.com');
+ expect(resolveApiBase(' ')).toBe('https://api.github.com');
+ });
+
+ it('accepts a GitHub Enterprise base and strips its trailing slashes', () => {
+ expect(resolveApiBase('https://github.example.test/api/v3/')).toBe('https://github.example.test/api/v3');
+ });
+
+ it.each([
+ ['plaintext http', 'http://example.invalid/api/v3'],
+ ['an unparseable value', 'not-a-url'],
+ ['embedded credentials', 'https://user:[email protected]/api/v3'],
+ // A query or fragment is silently dropped once a path is appended, so the
+ // request would not go to the URL the caller read.
+ ['a query string', 'https://example.invalid/api/v3?token=x'],
+ ['a fragment', 'https://example.invalid/api/v3#x'],
+ ])('refuses %s', (_label, value) => {
+ expect(resolveApiBase(value)).toBeNull();
+ });
+});
+
+describe('repoApiPath', () => {
+ it('builds the repo path from GITHUB_REPOSITORY alone', () => {
+ expect(repoApiPath({ GITHUB_REPOSITORY: 'example-owner/example-repo' }))
+ .toBe('https://api.github.com/repos/example-owner/example-repo');
+ });
+
+ it.each([
+ ['a URL smuggled into the slug', 'https://example.invalid/other'],
+ ['a missing repo segment', 'example-owner'],
+ ['whitespace in a segment', 'example owner/repo'],
+ ['nothing at all', ''],
+ ])('rejects %s', (_label, repository) => {
+ expect(repoApiPath({ GITHUB_REPOSITORY: repository })).toBeNull();
+ });
+
+ it('refuses to build a path when the API base is refused', () => {
+ expect(repoApiPath({
+ GITHUB_REPOSITORY: 'example-owner/example-repo',
+ GITHUB_API_URL: 'http://example.invalid',
+ })).toBeNull();
+ });
+});
+
+describe('githubRequest', () => {
+ it('sends the standard Actions headers and an abort signal', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue({ ok: true, status: 200 });
+ await githubRequest(fetchImpl, 'https://api.github.com/x', 'token-value', { method: 'POST' });
+
+ expect(fetchImpl).toHaveBeenCalledWith('https://api.github.com/x', {
+ method: 'POST',
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: 'Bearer token-value',
+ 'X-GitHub-Api-Version': '2022-11-28',
+ },
+ signal: expect.any(AbortSignal),
+ });
+ // timeoutMs configures the signal; it must not leak into fetch's init.
+ expect(fetchImpl.mock.calls[0][1]).not.toHaveProperty('timeoutMs');
+ });
+});
+
+describe('isSuccess', () => {
+ it.each([[200, true], [202, true], [299, true], [304, false], [403, false], [500, false]])(
+ 'reads status %i as %s', (status, expected) => {
+ expect(isSuccess({ status, ok: status >= 200 && status < 300 })).toBe(expected);
+ },
+ );
+
+ it('accepts a stub that reports only one of status or ok', () => {
+ expect(isSuccess({ ok: true })).toBe(true);
+ expect(isSuccess({ status: 201 })).toBe(true);
+ expect(isSuccess(null)).toBe(false);
+ });
+});
diff --git a/scripts/run-ci-tests.js b/scripts/run-ci-tests.js
index 2a47fb19fe..025d9ced15 100644
--- a/scripts/run-ci-tests.js
+++ b/scripts/run-ci-tests.js
@@ -1,11 +1,11 @@
#!/usr/bin/env node
import { spawnSync } from 'child_process';
-import { appendFileSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { prepareCliSpawn } from '../server/lib/bufferedSpawn.js';
import { isDirectlyInvoked } from './lib/directInvocation.js';
+import { writeStepSummary } from './lib/githubOutput.js';
const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
@@ -41,9 +41,7 @@ export function recordVitestDuration(scope, label, startedAt) {
const seconds = ((Date.now() - startedAt) / 1000).toFixed(1);
const line = `⏱ ${scope} ${label}: ${seconds}s`;
console.log(line);
- if (process.env.GITHUB_STEP_SUMMARY) {
- appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${line}\n`);
- }
+ writeStepSummary(line);
}
function spawnNpm(scope, script, extraArgs, label) {