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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
name the job and step behind a fail-fast CI cancel, instead of a wall of "cancelled" (#7574)
[._.]/ Adam Eivy82cfcd49ad8f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0bdeb6abb6..5b97e68349 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -318,9 +318,13 @@ jobs:if: needs.impact.outputs.smoke == 'true' && matrix.shard == 1run: npm run smoke- - name: Cancel sibling CI jobs after failure+ - name: Report the failure, then cancel sibling CI jobsif: failure() && github.event_name == 'pull_request'env:+ # Actions exposes no variable for the matrix leg, and the annotation+ # has to name the shard even when the API lookup behind it fails.+ # Empty on the unsharded jobs, which the script treats as absent.+ CI_FAILED_SHARD: ${{ matrix.shard }}GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: node scripts/cancel-current-ci-run.js@@ -412,9 +416,13 @@ jobs:if: needs.impact.outputs.build == 'true' && matrix.shard == 1run: npm run test --prefix client -- ApiExplorer.bundle- - name: Cancel sibling CI jobs after failure+ - name: Report the failure, then cancel sibling CI jobsif: failure() && github.event_name == 'pull_request'env:+ # Actions exposes no variable for the matrix leg, and the annotation+ # has to name the shard even when the API lookup behind it fails.+ # Empty on the unsharded jobs, which the script treats as absent.+ CI_FAILED_SHARD: ${{ matrix.shard }}GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: node scripts/cancel-current-ci-run.js@@ -488,9 +496,13 @@ jobs:CI_LINT_FILES: ${{ needs.impact.outputs.lint_files }}run: node scripts/run-ci-lint.js- - name: Cancel sibling CI jobs after failure+ - name: Report the failure, then cancel sibling CI jobsif: failure() && github.event_name == 'pull_request'env:+ # Actions exposes no variable for the matrix leg, and the annotation+ # has to name the shard even when the API lookup behind it fails.+ # Empty on the unsharded jobs, which the script treats as absent.+ CI_FAILED_SHARD: ${{ matrix.shard }}GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: node scripts/cancel-current-ci-run.js@@ -632,9 +644,13 @@ jobs:env:PGDATABASE: portos_test- - name: Cancel sibling CI jobs after failure+ - name: Report the failure, then cancel sibling CI jobsif: failure() && github.event_name == 'pull_request'env:+ # Actions exposes no variable for the matrix leg, and the annotation+ # has to name the shard even when the API lookup behind it fails.+ # Empty on the unsharded jobs, which the script treats as absent.+ CI_FAILED_SHARD: ${{ matrix.shard }}GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: node scripts/cancel-current-ci-run.js@@ -764,9 +780,13 @@ jobs:PGPASSWORD: portosrun: node scripts/run-ci-tests.js server- - name: Cancel sibling CI jobs after failure+ - name: Report the failure, then cancel sibling CI jobsif: failure() && github.event_name == 'pull_request'env:+ # Actions exposes no variable for the matrix leg, and the annotation+ # has to name the shard even when the API lookup behind it fails.+ # Empty on the unsharded jobs, which the script treats as absent.+ CI_FAILED_SHARD: ${{ matrix.shard }}GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: node scripts/cancel-current-ci-run.js@@ -775,6 +795,12 @@ jobs:if: always()needs: [impact, server, client, lint, database, windows-server]runs-on: ubuntu-latest+ # READ, not write: the reporter only lists this run's jobs, to name the one+ # whose STEP failed when the fail-fast cancel beat GitHub to writing the job+ # conclusion. Cancelling the run stays a leaf-job privilege.+ permissions:+ contents: read+ actions: readsteps:# The gate needs the repo only for scripts/ci-gate-report.js, which# imports Node builtins only — no dependency install, no setup-node.@@ -794,6 +820,9 @@ jobs:# job; adding a job to the gate is one line here and no code change.- name: Require every selected job to passenv:+ # Lets the reporter read this run's job steps when the verdict would+ # otherwise be a bare "cancelled" — see scripts/ci-gate-report.js.+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}CI_GATE_LABEL: CI GateCI_GATE_RESULT_IMPACT: ${{ needs.impact.result }}CI_GATE_RESULT_SERVER: ${{ needs.server.result }}@@ -824,6 +853,9 @@ jobs:if: always() && needs.impact.outputs.full == 'true' && needs.impact.outputs.windows_mode == 'full'needs: [impact, gate]runs-on: ubuntu-latest+ permissions:+ contents: read+ actions: readsteps:- uses: actions/checkout@v7with:@@ -834,6 +866,7 @@ jobs:# red complete suite on the release path either.- name: Require the aggregate gate to have passedenv:+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}CI_GATE_LABEL: Full CI Gate# Strict: a `skipped` gate must not satisfy this one. Unlike the# aggregate gate, whose per-job `skipped` is the impact plan doingdiff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex d0036ae735..231a0ba106 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -495,12 +495,30 @@ that is actually red. Two PortOS incidents were misdiagnosed as billing this way(#7482 on 2026-09-16, #7571 on 2026-09-17) and burned full-matrix re-runs beforeanyone read a job log.+#### Step 0 — read the annotation, then the gate (usually this is the whole answer)++Both now name the job and the failing step, and neither depends on a job+conclusion, so both survive the cancel:++- **The Checks tab's `::error` annotation.** `scripts/cancel-current-ci-run.js`+ prints it *before* it POSTs the cancel, and Actions records an annotation the+ instant the line is printed. It renders above the fold on the pull request.+- **The `CI Gate` summary.** `scripts/ci-gate-report.js` queries this run's job+ steps whenever its verdict would otherwise be `cancelled`, and reports a+ failure naming the culprit instead.++Both are best-effort. If the annotation shows only a job-and-shard label, or+the gate still says `CANCELLED, not failed`, the lookup behind them did not+land — fall through to step 1 and run it by hand. A run from before #7574 has+neither.+#### Step 1 — ask whether a STEP failed (this is the primary diagnostic)-A cancelled job keeps its steps' conclusions, so the failing step survives even-though the job that owns it reads `cancelled`. **`gh run view --json jobs` does-not expose steps** — that omission is precisely why both incidents above were-misread. Go to the REST API instead:+This is what step 0's two surfaces do for you; run it by hand when they are+missing or came back empty. A cancelled job keeps its steps' conclusions, so the+failing step survives even though the job that owns it reads `cancelled`.+**`gh run view --json jobs` does not expose steps** — that omission is precisely+why both incidents above were misread. Go to the REST API instead:```bashgh api "/repos/atomantic/PortOS/actions/runs/<run-id>/jobs?per_page=100" \@@ -559,9 +577,11 @@ Supporting signals for the spending-limit case, none of them sufficient alone:- Every runner is cancelled within a short window of one another, rather thanone job finishing ~30–60 s ahead of the rest.- The logs show tests still passing right up to the cancel.-- Nothing in `scripts/ci-gate-report.js`'s output helps here — it prints- `CANCELLED, not failed` for a fail-fast run too, because it reads job- conclusions. Do not count it as a signal either way.+- `scripts/ci-gate-report.js` distinguishes the two now, so its wording IS a+ signal — but read which sentence it printed. "Checked every job's STEP+ conclusions too, and none failed" means the lookup ran and cleared a+ fail-fast cancel. "could NOT be read" means it did not, and rules nothing+ out. A run from before #7574 says neither.Exceeding the concurrent-**job cap** makes GitHub queue runs; cancellingin-flight runs is the **spending-limit** behaviour. Full runs are expensive@@ -595,12 +615,15 @@ which branch protection still gates), and leave the PR for the owner.- 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". Two limits: `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; and the wording is- about job conclusions, so it says `CANCELLED, not failed` for a fail-fast run- as well. **Never read that line as proof of an external cancel** — it is a- statement about conclusions, not about causes.+ undifferentiated "did not pass". Since #7574 it reaches that wording only+ after querying the run's job **steps** and finding none failed, so a+ fail-fast cancel is reported as the red run it is rather than sharing the+ external cancel's line. Two limits remain: `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; and when the step lookup itself+ fails the gate says so and falls back to the conclusion-only wording, which+ proves nothing about causes. It covers a partial cancel; the recovery run+ covers the rest.**A caveat worth knowing**: the retry re-runs the whole suite, Windows shardsincluded, so if the cause really is the spending limit then recovery spendsdiff --git a/scripts/cancel-current-ci-run.js b/scripts/cancel-current-ci-run.jsindex 7d73b9be79..9c6a416e42 100644--- a/scripts/cancel-current-ci-run.js+++ b/scripts/cancel-current-ci-run.js@@ -1,47 +1,120 @@#!/usr/bin/env node/**- * Best-effort cancellation for the workflow run executing this step.+ * Report the failure, then cancel the workflow run executing this step.** The workflow deliberately supplies no target arguments. The repository and* run id come only from GitHub Actions' environment, so a PR cannot redirect* this request to another run or repository through script arguments.*- * This script runs after a real CI failure. Cancellation errors must never- * replace the original failure, so every unavailable/invalid path returns- * normally after emitting a single diagnostic line.+ * REPORTING COMES FIRST, and it is the reason this script is not just a POST.+ * Cancelling the run stops the failing job before GitHub writes its `failure`+ * conclusion, so afterwards `gh pr checks`, `gh run view --json jobs` and+ * `gh run view --log-failed` all show a wall of `cancelled` with no cause —+ * three debugging sessions went looking for a billing problem instead of the+ * one-line assertion sitting in a job log (issue 7574). A workflow annotation+ * is written the instant it is printed and survives the cancellation, so the+ * run says what failed before it stops saying anything at all.+ *+ * This script runs after a real CI failure. NOTHING here may replace that+ * failure: every diagnostic and cancellation path returns normally after+ * emitting a single line, and the cancel is attempted even when the reporting+ * half throws.*/import { isDirectlyInvoked } from './lib/directInvocation.js';-import { githubRequest, isSuccess, repoApiPath } from './lib/githubActionsApi.js';+import {+ currentRunTargetFromEnv, fetchJobsWithFailedSteps, formatFailedJob, githubRequest, isSuccess, trimmed,+} from './lib/githubActionsApi.js';+import { formatErrorAnnotation, safeWorkflowText, writeStepSummary } from './lib/githubOutput.js';const CANCELLATION_TIMEOUT_MS = 10_000;+/**+ * Short, because this lookup sits between the failure and the cancel and every+ * second of it is a second ~13 doomed sibling legs keep billing (the Windows+ * shards at a 2x minute multiplier). Three seconds is ~40 runner-seconds in the+ * worst case and a few in the normal one.+ *+ * Running the lookup CONCURRENTLY with the cancel would cost nothing at all,+ * and is deliberately not done: once the cancel lands, Actions may kill this+ * job mid-step, and the enriched annotation — the entire point of issue 7574 —+ * would be lost to that race on exactly the runs it exists to explain.+ */+const DIAGNOSTIC_TIMEOUT_MS = 3_000;-function targetFromEnv(env) {- 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 repoPath = repoApiPath(env);+/**+ * This job, as a human reads it in the Checks tab.+ *+ * `GITHUB_JOB` is the job ID (`windows-server`), not the rendered name, and+ * Actions exposes no variable for the matrix leg — so the workflow passes the+ * shard in. Together they identify the row without an API call, which is what+ * keeps the annotation useful when the lookup below is the thing that failed.+ */+function localJobLabel(env) {+ const job = safeWorkflowText(env.GITHUB_JOB, 'this job');+ const shard = trimmed(env.CI_FAILED_SHARD);+ return /^\d+$/.test(shard) ? `${job} (shard ${shard})` : job;+}- if (!repoPath || !/^\d+$/.test(runId) || !token) return null;+/**+ * Write the annotation and the run-summary block naming what failed.+ *+ * Never throws: it runs after a real CI failure, and a diagnostic that took the+ * cancel down with it would cost money on every red build.+ */+async function reportFailureBeforeCancel({ env, fetchImpl, logger, writeSummary, target }) {+ const label = localJobLabel(env);+ const found = await fetchJobsWithFailedSteps(fetchImpl, target && {+ ...target,+ timeoutMs: DIAGNOSTIC_TIMEOUT_MS,+ });+ const lines = found?.length+ ? found.map(formatFailedJob)+ : [`${label} — the failing step could not be read from the Actions API; open this job's log`];- return { token, url: `${repoPath}/actions/runs/${runId}/cancel` };+ try {+ for (const line of lines) logger.log?.(formatErrorAnnotation(`CI failed: ${label}`, line));+ writeSummary(+ [+ `### ❌ CI failed in ${label}`,+ '',+ ...lines.map((line) => `- ${line}`),+ '',+ 'Every other job was cancelled on purpose by the fail-fast step, so they are'+ + ' collateral and not the cause. `gh run view --log-failed` is empty for this'+ + ' run because the cancel lands before a `failure` conclusion is written —'+ + " open the job named above and read its log.",+ ].join('\n'),+ env,+ );+ } catch (error) {+ logger.error?.(`⚠️ Could not write the CI failure annotation: ${error?.message || 'unknown error'}`);+ }}/**- * Ask GitHub to cancel the workflow run containing this step.+ * Report the failure, then ask GitHub to cancel the workflow run containing+ * this step.** @param {object} [options]* @param {NodeJS.ProcessEnv} [options.env] - Actions environment to read.* @param {typeof fetch} [options.fetchImpl] - Injectable fetch for tests.* @param {{log?: Function, error?: Function}} [options.logger] - Injectable logger.+ * @param {Function} [options.writeSummary] - Injectable step-summary writer.* @returns {Promise<{outcome: string, status?: number, reason?: string}>}*/export async function cancelCurrentCiRun({env = process.env,fetchImpl = globalThis.fetch,logger = console,+ writeSummary = writeStepSummary,} = {}) {- const target = targetFromEnv(env);+ const target = currentRunTargetFromEnv(env);++ // Before the POST, and ahead of the early returns below: a job whose token or+ // repository is unusable still failed, and the annotation needs neither.+ await reportFailureBeforeCancel({ env, fetchImpl, logger, writeSummary, target });+if (!target) {logger.error?.('⚠️ CI run cancellation skipped: required GitHub Actions environment is unavailable');return { outcome: 'skipped', reason: 'invalid-environment' };@@ -53,7 +126,8 @@ export async function cancelCurrentCiRun({}try {- const response = await githubRequest(fetchImpl, target.url, target.token, {+ const url = `${target.repoPath}/actions/runs/${target.runId}/cancel`;+ const response = await githubRequest(fetchImpl, url, target.token, {method: 'POST',timeoutMs: CANCELLATION_TIMEOUT_MS,});diff --git a/scripts/cancel-current-ci-run.test.js b/scripts/cancel-current-ci-run.test.jsindex b317404248..0542b1f7fd 100644--- a/scripts/cancel-current-ci-run.test.js+++ b/scripts/cancel-current-ci-run.test.js@@ -133,3 +133,113 @@ describe('cancelCurrentCiRun', () => {expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('environment'));});});++/**+ * Issue 7574: cancelling the run stops the failing job before GitHub records+ * its `failure` conclusion, so the annotation printed here is the ONLY surface+ * that survives to name the culprit. These cover the ordering that makes that+ * true, and the contract that a broken diagnostic never costs the cancel.+ */+describe('reportFailureBeforeCancel', () => {+ const ANNOTATION_ENV = { ...ENV, GITHUB_JOB: 'windows-server', CI_FAILED_SHARD: '3' };+ const JOBS_URL = 'https://api.github.com/repos/example/portos/actions/runs/123456789/jobs?per_page=100';+ const CANCEL_URL = 'https://api.github.com/repos/example/portos/actions/runs/123456789/cancel';+ const jobsResponse = (jobs) => ({ ok: true, status: 200, json: async () => ({ jobs }) });+ const FAILED_RUN = [+ { name: 'Server tests (1/2)', conclusion: 'cancelled', steps: [{ name: 'Run server tests', conclusion: 'cancelled' }] },+ {+ name: 'Windows server unit tests (3/3)',+ conclusion: 'cancelled',+ steps: [+ { name: 'Checkout', conclusion: 'success' },+ { name: 'Run server tests on Windows', conclusion: 'failure' },+ ],+ },+ ];++ it('annotates the failing job and step BEFORE it asks for the cancel', async () => {+ const { fetchImpl, logger } = setup();+ const summaries = [];+ fetchImpl.mockImplementation((url) => (+ url === JOBS_URL ? Promise.resolve(jobsResponse(FAILED_RUN)) : Promise.resolve(response(202))+ ));++ await cancelCurrentCiRun({+ env: ANNOTATION_ENV, fetchImpl, logger, writeSummary: (markdown) => summaries.push(markdown),+ });++ const annotation = logger.log.mock.calls.map(([line]) => line).find((line) => line.startsWith('::error'));+ expect(annotation).toContain('Windows server unit tests (3/3) — failed step: Run server tests on Windows');+ // Ordering is the whole point: a cancel that lands first can kill this job+ // mid-step, and an unwritten annotation explains nothing.+ expect(fetchImpl.mock.calls.map(([url]) => url)).toEqual([JOBS_URL, CANCEL_URL]);+ expect(summaries[0]).toContain('Run server tests on Windows');+ expect(logger.error).not.toHaveBeenCalled();+ });++ it('still names this job and shard when the step lookup is unavailable', async () => {+ // The fallback is why the workflow passes the shard in: `GITHUB_JOB` alone+ // cannot tell three identical Windows rows apart.+ const { fetchImpl, logger } = setup();+ fetchImpl.mockImplementation((url) => (+ url === JOBS_URL ? Promise.reject(new Error('network unavailable')) : Promise.resolve(response(202))+ ));++ await expect(cancelCurrentCiRun({ env: ANNOTATION_ENV, fetchImpl, logger }))+ .resolves.toEqual({ outcome: 'requested', status: 202 });++ const annotation = logger.log.mock.calls.map(([line]) => line).find((line) => line.startsWith('::error'));+ expect(annotation).toContain('windows-server (shard 3)');+ });++ it('annotates even when the environment cannot authorize a cancel', async () => {+ const { fetchImpl, logger } = setup();++ await expect(cancelCurrentCiRun({ env: { GITHUB_JOB: 'lint' }, fetchImpl, logger }))+ .resolves.toEqual({ outcome: 'skipped', reason: 'invalid-environment' });++ expect(logger.log).toHaveBeenCalledWith(expect.stringContaining('::error'));+ expect(logger.log).toHaveBeenCalledWith(expect.stringContaining('lint'));+ expect(fetchImpl).not.toHaveBeenCalled();+ });++ it('still attempts the cancel when the annotation path throws', async () => {+ // The script runs after a real failure. A diagnostic that takes the cancel+ // down with it would cost money on every red build.+ const { fetchImpl } = setup();+ const logger = {+ log: vi.fn((line) => {+ if (String(line).startsWith('::error')) throw new Error('stdout closed');+ }),+ error: vi.fn(),+ };+ fetchImpl.mockResolvedValue(response(202));++ await expect(cancelCurrentCiRun({ env: ANNOTATION_ENV, fetchImpl, logger }))+ .resolves.toMatchObject({ outcome: 'requested' });++ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('annotation'));+ expect(fetchImpl).toHaveBeenCalledWith(CANCEL_URL, expect.objectContaining({ method: 'POST' }));+ });++ it('keeps a workflow-sourced name from forging its own workflow command', async () => {+ // Job and step names come from a workflow file, and Actions reads a leading+ // `::` as a command — so a name must never be able to open one.+ const { fetchImpl, logger } = setup();+ fetchImpl.mockImplementation((url) => (+ url === JOBS_URL+ ? Promise.resolve(jobsResponse([{+ name: 'evil\n::error::forged',+ steps: [{ name: 'step', conclusion: 'failure' }],+ }]))+ : Promise.resolve(response(202))+ ));++ await cancelCurrentCiRun({ env: ANNOTATION_ENV, fetchImpl, logger });++ const printed = logger.log.mock.calls.map(([line]) => line).filter((line) => line.startsWith('::error'));+ expect(printed).toHaveLength(1);+ expect(printed[0]).not.toContain('::error::forged');+ expect(printed[0]).toContain('evil');+ });+});diff --git a/scripts/ci-fail-fast.test.js b/scripts/ci-fail-fast.test.jsindex f6fe2b05ee..524f98d066 100644--- a/scripts/ci-fail-fast.test.js+++ b/scripts/ci-fail-fast.test.js@@ -15,7 +15,7 @@ const NON_LEAF_JOBS = new Set(['impact', 'gate', 'full-gate']);// opposite — discovery silently ceasing to see one of the four while the other// three keep every assertion green.const EXPECTED_LEAF_JOBS = ['client', 'database', 'server', 'windows-server'];-const CANCEL_STEP_HEADING = ' - name: Cancel sibling CI jobs after failure';+const CANCEL_STEP_HEADING = ' - name: Report the failure, then cancel sibling CI jobs';// Both spellings of the dependency. Under a scalar-only pattern, a leaf job// rewritten to the list form (`needs: [impact]`) dropped out of every assertion// below without failing anything — the exact silent coverage loss this contract@@ -25,9 +25,22 @@ const FAIL_FAST_STEP = [CANCEL_STEP_HEADING," if: failure() && github.event_name == 'pull_request'",' env:',+ // The annotation names the matrix leg, and Actions exposes no variable for+ // it — so the shard is passed in. Empty on the unsharded jobs, which the+ // script treats as absent.+ ' CI_FAILED_SHARD: ${{ matrix.shard }}',' GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}',' run: node scripts/cancel-current-ci-run.js',].join('\n');+/**+ * Comments are explanation, not contract. Stripping them before the exact match+ * below keeps the guard on the step's BEHAVIOUR — `if:`, env, `run:` — so+ * rewording a comment in ci.yml cannot fail CI in five jobs at once.+ */+const withoutComments = (yaml) => yaml+ .split('\n')+ .filter((line) => !/^\s*#/.test(line))+ .join('\n');describe('ci.yml fail-fast cancellation contract', () => {const jobs = workflowJobs(WORKFLOW);@@ -52,7 +65,7 @@ describe('ci.yml fail-fast cancellation contract', () => {for (const id of leafJobs) {const body = jobs[id];expect(body, id).toBeTruthy();- const step = body.slice(body.lastIndexOf(CANCEL_STEP_HEADING)).trimEnd();+ const step = withoutComments(body.slice(body.lastIndexOf(CANCEL_STEP_HEADING))).trimEnd();expect(step, id).toBe(FAIL_FAST_STEP);expect(body.match(/GITHUB_TOKEN:/g), id).toHaveLength(1);}diff --git a/scripts/ci-gate-report.js b/scripts/ci-gate-report.jsindex 4d8301069c..0446bd20dd 100644--- a/scripts/ci-gate-report.js+++ b/scripts/ci-gate-report.js@@ -15,13 +15,26 @@* 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.+ * reported as collateral, because the fail-fast step in+ * ci.yml cancels them on purpose.+ *+ * The catch, and why this talks to the API at all: `needs.<job>.result` is the+ * job's CONCLUSION, and the fail-fast step cancels the run before GitHub writes+ * the failing job's `failure` conclusion. The culprit therefore arrives here as+ * `cancelled` like everything else, and the gate reported the cancelled verdict+ * on a run that really was red (issue 7574). A cancelled job keeps its STEPS'+ * conclusions, so when — and only when — the cancelled verdict is about to be+ * printed, the run's jobs are queried for a failed step. Best-effort by design:+ * an API failure falls back to today's wording rather than turning a cancelled+ * run red or green on a network blip.** 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.+ * itself runs. The two cancels differ here, and it matters. Our OWN fail-fast+ * cancel leaves the gate running — `if: always()` survives it, and the gate is+ * where a red run gets its verdict, which is why the culprit lookup above is+ * worth having. An EXTERNAL 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@@ -29,6 +42,9 @@*/import { isDirectlyInvoked } from './lib/directInvocation.js';+import {+ currentRunTargetFromEnv, fetchJobsWithFailedSteps, formatFailedJob,+} from './lib/githubActionsApi.js';import { writeStepSummary } from './lib/githubOutput.js';const RESULT_ENV_PREFIX = 'CI_GATE_RESULT_';@@ -42,6 +58,14 @@ const PASSING_RESULTS = new Set(['success', 'skipped']);*/const STRICT_PASSING_RESULTS = new Set(['success']);const DEFAULT_LABEL = 'CI Gate';+/**+ * The gate jobs' own display names, excluded from the culprit lookup. Both fail+ * downstream of any red run — by design, that is their job — so naming one as+ * the culprit would point every reader back at the gate they are already+ * looking at. Asserted against ci.yml's `name:` lines in the wiring test.+ */+const GATE_JOB_NAMES = new Set(['CI Gate', 'Full CI Gate']);+const CULPRIT_TIMEOUT_MS = 10_000;const TROUBLESHOOTING_ANCHOR = '"CI red with every job \'cancelled\'" in docs/TROUBLESHOOTING.md';const pair = ({ job, result }) => `${job}=${result}`;@@ -72,10 +96,21 @@ export function collectGateResults(env = process.env) {** @param {Array<{job: string, result: string}>} results* @param {string} [label] - The gate's display name, for the message.- * @param {boolean} [requireSuccess] - when true, `skipped` does not pass+ * @param {object} [options]+ * @param {boolean} [options.requireSuccess] - when true, `skipped` does not pass+ * @param {Array<{name: string, steps: string[]}>|null} [options.culprits] - jobs+ * the Actions API reports with a FAILED STEP, consulted only for a run that+ * would otherwise read as cancelled. THREE states, not two: a non-empty list+ * is a red run; `[]` is "looked, nothing failed"; `null` is "could not look".+ * The last two both stay cancelled, but they warrant different advice — see+ * the cancelled branch.* @returns {{verdict: 'pass'|'cancelled'|'failure', lines: string[]}}*/-export function summarizeGateResults(results, label = DEFAULT_LABEL, requireSuccess = false) {+export function summarizeGateResults(+ results,+ label = DEFAULT_LABEL,+ { requireSuccess = false, culprits = null } = {},+) {const passing = requireSuccess ? STRICT_PASSING_RESULTS : PASSING_RESULTS;const passed = results.filter(({ result }) => passing.has(result));const cancelled = results.filter(({ result }) => result === 'cancelled').map(({ job }) => job);@@ -105,27 +140,48 @@ export function summarizeGateResults(results, label = DEFAULT_LABEL, requireSucc}if (cancelled.length) {+ if (culprits?.length) {+ return {+ verdict: 'failure',+ lines: [+ `❌ ${label}: a job FAILED. Its conclusion reads cancelled because the fail-fast`+ + ' step stopped the run before GitHub recorded the failure.',+ ...culprits.map((job) => `Failing job: ${formatFailedJob(job)}`),+ `Cancelled jobs: ${cancelled.join(', ')}`,+ finished(),+ 'Open that job and read its log. `gh run view --log-failed` returns nothing'+ + ' for this shape of run, because no job concluded `failure`.',+ ],+ };+ }return {verdict: 'cancelled',lines: [`🚫 ${label}: this run was CANCELLED, not failed — no job REPORTED a failure.`,`Cancelled jobs: ${cancelled.join(', ')}`,finished(),- // This wording is load-bearing. The old line said "No test failed", and- // twice (#7482, #7571) that sent a reader straight to the billing+ // This distinction is load-bearing. The old line said "No test failed",+ // and twice (#7482, #7571) that sent a reader straight to the billing// dashboard while a real assertion sat unread in a job log: a job that// fails is cancelled by scripts/cancel-current-ci-run.js before its own// reporting step runs, so its conclusion is `cancelled` too and NOTHING- // in the run metadata reads `failure`. Only the logs distinguish them.- 'A cancelled conclusion does NOT mean no test failed. PortOS fail-fasts:'- + ' the job that failed is cancelled out from under its own reporting'- + ' step, so a real red build looks exactly like this. READ THE JOB LOGS'- + ' FIRST — and note that `gh run view --job <id> --log-failed` prints'- + ' NOTHING here, because no step is marked failed. Use the full'- + ' `--log` and grep for `🛑 Requested cancellation` (written only when'- + ' a job really failed), `FAIL `, or `AssertionError`; the culprit is'- + ' usually the job that completed EARLIEST.',- 'Only if no job log shows a failure: a job that hits the 6-hour limit is'+ // in the run metadata reads `failure`. That is now CHECKED rather than+ // guessed — but only when the lookup ran, so the two states say+ // different things instead of sharing the more alarming wording.+ ...(culprits+ ? ["Checked every job's STEP conclusions too, and none failed — so this"+ + ' is not the usual fail-fast cancel wearing a cancelled conclusion.']+ : ["This run's step conclusions could NOT be read, so a cancelled"+ + ' conclusion here does NOT mean no test failed: PortOS fail-fasts,'+ + ' the job that failed is cancelled out from under its own reporting'+ + ' step, and a real red build then looks exactly like this.'+ + ' READ THE JOB LOGS FIRST — and note that'+ + ' `gh run view --job <id> --log-failed` prints NOTHING here, because'+ + ' no step is marked failed. Use the full `--log` and grep for'+ + ' `🛑 Requested cancellation` (written only when a job really'+ + ' failed), `FAIL `, or `AssertionError`; the culprit is usually the'+ + ' job that completed EARLIEST.']),+ 'Otherwise: a job that hits the 6-hour limit is'+ ' recorded as `cancelled` rather than `timed_out` (check for a hang),'+ ' a newer push superseded this run (cancel-in-progress leaves a NEWER'+ ' run for the branch), or GitHub cancelled it externally — the Actions'@@ -154,6 +210,27 @@ export function summarizeGateResults(results, label = DEFAULT_LABEL, requireSucc};}+/**+ * Jobs in THIS run that carry a failed step, the gate jobs excluded.+ *+ * `null` on an unusable environment or a failed lookup, kept distinct from the+ * empty array: both keep the cancelled verdict, but only "looked and found+ * none" earns the wording that rules a fail-fast cancel out. A failed lookup+ * must never invent a failure the run may not have, nor vouch for its absence.+ *+ * @param {NodeJS.ProcessEnv} env+ * @param {typeof fetch} fetchImpl+ * @returns {Promise<Array<{name: string, steps: string[]}>|null>}+ */+async function findCulprits(env, fetchImpl) {+ const target = currentRunTargetFromEnv(env);+ const jobs = await fetchJobsWithFailedSteps(fetchImpl, target && {+ ...target,+ timeoutMs: CULPRIT_TIMEOUT_MS,+ });+ return jobs && jobs.filter(({ name }) => !GATE_JOB_NAMES.has(name));+}+/*** Print the verdict — to the step log and to the run summary — and report* whether the gate passed.@@ -162,19 +239,30 @@ export function summarizeGateResults(results, label = DEFAULT_LABEL, requireSucc* @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[]}}+ * @param {typeof fetch} [options.fetchImpl] - injectable fetch for tests+ * @returns {Promise<{verdict: string, ok: boolean, lines: string[]}>}*/-export function reportGate({+export async function reportGate({env = process.env,logger = console,writeSummary = writeStepSummary,+ fetchImpl = globalThis.fetch,} = {}) {const label = env.CI_GATE_LABEL?.trim() || DEFAULT_LABEL;- const { verdict, lines } = summarizeGateResults(- collectGateResults(env),- label,- env.CI_GATE_REQUIRE_SUCCESS === 'true',- );+ const results = collectGateResults(env);+ const requireSuccess = env.CI_GATE_REQUIRE_SUCCESS === 'true';+ const provisional = summarizeGateResults(results, label, { requireSuccess });+ // The lookup runs ONLY for the cancelled verdict. Every other one already+ // names its cause, and a gate that queried the API on every green run would+ // spend a request per build to learn nothing. Re-summarizing is a second pass+ // over a handful of strings — cheaper than threading a lazy resolver through+ // a pure function for the sake of one rare branch.+ const { verdict, lines } = provisional.verdict === 'cancelled'+ ? summarizeGateResults(results, label, {+ requireSuccess,+ culprits: await findCulprits(env, fetchImpl),+ })+ : provisional;const ok = verdict === 'pass';for (const line of lines) (ok ? logger.log : logger.error)?.call(logger, line);@@ -186,5 +274,5 @@ export function reportGate({}if (isDirectlyInvoked(import.meta.url)) {- if (!reportGate().ok) process.exitCode = 1;+ if (!(await reportGate()).ok) process.exitCode = 1;}diff --git a/scripts/ci-gate-report.test.js b/scripts/ci-gate-report.test.jsindex c4b74b56b1..3a2b92862e 100644--- a/scripts/ci-gate-report.test.js+++ b/scripts/ci-gate-report.test.js@@ -7,7 +7,7 @@ import { readFileSync } from 'fs';import { dirname, join } from 'path';import { fileURLToPath } from 'url';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { collectGateResults, reportGate, summarizeGateResults } from './ci-gate-report.js';import { workflowJobs } from './lib/workflowJobs.js';@@ -64,6 +64,7 @@ describe('summarizeGateResults', () => {expect(text).toContain('READ THE JOB LOGS FIRST');expect(text).toContain('does NOT mean no test failed');expect(text).not.toMatch(/\bNo test failed\b/);+ expect(text).toContain('could NOT be read');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@@ -98,7 +99,7 @@ describe('summarizeGateResults', () => {// the complete suite on the strength of that check.expect(summarizeGateResults(results({ gate: 'skipped' })).verdict).toBe('pass');- const strict = summarizeGateResults(results({ gate: 'skipped' }), 'Full CI Gate', true);+ const strict = summarizeGateResults(results({ gate: 'skipped' }), 'Full CI Gate', { requireSuccess: true });expect(strict.verdict).toBe('failure');expect(strict.lines).toContain('Failed jobs: gate=skipped');});@@ -115,6 +116,51 @@ describe('summarizeGateResults', () => {const summary = summarizeGateResults(results({ gate: 'cancelled' }), 'Full CI Gate');expect(summary.lines[0]).toContain('Full CI Gate');});++ it('stops sending the reader to the logs once the steps have been cleared', () => {+ // The paragraph above is the guard against the #7482 / #7571 misdiagnosis,+ // and it is still right when NOTHING checked the steps. Once the lookup HAS+ // run and found none, repeating it would send every genuine external cancel+ // hunting for a failure that really is absent — so the two states differ,+ // and neither may imply the tree is green.+ const summary = summarizeGateResults(results({ server: 'cancelled' }), 'CI Gate', { culprits: [] });++ expect(summary.verdict).toBe('cancelled');+ const text = summary.lines.join('\n');+ expect(text).toContain("Checked every job's STEP conclusions too, and none failed");+ expect(text).not.toContain('READ THE JOB LOGS FIRST');+ expect(text).not.toMatch(/\bNo test failed\b/);+ });++ it('names the culprit instead of reporting a cancel when a job has a failed step', () => {+ // The shape of every fail-fast run (7574): the failing job's own conclusion+ // is `cancelled` because the cancel beat GitHub to writing it, so this is+ // the ONLY input that can tell the reader a test actually failed.+ const summary = summarizeGateResults(+ results({ impact: 'success', server: 'cancelled', 'windows-server': 'cancelled' }),+ 'CI Gate',+ { culprits: [{ name: 'Windows server unit tests (3/3)', steps: ['Run server tests on Windows'] }] },+ );++ expect(summary.verdict).toBe('failure');+ const text = summary.lines.join('\n');+ expect(text).not.toContain('CANCELLED, not failed');+ expect(summary.lines).toContain(+ 'Failing job: Windows server unit tests (3/3) — failed step: Run server tests on Windows',+ );+ // The cancelled siblings still get named, as collateral rather than cause.+ expect(summary.lines).toContain('Cancelled jobs: server, windows-server');+ expect(text).toContain('--log-failed');+ });++ it('keeps the cancelled verdict when the lookup could not run at all', () => {+ // A genuine external cancel, or a lookup that failed. Either way it must+ // stay `cancelled`, so the run still earns its one automatic retry from+ // ci-cancel-recovery.yml.+ const summary = summarizeGateResults(results({ server: 'cancelled' }), 'CI Gate', { culprits: null });+ expect(summary.verdict).toBe('cancelled');+ expect(summary.lines.join('\n')).toContain('CANCELLED, not failed');+ });});describe('reportGate', () => {@@ -131,29 +177,29 @@ describe('reportGate', () => {};};- it('turns CI_GATE_REQUIRE_SUCCESS on for the strict gate', () => {+ it('turns CI_GATE_REQUIRE_SUCCESS on for the strict gate', async () => {const { ...sinks } = capture();- expect(reportGate({+ await expect(reportGate({env: { CI_GATE_RESULT_GATE: 'skipped', CI_GATE_REQUIRE_SUCCESS: 'true' }, ...sinks,- })).toMatchObject({ verdict: 'failure', ok: false });- expect(reportGate({ env: { CI_GATE_RESULT_GATE: 'skipped' }, ...sinks }))- .toMatchObject({ verdict: 'pass', ok: true });+ })).resolves.toMatchObject({ verdict: 'failure', ok: false });+ await expect(reportGate({ env: { CI_GATE_RESULT_GATE: 'skipped' }, ...sinks }))+ .resolves.toMatchObject({ verdict: 'pass', ok: true });});- it('writes a pass to stdout and reports ok', () => {+ it('writes a pass to stdout and reports ok', async () => {const { logged, errored, ...sinks } = capture();- const outcome = reportGate({ env: { CI_GATE_RESULT_SERVER: 'success' }, ...sinks });+ const outcome = await 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('writes a cancel to stderr AND to the run summary, and still blocks', () => {+ it('writes a cancel to stderr AND to the run summary, and still blocks', async () => {// 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({+ const outcome = await reportGate({env: { CI_GATE_RESULT_SERVER: 'cancelled' },logger: sinks.logger,writeSummary: sinks.writeSummary,@@ -168,6 +214,82 @@ describe('reportGate', () => {});});+describe('reportGate culprit lookup', () => {+ const API_ENV = {+ GITHUB_REPOSITORY: 'example/portos',+ GITHUB_RUN_ID: '123456789',+ GITHUB_TOKEN: 'ephemeral-test-token',+ CI_GATE_RESULT_SERVER: 'cancelled',+ CI_GATE_RESULT_WINDOWS_SERVER: 'cancelled',+ };+ const jobsResponse = (jobs) => ({ ok: true, status: 200, json: async () => ({ jobs }) });+ const run = (options) => {+ const errored = [];+ const summaries = [];+ return reportGate({+ env: API_ENV,+ logger: { log: () => {}, error: (line) => errored.push(line) },+ writeSummary: (markdown) => summaries.push(markdown),+ ...options,+ }).then((outcome) => ({ outcome, errored, summaries }));+ };++ it('reports a failure naming the job and step behind a cancelled run', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(jobsResponse([+ { name: 'Server tests (1/2)', conclusion: 'cancelled', steps: [{ name: 'Run server tests', conclusion: 'cancelled' }] },+ {+ name: 'Windows server unit tests (3/3)',+ conclusion: 'cancelled',+ steps: [+ { name: 'Checkout', conclusion: 'success' },+ { name: 'Run server tests on Windows', conclusion: 'failure' },+ ],+ },+ ]));++ const { outcome, errored } = await run({ fetchImpl });++ expect(outcome).toMatchObject({ verdict: 'failure', ok: false });+ expect(errored.join('\n')).toContain('Windows server unit tests (3/3) — failed step: Run server tests on Windows');+ // The gate reads THIS run, not one a workflow input could point it at.+ expect(fetchImpl).toHaveBeenCalledWith(+ 'https://api.github.com/repos/example/portos/actions/runs/123456789/jobs?per_page=100',+ expect.any(Object),+ );+ });++ it("ignores the gate jobs' own failed steps", async () => {+ // Both gates fail downstream of any red run, so naming one would send the+ // reader back to the check they are already looking at.+ const fetchImpl = vi.fn().mockResolvedValue(jobsResponse([+ { name: 'CI Gate', conclusion: 'failure', steps: [{ name: 'Require every selected job to pass', conclusion: 'failure' }] },+ { name: 'Full CI Gate', conclusion: 'failure', steps: [{ name: 'Require the aggregate gate to have passed', conclusion: 'failure' }] },+ ]));++ const { outcome, errored } = await run({ fetchImpl });++ expect(outcome).toMatchObject({ verdict: 'cancelled', ok: false });+ expect(errored.join('\n')).toContain('CANCELLED, not failed');+ });++ it('falls back to the cancelled wording when the API is unavailable', async () => {+ // A network blip must never flip a cancelled run red — the run still needs+ // its one automatic retry from ci-cancel-recovery.yml. The lookup's own+ // failure modes are pinned in lib/githubActionsApi.test.js; this is the+ // gate's side of that contract.+ const { outcome, errored } = await run({ fetchImpl: vi.fn().mockRejectedValue(new Error('network unavailable')) });+ expect(outcome).toMatchObject({ verdict: 'cancelled', ok: false });+ expect(errored.join('\n')).toContain('CANCELLED, not failed');+ });++ it('does not query the API for a verdict that already names its cause', async () => {+ const fetchImpl = vi.fn();+ await run({ env: { ...API_ENV, CI_GATE_RESULT_SERVER: 'success', CI_GATE_RESULT_WINDOWS_SERVER: 'success' }, fetchImpl });+ await run({ env: { ...API_ENV, CI_GATE_RESULT_SERVER: 'failure' }, fetchImpl });+ expect(fetchImpl).not.toHaveBeenCalled();+ });+});+describe('ci.yml gate wiring', () => {const jobs = workflowJobs(WORKFLOW);@@ -182,6 +304,22 @@ describe('ci.yml gate wiring', () => {expect(jobs[id]).toContain('sparse-checkout: scripts');});+ it.each(['gate', 'full-gate'])('gives %s the read-only grant its culprit lookup needs', (id) => {+ // Without the token the reporter silently falls back to the cancelled+ // wording, which is exactly the misleading verdict this lookup replaced.+ expect(jobs[id]).toContain('GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}');+ expect(jobs[id]).toMatch(/\n permissions:\n contents: read\n actions: read\n/);+ // Listing jobs is a read. Cancelling stays a leaf-job privilege.+ expect(jobs[id]).not.toContain('actions: write');+ });++ it('excludes exactly the gate job names the reporter filters out', () => {+ // The reporter drops these two by NAME, so a renamed gate would start+ // reporting itself as the culprit behind every cancelled run.+ expect(jobs.gate).toContain('name: CI Gate');+ expect(jobs['full-gate']).toContain('name: Full CI Gate');+ });+it('runs the full gate in strict mode and the aggregate gate not', () => {expect(jobs['full-gate']).toContain("CI_GATE_REQUIRE_SUCCESS: 'true'");expect(jobs.gate).not.toContain('CI_GATE_REQUIRE_SUCCESS');diff --git a/scripts/ci-retry-cancelled-run.js b/scripts/ci-retry-cancelled-run.jsindex 30d93b1ad0..2f7d4541df 100644--- a/scripts/ci-retry-cancelled-run.js+++ b/scripts/ci-retry-cancelled-run.js@@ -5,10 +5,10 @@** 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 (issue 7437). The same SHA passes on the next- * attempt once the queue drains, so one automatic re-dispatch clears it.+ * `Report the failure, then cancel sibling CI jobs` 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 (issue 7437). The same SHA passes+ * on the next attempt once the queue drains, so one re-dispatch clears it.** 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@@ -39,8 +39,10 @@*/import { isDirectlyInvoked } from './lib/directInvocation.js';-import { githubRequest, isSuccess, repoApiPath, trimmed } from './lib/githubActionsApi.js';-import { writeStepSummary } from './lib/githubOutput.js';+import {+ githubJson, githubRequest, isSuccess, jobFailed, repoApiPath, trimmed,+} from './lib/githubActionsApi.js';+import { safeWorkflowText, writeStepSummary } from './lib/githubOutput.js';const REQUEST_TIMEOUT_MS = 15_000;/** ~1500 jobs. A bound, not an expectation — CI runs about fifteen. */@@ -48,8 +50,6 @@ const MAX_JOB_PAGES = 15;const JOBS_PER_PAGE = 100;/** Newest-first; a successor, if one exists, is within the first few. */const SIBLING_RUNS_PER_PAGE = 5;-/** A conclusion that means something really broke, not that it was stopped. */-const FAILING_CONCLUSIONS = new Set(['failure', 'timed_out']);/*** How long to idle before re-dispatching (issue 7439).@@ -126,27 +126,12 @@ const CHECK_REASON_TEXT = {};const CHECK_REASON_FALLBACK = 'Recovery evaluated this cancelled run and did not re-dispatch it. Re-run CI manually if the cancellation was external.';-/**- * True when this job carries a real failure.- *- * The job's own conclusion is not enough. `cancel-current-ci-run.js` cancels- * the RUN from inside the failing job, and the cancel can land while that job- * is still finishing its post-steps — GitHub then records the job as- * `cancelled` even though one of its steps failed. Reading the steps too is- * what keeps this guard failing CLOSED, which is the whole point of it.- */-const jobFailed = (job) => FAILING_CONCLUSIONS.has(job?.conclusion)- || (Array.isArray(job?.steps) && job.steps.some((step) => FAILING_CONCLUSIONS.has(step?.conclusion)));-/*** A job name for a log line. The name comes from the pull request's own* workflow file, and Actions parses `::` at the start of a line as a workflow* command — so newlines and `::` never reach stdout verbatim.*/-const safeJobName = (job) => String(job?.name || 'unnamed job')- .replace(/[\r\n]+/g, ' ')- .replace(/::/g, ':')- .slice(0, 80);+const safeJobName = (job) => safeWorkflowText(job?.name, 'unnamed job');/*** Validate and normalise the run this invocation may retry.@@ -193,16 +178,8 @@ 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 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'}`);- return null;- }-}+const readJson = (fetchImpl, url, token, logger) =>+ githubJson(fetchImpl, url, token, { timeoutMs: REQUEST_TIMEOUT_MS, logger });/*** Every job of the cancelled attempt, or null when the listing is incomplete.diff --git a/scripts/lib/githubActionsApi.js b/scripts/lib/githubActionsApi.jsindex 8c9504d690..bb77e7eda5 100644--- a/scripts/lib/githubActionsApi.js+++ b/scripts/lib/githubActionsApi.js@@ -7,9 +7,13 @@* 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.+ * ZERO external dependencies — see githubOutput.js. The one internal import+ * is githubOutput's own sanitizer, so an API-sourced job or step name is safe+ * the moment it leaves here rather than at each call site.*/+import { safeWorkflowText } from './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. */@@ -115,3 +119,121 @@ export function isSuccess(response) {const status = Number(response?.status) || 0;return (status >= 200 && status < 300) || response?.ok === true;}++/**+ * The run this step is part of, plus the token to read it with — or null.+ *+ * The single derivation of "which run am I, and with what token". Both the+ * fail-fast reporter and the gate reporter need it, and this module exists+ * precisely so a hardening fix to that reasoning cannot land on one copy and+ * miss the other.+ *+ * @param {NodeJS.ProcessEnv} env+ * @returns {{token: string, repoPath: string, runId: string}|null}+ */+export function currentRunTargetFromEnv(env) {+ const runId = trimmed(env.GITHUB_RUN_ID);+ const token = trimmed(env.GITHUB_TOKEN);+ const repoPath = repoApiPath(env);++ if (!repoPath || !/^\d+$/.test(runId) || !token) return null;++ return { token, repoPath, runId };+}++/**+ * One authenticated GET, parsed. `null` for ANY transport, status, or parse+ * failure — every caller treats "could not read" as its own outcome, never as+ * an empty result.+ *+ * @param {typeof fetch} fetchImpl+ * @param {string} url+ * @param {string} token+ * @param {{timeoutMs?: number, logger?: {error?: Function}}} [options]+ * @returns {Promise<object|null>}+ */+export async function githubJson(fetchImpl, url, token, { timeoutMs, logger } = {}) {+ try {+ const response = await githubRequest(fetchImpl, url, token, { timeoutMs });+ if (!isSuccess(response)) return null;+ return await response.json();+ } catch (error) {+ logger?.error?.(`⚠️ GitHub API request failed: ${error?.message || 'network request failed'}`);+ return null;+ }+}++/**+ * A conclusion that means something really broke, not that it was stopped.+ * `cancelled` is deliberately absent — this repository cancels its own run+ * from the failing job, so a cancel is usually the CONSEQUENCE of a failure.+ */+const FAILING_CONCLUSIONS = new Set(['failure', 'timed_out']);++/**+ * The steps of one job that actually failed.+ *+ * A cancelled job KEEPS its steps' conclusions, which is the whole reason this+ * exists: `cancel-current-ci-run.js` cancels the run from inside the failing+ * job, so GitHub can record the job as `cancelled` while one of its steps is+ * `failure`. Nothing that reads only job conclusions — `gh pr checks`,+ * `gh run view --json jobs`, `gh run view --log-failed` — can see that (7574).+ */+const failedSteps = (job) => (Array.isArray(job?.steps) ? job.steps : [])+ .filter((step) => FAILING_CONCLUSIONS.has(step?.conclusion));++/** True when this job carries a real failure, at the job or the step level. */+export const jobFailed = (job) => FAILING_CONCLUSIONS.has(job?.conclusion)+ || failedSteps(job).length > 0;++/**+ * One culprit as both reporting surfaces render it. Shared so the Checks-tab+ * annotation and the gate summary — the two lines a human cross-reads — cannot+ * drift into describing the same failure differently.+ *+ * @param {{name: string, steps: string[]}} job+ * @returns {string}+ */+export const formatFailedJob = ({ name, steps }) => `${name} — failed step: ${steps.join(', ')}`;++/** CI runs about fifteen jobs; one page names them all. */+const RUN_JOBS_PER_PAGE = 100;++/**+ * Best-effort: the run's jobs that carry a failed STEP, named and sanitized.+ *+ * `null` means "could not be read" and is deliberately distinct from `[]`,+ * because the callers turn `[]` into a verdict ("nothing failed — this really+ * was a cancel") that a failed lookup must never produce.+ *+ * Names are sanitized HERE rather than at each call site: they come from a+ * workflow file and reach stdout, where Actions parses a leading `::` as a+ * command, so making that the boundary's job is what keeps a future consumer+ * from forgetting it.+ *+ * Deliberately single-page and deliberately NOT attempt-scoped: both callers+ * are diagnostics that run inside the run they are describing, where an+ * incomplete answer is worth more than a slow one. The retry guard in+ * `ci-retry-cancelled-run.js` needs the opposite trade and keeps its own+ * paginated, fail-closed listing.+ *+ * @param {typeof fetch} fetchImpl+ * @param {{repoPath: string, runId: string, token: string, timeoutMs?: number}} [target]+ * @returns {Promise<Array<{name: string, steps: string[]}>|null>}+ */+export async function fetchJobsWithFailedSteps(fetchImpl, target) {+ const { repoPath, runId, token, timeoutMs } = target || {};+ if (typeof fetchImpl !== 'function' || !repoPath || !/^\d+$/.test(String(runId)) || !token) return null;+ const url = `${repoPath}/actions/runs/${runId}/jobs?per_page=${RUN_JOBS_PER_PAGE}`;+ const body = await githubJson(fetchImpl, url, token, { timeoutMs });+ if (!Array.isArray(body?.jobs)) return null;+ return body.jobs.flatMap((job) => {+ const failed = failedSteps(job);+ return failed.length+ ? [{+ name: safeWorkflowText(job?.name, 'unnamed job'),+ steps: failed.map((step) => safeWorkflowText(step?.name, 'unnamed step')),+ }]+ : [];+ });+}diff --git a/scripts/lib/githubActionsApi.test.js b/scripts/lib/githubActionsApi.test.jsindex 805c97ed98..9d6462823a 100644--- a/scripts/lib/githubActionsApi.test.js+++ b/scripts/lib/githubActionsApi.test.js@@ -5,7 +5,9 @@*/import { describe, expect, it, vi } from 'vitest';-import { githubRequest, isSuccess, repoApiPath, resolveApiBase } from './githubActionsApi.js';+import {+ fetchJobsWithFailedSteps, githubRequest, isSuccess, repoApiPath, resolveApiBase,+} from './githubActionsApi.js';describe('resolveApiBase', () => {it('defaults to the public API when GITHUB_API_URL is absent', () => {@@ -110,3 +112,50 @@ describe('isSuccess', () => {expect(isSuccess(null)).toBe(false);});});++describe('fetchJobsWithFailedSteps', () => {+ const TARGET = {+ repoPath: 'https://api.github.com/repos/example/portos',+ runId: '123456789',+ token: 'ephemeral-test-token',+ };+ const jobs = (value) => vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => value });++ it('names the failed steps of a job GitHub recorded as cancelled', () => {+ // The fail-fast cancel lands before the job's `failure` conclusion is+ // written, so the step conclusions are the only surviving evidence (7574).+ return expect(fetchJobsWithFailedSteps(jobs({+ jobs: [+ { name: 'Server tests (1/2)', conclusion: 'cancelled', steps: [{ name: 'Run', conclusion: 'cancelled' }] },+ {+ name: 'Windows server unit tests (3/3)',+ conclusion: 'cancelled',+ steps: [{ name: 'Checkout', conclusion: 'success' }, { name: 'Run tests', conclusion: 'failure' }],+ },+ ],+ }), TARGET)).resolves.toEqual([+ { name: 'Windows server unit tests (3/3)', steps: ['Run tests'] },+ ]);+ });++ it('separates "nothing failed" from "could not look"', async () => {+ // Both callers turn a non-empty list into a red verdict and `[]` into a+ // cancelled one. Collapsing null into `[]` would be invisible there and+ // would silently re-hide the failure this lookup exists to surface.+ await expect(fetchJobsWithFailedSteps(jobs({ jobs: [] }), TARGET)).resolves.toEqual([]);++ for (const fetchImpl of [+ vi.fn().mockResolvedValue({ ok: false, status: 403 }),+ vi.fn().mockRejectedValue(new Error('network unavailable')),+ vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => ({}) }),+ undefined,+ ]) {+ await expect(fetchJobsWithFailedSteps(fetchImpl, TARGET)).resolves.toBeNull();+ }++ const unused = jobs({ jobs: [] });+ await expect(fetchJobsWithFailedSteps(unused, { ...TARGET, token: '' })).resolves.toBeNull();+ await expect(fetchJobsWithFailedSteps(unused, { ...TARGET, runId: 'not-a-run' })).resolves.toBeNull();+ expect(unused).not.toHaveBeenCalled();+ });+});diff --git a/scripts/lib/githubOutput.js b/scripts/lib/githubOutput.jsindex 75eef33ad6..bdf5cadaf5 100644--- a/scripts/lib/githubOutput.js+++ b/scripts/lib/githubOutput.js@@ -62,3 +62,54 @@ export function writeStepSummary(markdown, env = process.env) {if (!path) return;appendFileSync(path, `${markdown}\n`);}++/**+ * A workflow-sourced name (a job's, a step's) rendered into a log line.+ *+ * Actions parses a line beginning `::` as a workflow command, and the name+ * comes from a workflow file, so a newline or a `::` would let a name forge a+ * command instead of appearing in one. Capped because these land in an+ * annotation title, not in a report.+ *+ * @param {unknown} value+ * @param {string} [fallback] - used when the value is empty+ * @returns {string}+ */+export function safeWorkflowText(value, fallback = '') {+ return String(value || fallback)+ .replace(/[\r\n]+/g, ' ')+ .replace(/::/g, ':')+ .slice(0, 80);+}++/**+ * Escaping for the two halves of a workflow command, which differ: a property+ * value is delimited by `:` and `,` as well, so those need encoding there and+ * must NOT be encoded in the message (where they are ordinary punctuation).+ * `%` goes first, or it would re-encode the escapes that follow it.+ */+const escapeCommandData = (value) => String(value)+ .replace(/%/g, '%25')+ .replace(/\r/g, '%0D')+ .replace(/\n/g, '%0A');+const escapeCommandProperty = (value) => escapeCommandData(value)+ .replace(/:/g, '%3A')+ .replace(/,/g, '%2C');++/**+ * An `::error::` workflow annotation line, ready to print to stdout.+ *+ * Annotations are the one diagnostic surface that survives the run being+ * cancelled out from under the job that wrote it: Actions records them the+ * moment the line is printed, and renders them at the top of the pull+ * request's Checks tab. That is why fail-fast reporting uses one — a job's+ * step conclusions are readable over the API, but only by somebody who+ * already knows to look (issue 7574).+ *+ * @param {string} title - short heading; shown in the Checks tab+ * @param {string} message - the detail line+ * @returns {string}+ */+export function formatErrorAnnotation(title, message) {+ return `::error title=${escapeCommandProperty(title)}::${escapeCommandData(message)}`;+}diff --git a/scripts/lib/githubOutput.test.js b/scripts/lib/githubOutput.test.jsindex b250c7de38..ee789a6f20 100644--- a/scripts/lib/githubOutput.test.js+++ b/scripts/lib/githubOutput.test.js@@ -4,7 +4,9 @@ import { join } from 'path';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { writeStepEnv, writeStepOutput, writeStepSummary } from './githubOutput.js';+import {+ formatErrorAnnotation, writeStepEnv, writeStepOutput, writeStepSummary,+} from './githubOutput.js';describe('writeStepOutput', () => {let outputPath;@@ -113,3 +115,18 @@ describe('writeStepSummary', () => {expect(readFileSync(summaryPath, 'utf8')).toBe('');});});++describe('formatErrorAnnotation', () => {+ it('escapes the title and the message by their different rules', () => {+ // A `:` or `,` in a PROPERTY ends it, so both must be encoded there — and+ // must NOT be in the message, where they are ordinary punctuation.+ expect(formatErrorAnnotation('CI failed: server (1/2)', 'Run tests, then build'))+ .toBe('::error title=CI failed%3A server (1/2)::Run tests, then build');+ });++ it('encodes a newline rather than letting it end the annotation early', () => {+ expect(formatErrorAnnotation('t', 'line one\nline two')).toBe('::error title=t::line one%0Aline two');+ // `%` first, or the escapes above would be re-escaped into nonsense.+ expect(formatErrorAnnotation('t', '50% slower')).toBe('::error title=t::50%25 slower');+ });+});diff --git a/scripts/run-ci-tests.test.js b/scripts/run-ci-tests.test.jsindex c360ea181f..ff4dd4c205 100644--- a/scripts/run-ci-tests.test.js+++ b/scripts/run-ci-tests.test.js@@ -63,7 +63,11 @@ describe('ci.yml shard wiring', () => {expect(jobs.lint).toBeTruthy();expect(jobs.lint).toContain('run: node scripts/run-ci-lint.js');expect(jobs.lint).not.toContain('strategy:');- expect(jobs.lint).not.toContain('matrix.shard');+ // Exactly one `matrix.shard`: the shared fail-fast step's CI_FAILED_SHARD,+ // which renders empty on an unsharded job. A second occurrence — a cache+ // key, a step name, above all a shard-pinned `if:` — is the regression.+ expect(jobs.lint.match(/matrix\.shard/g)).toHaveLength(1);+ expect(jobs.lint).toContain('CI_FAILED_SHARD: ${{ matrix.shard }}');// A scoped plan emits `client_shards: [1]`, so a later-shard pin would skip// lint on every impact-scoped pull request. Its gate is the plan's lint mode.expect(jobs.lint).toContain("if: needs.impact.outputs.lint_mode != 'skip'");