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
explain a run-wide CI cancel on the pull request itself, as a neutral check run (#7438)
[._.]/ Adam Eivy5321643aac1a
diff --git a/.github/workflows/ci-cancel-recovery.yml b/.github/workflows/ci-cancel-recovery.ymlindex 0e9caddc1d..2ab36df201 100644--- a/.github/workflows/ci-cancel-recovery.yml+++ b/.github/workflows/ci-cancel-recovery.yml@@ -11,7 +11,8 @@# pull request's head. The only PR-derived values it touches are the run# metadata passed as environment variables below, and the script uses them as# validated numbers and one encoded query parameter — never as a path, an-# argument, or shell input.+# argument, or shell input. The check run it publishes (#7438) renders fixed+# reason codes only, never the branch name or any other payload text.name: CI cancel recoveryon:@@ -22,6 +23,9 @@ on:permissions:contents: readactions: write+ # Publishing the verdict back onto the pull request as a check run (#7438).+ # The check is ALWAYS `neutral`, so this grant explains a gate, never adds one.+ checks: write# One recovery evaluation per run. Never `cancel-in-progress`: cancelling the# thing that recovers from cancellations is how this whole class of bug starts.diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.mdindex 52b53e12fb..2c330919a7 100644--- a/docs/GITHUB_ACTIONS.md+++ b/docs/GITHUB_ACTIONS.md@@ -685,8 +685,27 @@ fail-fast above and is not on the table.always()` on the gate defeats an upstream failure, not a cancellation of thewhole run — so in the external-cancel case the gate is cancelled too and neverprints 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.+step summary records which guard applied.++That summary lives on the recovery run, which nobody finds from the pull+request, so the workflow also **publishes the verdict back onto the cancelled+head SHA as a check run** named `CI cancel recovery` (issue #7438). It carries+the same fixed reason code the step summary renders — `superseded`,+`job-failed`, `re-dispatched`, `retry-budget-exhausted`, `run-state-moved-on`,+or one of the `*-unavailable` lookup failures — plus one sentence saying what+to do about it.++The check's conclusion is **always `neutral`, and that is load-bearing**.+Branch protection requires `CI Gate` alone, so a `failure` here would block a+merge the repository allows; and `success` would read as a passing gate —+PortOS's own auto-merge watcher (`server/services/prWatcher.js`) counts+`NEUTRAL` as green. Neutral is the only conclusion that stays informational to+a human and to that watcher alike. Publishing is best-effort for the same+reason the retry is: a recovery job must never turn red on top of an+already-cancelled run, so a rejected or failed publish is logged and swallowed+and the job still exits 0. The only extra grant this needs is `checks: write`;+a `contents:`/`pull-requests: write` token on a `workflow_run` workflow is what+would turn an informational job into a push surface.One known limit, filed: a retry re-runs the whole suite — Windows shardsincluded — so if the cause is the spending limit then recovery spends more of@@ -694,9 +713,10 @@ it. Reducing the billable minutes of a full run is the complementary root-causelever (#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-values it touches are validated run ids and one URL-encoded branch name.+**default branch's** copy of itself with writable `actions` and `checks`+tokens, and never checks out, installs, or executes the pull request's head.+The only PR-derived values it touches are validated run ids and one+URL-encoded branch name.Reader-facing symptoms, the `gh` commands that tell an external cancel from asupersession, and the account-billing check that confirms the upstream causediff --git a/scripts/ci-retry-cancelled-run.js b/scripts/ci-retry-cancelled-run.jsindex cdbcfdc625..30d93b1ad0 100644--- a/scripts/ci-retry-cancelled-run.js+++ b/scripts/ci-retry-cancelled-run.js@@ -89,6 +89,43 @@ export const MAX_RUNTIME_MS = RETRY_DELAY_MS/** Real elapsed time. Injected in tests so no suite ever sleeps. */const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });+/**+ * The check run's name — stable, so every cancelled run reports under one+ * heading in the PR's Checks tab rather than a new name each time.+ */+const RECOVERY_CHECK_NAME = 'CI cancel recovery';+/**+ * ALWAYS `neutral`, never `failure`/`success`. This check EXPLAINS the gate; it+ * must never become a second one. `failure` would block a merge that branch+ * protection — which requires `CI Gate` alone — allows, and `success` would read+ * as a passing gate. PortOS's own auto-merge watcher (server/services/prWatcher.js)+ * already counts NEUTRAL as green, so neutral is the one conclusion that stays+ * purely informational to a human reader and to that watcher alike.+ */+const RECOVERY_CHECK_CONCLUSION = 'neutral';+/** A check run is created against a commit, so the sha has to be a real one. */+const COMMIT_SHA_PATTERN = /^[0-9a-f]{40}$/i;++/**+ * One sentence per reason code, for the PR reader looking at a bare red gate.+ *+ * Keyed by the SAME fixed reason codes the step summary renders, so the two+ * surfaces cannot drift. Fixed prose only — never the branch name or any other+ * payload text, for the reason `safeJobName` exists.+ */+const CHECK_REASON_TEXT = {+ 're-dispatched': 'This run was cancelled with no successor run and no failing job, so CI was re-dispatched automatically — once. Watch the new run for the real result.',+ superseded: 'This run was cancelled because a newer CI run started for the same pull request. That newer run carries the real result, so this one was deliberately not retried.',+ 'job-failed': 'This run was cancelled by CI itself after a job genuinely failed, which is why the run reads cancelled rather than failure. That is a real red, not queue contention, so it was not retried.',+ 'retry-budget-exhausted': 'This run is already a retry attempt, and recovery re-dispatches a run at most once. Re-run it manually if it was cancelled externally again.',+ 'run-state-moved-on': 'The run changed state after the cancellation event — it has already been re-run, or is no longer a completed cancellation — so the one-retry budget was left unspent.',+ 'jobs-unavailable': "Recovery could not list this run's jobs, so it could not rule out a real job failure and did not retry. Re-run CI manually if the cancellation was external.",+ 'run-state-unavailable': "Recovery could not read this run's current state, so it did not risk spending the one-retry budget on a stale reading. Re-run CI manually if the cancellation was external.",+ 'sibling-runs-unavailable': "Recovery could not list the pull request's other runs, so it could not tell an external cancel from a supersession and did not retry. Re-run CI manually if the cancellation was external.",+ 'rerun-rejected': 'Recovery tried to re-dispatch this run and GitHub rejected the request. Re-run CI manually.',+};+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.*@@ -301,6 +338,53 @@ async function evaluateApiGuards(fetchImpl, target, logger) {return null;}+/**+ * Publish the verdict back onto the pull request as a NEUTRAL check run.+ *+ * This is the only layer that can explain a run-wide cancel (#7438). `if:+ * always()` on the CI gate defeats an upstream job failure, not a cancellation+ * of the whole run — when GitHub cancels the run externally the gate is+ * cancelled with it and prints nothing, so the PR shows a bare red `CI Gate`+ * and the explanation exists only on a separate workflow run nobody finds.+ *+ * BEST-EFFORT, always. A recovery job must never turn red on top of an already+ * cancelled run, so every failure here is logged and swallowed — the step+ * summary is still written and the process still exits 0.+ */+async function publishRecoveryCheck(fetchImpl, target, result, logger) {+ if (!COMMIT_SHA_PATTERN.test(target.headSha)) {+ logger?.error?.('⚠️ CI cancel recovery: no usable head sha, so no explanatory check run was published');+ return;+ }+ const reason = result.reason || 're-dispatched';+ const response = await request(fetchImpl, `${target.repoPath}/check-runs`, target.token, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ name: RECOVERY_CHECK_NAME,+ head_sha: target.headSha,+ status: 'completed',+ conclusion: RECOVERY_CHECK_CONCLUSION,+ output: {+ title: `${result.outcome}: ${reason}`,+ // The same fixed reason code the step summary renders, plus the+ // sentence that makes it actionable without opening another run.+ summary: `CI run ${target.runId} ended \`cancelled\`.\n\n`+ + `- outcome: \`${result.outcome}\`\n`+ + `- reason: \`${reason}\`\n\n`+ + `${CHECK_REASON_TEXT[reason] || CHECK_REASON_FALLBACK}\n\n`+ + 'This check is informational and always neutral — it never blocks a merge.',+ },+ }),+ }).catch((error) => {+ logger?.error?.(`⚠️ CI cancel recovery: could not publish the explanatory check run: ${error?.message || 'network request failed'}`);+ return null;+ });+ // A thrown request already logged its own reason above.+ if (!response || isSuccess(response)) return;+ logger?.error?.(`⚠️ CI cancel recovery: GitHub rejected the explanatory check run with ${Number(response.status) || 'an unknown status'}`);+}+/*** Decide whether the cancelled run deserves one re-dispatch, and do it.*@@ -331,14 +415,21 @@ export async function retryCancelledCiRun({// they say whether an outcome was reached before or after the wait, and how// long that wait was, so a later tuning pass can read its own baseline// instead of guessing at summaries written under a since-changed constant.+ //+ // `checkTarget` stays null until the run is known to be a cancelled+ // pull-request run, because those are the only PRs with a gate to explain: a+ // run that concluded normally would get an unprompted check on a green PR,+ // and a non-PR run has no pull request to annotate at all.let phase = 'before-wait';- const done = (level, message, result) => {+ let checkTarget = null;+ const done = async (level, message, result) => {logger[level]?.(message);writeSummary(`### CI cancel recovery: ${result.outcome}\n\n`+ `- run: ${runLabel}\n`+ `- reason: ${result.reason || 're-dispatched'}\n`+ `- phase: ${phase}\n`+ `- delay: ${Math.round(delayMs / 1000)}s`, env);+ if (checkTarget) await publishRecoveryCheck(fetchImpl, checkTarget, result, logger);return { ...result, phase };};@@ -360,6 +451,11 @@ export async function retryCancelledCiRun({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' });}++ // From here on the run IS a cancelled pull-request run, so every remaining+ // exit — retried, skipped, or a lookup that failed, before or after the+ // wait — is published back onto the PR by `done`.+ checkTarget = target;if (target.runAttempt !== 1) {return done('log', `ℹ️ CI retry skipped: run ${target.runId} is already attempt ${target.runAttempt} — one retry per run`,{ outcome: 'skipped', reason: 'retry-budget-exhausted' });diff --git a/scripts/ci-retry-cancelled-run.test.js b/scripts/ci-retry-cancelled-run.test.jsindex 390732427d..035c46e771 100644--- a/scripts/ci-retry-cancelled-run.test.js+++ b/scripts/ci-retry-cancelled-run.test.js@@ -46,13 +46,16 @@ const json = (body) => ({ ok: true, status: 200, json: async () => body });* A fetch stub routed by URL shape. `jobs`/`runs` default to the clean* external-cancel case so each test overrides only what it is about.*/-function stubFetch({ jobs = [], runs = [], rerunStatus = 201, live } = {}) {+function stubFetch({ jobs = [], runs = [], rerunStatus = 201, checkStatus = 201, jobsStatus = 200, live } = {}) {const calls = [];const impl = vi.fn(async (url, init = {}) => {- calls.push({ url, method: init.method || 'GET' });+ calls.push({ url, method: init.method || 'GET', body: init.body });// The ATTEMPT-scoped path, deliberately: /runs/{id}/jobs returns the// LATEST attempt's jobs, which is the wrong set after a human re-run.- if (url.includes('/attempts/1/jobs?')) return json({ total_count: jobs.length, jobs });+ if (url.includes('/attempts/1/jobs?')) {+ if (jobsStatus >= 300) return { ok: false, status: jobsStatus };+ return json({ total_count: jobs.length, jobs });+ }if (url.includes('/runs?')) {return json({total_count: runs.length,@@ -60,12 +63,22 @@ function stubFetch({ jobs = [], runs = [], rerunStatus = 201, live } = {}) {});}if (url.endsWith('/rerun')) return { ok: rerunStatus < 300, status: rerunStatus };+ if (url.endsWith('/check-runs')) return { ok: checkStatus < 300, status: checkStatus };if (/\/actions\/runs\/\d+$/.test(url)) {return json({ run_attempt: 1, status: 'completed', conclusion: 'cancelled', ...live });}throw new Error(`unexpected url ${url}`);});- return { impl, calls, rerunRequested: () => calls.some((c) => c.url.endsWith('/rerun')) };+ return {+ impl,+ calls,+ rerunRequested: () => calls.some((c) => c.url.endsWith('/rerun')),+ /** The parsed check-run body, or null when none was published. */+ publishedCheck: () => {+ const call = calls.find((c) => c.url.endsWith('/check-runs'));+ return call ? JSON.parse(call.body) : null;+ },+ };}const silent = { log: () => {}, error: () => {} };@@ -115,7 +128,9 @@ describe('retryCancelledCiRun guards', () => {const fetchStub = stubFetch();await expect(run({ ...BASE_ENV, CI_RUN_ATTEMPT: '2' }, fetchStub)).resolves.toMatchObject({ outcome: 'skipped', reason: 'retry-budget-exhausted' });- expect(fetchStub.impl).not.toHaveBeenCalled();+ // The budget guard short-circuits before every lookup. The only call it may+ // make is the neutral check that explains the skip on the pull request.+ expect(fetchStub.calls.map((c) => c.url).filter((url) => !url.endsWith('/check-runs'))).toEqual([]);});it('never retries a legitimate cancel-in-progress supersession', async () => {@@ -460,6 +475,96 @@ describe('the wait before re-dispatching', () => {});});+describe('the neutral check run published back onto the pull request', () => {+ // `if: always()` on the CI gate defeats an upstream job failure, not a+ // cancellation of the whole run, so an externally cancelled run leaves a bare+ // red `CI Gate` with no message. This recovery run is a separate run and+ // survives, which makes it the only layer that can explain one (#7438).++ it('names the reason the cancelled run was not retried, on the cancelled head sha', async () => {+ const fetchStub = stubFetch({ runs: [{ id: 5000, run_number: 901 }] });+ await run(BASE_ENV, fetchStub);++ const check = fetchStub.publishedCheck();+ expect(check).toMatchObject({+ name: 'CI cancel recovery',+ head_sha: BASE_ENV.CI_RUN_HEAD_SHA,+ status: 'completed',+ conclusion: 'neutral',+ });+ // The same fixed reason code the step summary renders, so a reader of+ // either surface sees the same verdict.+ expect(check.output.summary).toContain('reason: `superseded`');+ expect(check.output.summary).toContain('newer CI run started');+ });++ it.each([+ ['a re-dispatch', {}, {}],+ ['a supersession', { runs: [{ id: 5000, run_number: 901 }] }, {}],+ ['a real job failure', { jobs: [{ name: 'Server tests', conclusion: 'failure' }] }, {}],+ ['an exhausted retry budget', {}, { CI_RUN_ATTEMPT: '2' }],+ ['a rejected re-dispatch', { rerunStatus: 403 }, {}],+ ['an unreadable job listing', { jobsStatus: 502 }, {}],+ ])('stays neutral for %s — it explains the gate, it never becomes a second one', async (_label, options, envOverride) => {+ // `failure` would block a merge that branch protection (which requires+ // `CI Gate` alone) allows; `success` would read as a passing gate, and+ // server/services/prWatcher.js already counts NEUTRAL as green.+ const fetchStub = stubFetch(options);+ await run({ ...BASE_ENV, ...envOverride }, fetchStub);++ expect(fetchStub.publishedCheck()?.conclusion).toBe('neutral');+ });++ it('never echoes the attacker-controlled branch name into the check', async () => {+ // The check body is rendered from fixed reason codes only, for the same+ // reason `safeJobName` exists — a fork PR names its own branch.+ const fetchStub = stubFetch({ runs: [{ id: 5000, run_number: 901 }] });+ await run({ ...BASE_ENV, CI_RUN_HEAD_BRANCH: 'evil <img src=x>' }, fetchStub);++ expect(JSON.stringify(fetchStub.publishedCheck())).not.toContain('evil');+ });++ it.each([+ ['a run that concluded normally', { CI_RUN_CONCLUSION: 'success' }],+ ['a nightly or dispatched run', { CI_RUN_EVENT: 'schedule' }],+ ])('publishes nothing for %s', async (_label, override) => {+ // A green PR must not collect an unprompted check, and a non-PR run has no+ // pull request to annotate at all.+ const fetchStub = stubFetch();+ await run({ ...BASE_ENV, ...override }, fetchStub);++ expect(fetchStub.publishedCheck()).toBeNull();+ });++ it('publishes nothing when the head sha is not a commit sha', async () => {+ const fetchStub = stubFetch({ runs: [{ id: 5000, run_number: 901 }] });+ await run({ ...BASE_ENV, CI_RUN_HEAD_SHA: 'not-a-sha' }, fetchStub);++ expect(fetchStub.publishedCheck()).toBeNull();+ });++ it.each([+ ['GitHub rejects it', { checkStatus: 422 }],+ ['the request never completes', { checkStatus: 'throw' }],+ ])('swallows a publishing failure when %s — the verdict still stands', async (_label, options) => {+ // Best-effort, always: the recovery job must never turn red on top of an+ // already-cancelled run.+ const fetchStub = options.checkStatus === 'throw'+ ? {+ impl: vi.fn(async (url) => {+ if (url.endsWith('/check-runs')) throw new Error('socket hang up');+ if (url.includes('/jobs?')) return json({ total_count: 0, jobs: [] });+ if (url.includes('/runs?')) return json({ workflow_runs: [{ id: 5000, run_number: 901 }] });+ return json({ run_attempt: 1, status: 'completed', conclusion: 'cancelled' });+ }),+ }+ : stubFetch({ ...options, runs: [{ id: 5000, run_number: 901 }] });++ await expect(invoke({ env: BASE_ENV, fetchImpl: fetchStub.impl }))+ .resolves.toMatchObject({ outcome: 'skipped', reason: 'superseded' });+ });+});+describe('ci-cancel-recovery.yml wiring', () => {const jobs = workflowJobs(RECOVERY_WORKFLOW);@@ -527,8 +632,13 @@ describe('ci-cancel-recovery.yml wiring', () => {expect(jobs.retry).not.toContain('actions/setup-node');});- it('grants write only to actions, and never cancels its own recovery', () => {+ it('grants write only to actions and checks, and never cancels its own recovery', () => {expect(RECOVERY_WORKFLOW).toMatch(/permissions:\n {2}contents: read\n {2}actions: write\n/);+ // The check-run publisher needs this grant, and nothing wider: a+ // `contents: write` or `pull-requests: write` token on a workflow_run+ // workflow is what turns an informational job into a push surface.+ expect(RECOVERY_WORKFLOW).toMatch(/^ {2}checks: write$/m);+ expect(RECOVERY_WORKFLOW).not.toMatch(/^ {2}(contents|packages|id-token|pull-requests|issues|deployments): write$/m);expect(RECOVERY_WORKFLOW).toContain('cancel-in-progress: false');});});diff --git a/scripts/lib/githubActionsApi.js b/scripts/lib/githubActionsApi.jsindex c30d6b9cc4..f34601566f 100644--- a/scripts/lib/githubActionsApi.js+++ b/scripts/lib/githubActionsApi.js@@ -71,16 +71,22 @@ export function repoApiPath(env) {/*** One authenticated Actions API call with the standard headers and a timeout.*+ * A caller may add headers (a POST body needs its `Content-Type`), but they are+ * spread FIRST so the three fixed ones always win: this helper decides which+ * host the token is sent to, and a caller that could rewrite `Authorization`+ * would take that decision back out of here.+ ** @param {typeof fetch} fetchImpl* @param {string} url* @param {string} token- * @param {{method?: string, timeoutMs?: number}} [options]+ * @param {{method?: string, timeoutMs?: number, headers?: Record<string, string>}} [options]* @returns {Promise<Response>}*/-export function githubRequest(fetchImpl, url, token, { timeoutMs = DEFAULT_TIMEOUT_MS, ...init } = {}) {+export function githubRequest(fetchImpl, url, token, { timeoutMs = DEFAULT_TIMEOUT_MS, headers, ...init } = {}) {return fetchImpl(url, {...init,headers: {+ ...headers,Accept: 'application/vnd.github+json',Authorization: `Bearer ${token}`,'X-GitHub-Api-Version': GITHUB_API_VERSION,diff --git a/scripts/lib/githubActionsApi.test.js b/scripts/lib/githubActionsApi.test.jsindex 2cc73c52cc..2facb59fb1 100644--- a/scripts/lib/githubActionsApi.test.js+++ b/scripts/lib/githubActionsApi.test.js@@ -70,6 +70,23 @@ describe('githubRequest', () => {// timeoutMs configures the signal; it must not leak into fetch's init.expect(fetchImpl.mock.calls[0][1]).not.toHaveProperty('timeoutMs');});++ it('lets a caller add a header but never rewrite the three fixed ones', async () => {+ // A POST body needs its Content-Type; `Authorization` decides which host+ // the step-scoped token is sent to, so it must not be caller-settable.+ const fetchImpl = vi.fn().mockResolvedValue({ ok: true, status: 201 });+ await githubRequest(fetchImpl, 'https://api.github.com/x', 'token-value', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer stolen' },+ });++ expect(fetchImpl.mock.calls[0][1].headers).toEqual({+ 'Content-Type': 'application/json',+ Accept: 'application/vnd.github+json',+ Authorization: 'Bearer token-value',+ 'X-GitHub-Api-Version': '2022-11-28',+ });+ });});describe('isSuccess', () => {