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

fix: cancel sibling CI jobs after first required failure (#5519)

[._.]/ Adam Eivyc6111998eca5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 50b66f5866..5ff90ac507 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -112,6 +112,9 @@ jobs:
needs: impact
if: needs.impact.outputs.server_mode != 'skip'
runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ actions: write
steps:
- uses: actions/checkout@v7
with:
@@ -251,11 +254,20 @@ jobs:
if: needs.impact.outputs.smoke == 'true'
run: npm run smoke
+ - name: Cancel sibling CI jobs after failure
+ if: failure()
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: node scripts/cancel-current-ci-run.js
+
client:
name: Client tests and build
needs: impact
if: needs.impact.outputs.client_mode != 'skip' || needs.impact.outputs.build == 'true' || needs.impact.outputs.lint_mode != 'skip'
runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ actions: write
steps:
- uses: actions/checkout@v7
with:
@@ -306,11 +318,20 @@ jobs:
if: needs.impact.outputs.build == 'true'
run: npm run build --prefix client
+ - name: Cancel sibling CI jobs after failure
+ if: failure()
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: node scripts/cancel-current-ci-run.js
+
database:
name: DB tests
needs: impact
if: needs.impact.outputs.db == 'true'
runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ actions: write
services:
postgres:
image: pgvector/pgvector:pg17
@@ -438,11 +459,20 @@ jobs:
env:
PGDATABASE: portos_test
+ - name: Cancel sibling CI jobs after failure
+ if: failure()
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: node scripts/cancel-current-ci-run.js
+
windows-server:
name: Windows server unit tests
needs: impact
if: needs.impact.outputs.windows == 'true'
runs-on: windows-latest
+ permissions:
+ contents: read
+ actions: write
steps:
- uses: actions/checkout@v7
with:
@@ -555,6 +585,12 @@ jobs:
PGPASSWORD: portos
run: node scripts/run-ci-tests.js server
+ - name: Cancel sibling CI jobs after failure
+ if: failure()
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: node scripts/cancel-current-ci-run.js
+
gate:
name: CI Gate
if: always()
diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.md
index 6edc331102..91711d4fdf 100644
--- a/docs/GITHUB_ACTIONS.md
+++ b/docs/GITHUB_ACTIONS.md
@@ -260,6 +260,33 @@ green PRs, and the `main` → `release` PR catches it before a release ships.
Changes to CI/test configuration also force the full suite on their own PR.
`[skip ci]` remains honored for push events only; PR CI always runs.
+### Fail-fast sibling cancellation
+
+Each selected leaf job (`server`, `client`, `database`, and
+`windows-server`) ends with an `if: failure()` step that asks GitHub to cancel
+the current workflow run. The request uses the repository-owned
+`scripts/cancel-current-ci-run.js` helper and the standard workflow-run cancel
+endpoint. The helper accepts no repository or run arguments: it validates and
+uses only `GITHUB_REPOSITORY` and `GITHUB_RUN_ID` supplied by Actions, with the
+step-scoped `GITHUB_TOKEN`.
+
+The leaf jobs request only `contents: read` and `actions: write`. The token is
+present in the environment only for the cancellation step, and no third-party
+action or long-lived secret is involved. The failing test/build step runs
+before cancellation, so its annotations and logs remain the evidence for the
+failure. A successful cancellation returns `202`; a `409` means the run is
+already terminal and is treated as a no-op.
+
+Cancellation is deliberately best-effort. Fork pull requests and other
+read-only-token runs may receive a permission failure, and transient API or
+network failures are also possible. The helper logs the unavailable
+cancellation and exits normally, preserving the original failed step and its
+failed job result. `CI Gate` still allows only `success` or `skipped` results;
+failed or canceled leaf jobs therefore cannot satisfy the required aggregate
+context. The target is for siblings to become canceled within 30 seconds of
+the first failing job completing, while the existing workflow-level
+concurrency cancellation continues to handle newer runs independently.
+
### Impact-planner safety rules
- A directory feature such as `server/services/sprites/` selects tests carrying
diff --git a/scripts/cancel-current-ci-run.js b/scripts/cancel-current-ci-run.js
new file mode 100644
index 0000000000..8e2b6e675c
--- /dev/null
+++ b/scripts/cancel-current-ci-run.js
@@ -0,0 +1,98 @@
+#!/usr/bin/env node
+
+/**
+ * Best-effort cancellation for 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.
+ */
+
+import { isDirectlyInvoked } from './lib/directInvocation.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 token = typeof env.GITHUB_TOKEN === 'string' ? env.GITHUB_TOKEN.trim() : '';
+
+ if (!/^[^/\s]+\/[^/\s]+$/.test(repository) || !/^\d+$/.test(runId) || !token) {
+ return null;
+ }
+
+ const [owner, repo] = repository.split('/');
+ return {
+ token,
+ url: `${GITHUB_API_BASE}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/actions/runs/${runId}/cancel`,
+ };
+}
+
+/**
+ * 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.
+ * @returns {Promise<{outcome: string, status?: number, reason?: string}>}
+ */
+export async function cancelCurrentCiRun({
+ env = process.env,
+ fetchImpl = globalThis.fetch,
+ logger = console,
+} = {}) {
+ const target = targetFromEnv(env);
+ if (!target) {
+ logger.error?.('⚠️ CI run cancellation skipped: required GitHub Actions environment is unavailable');
+ return { outcome: 'skipped', reason: 'invalid-environment' };
+ }
+
+ if (typeof fetchImpl !== 'function') {
+ logger.error?.('⚠️ CI run cancellation unavailable: fetch is not available');
+ return { outcome: 'unavailable', reason: 'fetch-unavailable' };
+ }
+
+ try {
+ const response = await fetchImpl(target.url, {
+ 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),
+ });
+ const status = Number(response?.status) || 0;
+
+ if ((status >= 200 && status < 300) || response?.ok === true) {
+ logger.log?.('🛑 Requested cancellation of the current CI run');
+ return { outcome: 'requested', status };
+ }
+
+ if (status === 409) {
+ logger.log?.('ℹ️ Current CI run is already terminal; sibling cancellation was unnecessary');
+ return { outcome: 'already-terminal', status };
+ }
+
+ logger.error?.(`⚠️ Could not cancel the current CI run: GitHub API returned ${status || 'an unknown status'}`);
+ return { outcome: 'unavailable', status };
+ } catch (error) {
+ logger.error?.(`⚠️ Could not cancel the current CI run: ${error?.message || 'network request failed'}`);
+ return { outcome: 'unavailable', reason: 'request-failed' };
+ }
+}
+
+if (isDirectlyInvoked(import.meta.url)) {
+ await cancelCurrentCiRun();
+}
diff --git a/scripts/cancel-current-ci-run.test.js b/scripts/cancel-current-ci-run.test.js
new file mode 100644
index 0000000000..9bde971941
--- /dev/null
+++ b/scripts/cancel-current-ci-run.test.js
@@ -0,0 +1,93 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { cancelCurrentCiRun } from './cancel-current-ci-run.js';
+
+const ENV = {
+ GITHUB_REPOSITORY: 'example/portos',
+ GITHUB_RUN_ID: '123456789',
+ GITHUB_TOKEN: 'ephemeral-test-token',
+};
+
+const response = (status) => ({ ok: status >= 200 && status < 300, status });
+
+function setup() {
+ return {
+ fetchImpl: vi.fn(),
+ logger: { log: vi.fn(), error: vi.fn() },
+ };
+}
+
+describe('cancelCurrentCiRun', () => {
+ it('cancels the current repository run with the step-scoped token', async () => {
+ const { fetchImpl, logger } = setup();
+ fetchImpl.mockResolvedValue(response(202));
+
+ await expect(cancelCurrentCiRun({ env: ENV, fetchImpl, logger })).resolves.toEqual({
+ outcome: 'requested',
+ status: 202,
+ });
+
+ expect(fetchImpl).toHaveBeenCalledWith(
+ 'https://api.github.com/repos/example/portos/actions/runs/123456789/cancel',
+ expect.objectContaining({
+ method: 'POST',
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: 'Bearer ephemeral-test-token',
+ 'X-GitHub-Api-Version': '2022-11-28',
+ },
+ signal: expect.any(AbortSignal),
+ }),
+ );
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+
+ it('treats an already-terminal run as a successful no-op', async () => {
+ const { fetchImpl, logger } = setup();
+ fetchImpl.mockResolvedValue(response(409));
+
+ await expect(cancelCurrentCiRun({ env: ENV, fetchImpl, logger })).resolves.toEqual({
+ outcome: 'already-terminal',
+ status: 409,
+ });
+
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+
+ it('keeps a permission failure best-effort and preserves the original job failure', async () => {
+ const { fetchImpl, logger } = setup();
+ fetchImpl.mockResolvedValue(response(403));
+
+ await expect(cancelCurrentCiRun({ env: ENV, fetchImpl, logger })).resolves.toEqual({
+ outcome: 'unavailable',
+ status: 403,
+ });
+
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('403'));
+ });
+
+ it('keeps a network failure best-effort', async () => {
+ const { fetchImpl, logger } = setup();
+ fetchImpl.mockRejectedValue(new Error('network unavailable'));
+
+ await expect(cancelCurrentCiRun({ env: ENV, fetchImpl, logger })).resolves.toEqual({
+ outcome: 'unavailable',
+ reason: 'request-failed',
+ });
+
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('network unavailable'));
+ });
+
+ it('does not make a request when the target cannot come from Actions environment', async () => {
+ const { fetchImpl, logger } = setup();
+
+ await expect(cancelCurrentCiRun({
+ env: { ...ENV, GITHUB_REPOSITORY: 'https://example.invalid/other', GITHUB_RUN_ID: 'run-from-args' },
+ fetchImpl,
+ logger,
+ })).resolves.toEqual({ outcome: 'skipped', reason: 'invalid-environment' });
+
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('environment'));
+ });
+});
diff --git a/scripts/ci-fail-fast.test.js b/scripts/ci-fail-fast.test.js
new file mode 100644
index 0000000000..ed580e8ec4
--- /dev/null
+++ b/scripts/ci-fail-fast.test.js
@@ -0,0 +1,68 @@
+import { readFileSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+import { describe, expect, it } from 'vitest';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+const WORKFLOW = readFileSync(join(REPO_ROOT, '.github/workflows/ci.yml'), 'utf8');
+const LEAF_JOBS = ['server', 'client', 'database', 'windows-server'];
+const NON_LEAF_JOBS = ['impact', 'gate', 'full-gate'];
+const FAIL_FAST_STEP = [
+ ' - name: Cancel sibling CI jobs after failure',
+ ' if: failure()',
+ ' env:',
+ ' GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}',
+ ' run: node scripts/cancel-current-ci-run.js',
+].join('\n');
+
+function workflowJobs(yaml) {
+ const jobsStart = yaml.indexOf('\njobs:\n');
+ const body = yaml.slice(jobsStart);
+ const jobs = {};
+ let current = null;
+ for (const line of body.split('\n')) {
+ const header = line.match(/^ {2}([a-z][a-z0-9-]*):\s*$/);
+ if (header) {
+ current = header[1];
+ jobs[current] = [];
+ continue;
+ }
+ if (current) jobs[current].push(line);
+ }
+ return Object.fromEntries(Object.entries(jobs).map(([id, lines]) => [id, lines.join('\n')]));
+}
+
+describe('ci.yml fail-fast cancellation contract', () => {
+ const jobs = workflowJobs(WORKFLOW);
+
+ it('adds the cancellation step as the final step of every expensive leaf job', () => {
+ for (const id of LEAF_JOBS) {
+ const body = jobs[id];
+ expect(body, id).toBeTruthy();
+ const step = body.slice(body.lastIndexOf(' - name: Cancel sibling CI jobs after failure')).trimEnd();
+ expect(step, id).toBe(FAIL_FAST_STEP);
+ expect(body.match(/GITHUB_TOKEN:/g), id).toHaveLength(1);
+ }
+ });
+
+ it('grants only the leaf jobs the minimum cancellation permissions', () => {
+ for (const id of LEAF_JOBS) {
+ const body = jobs[id];
+ expect(body, id).toMatch(/\n permissions:\n contents: read\n actions: write\n/);
+ }
+ for (const id of NON_LEAF_JOBS) {
+ expect(jobs[id], id).not.toContain('actions: write');
+ }
+ });
+
+ it('does not pass arbitrary repository or run targets to the helper', () => {
+ for (const id of LEAF_JOBS) {
+ const body = jobs[id];
+ expect(body, id).not.toMatch(/GITHUB_(?:REPOSITORY|RUN_ID):/);
+ const step = body.slice(body.lastIndexOf(' - name: Cancel sibling CI jobs after failure'));
+ expect(step, id).not.toContain('\n with:');
+ expect(body, id).toContain('if: failure()');
+ }
+ });
+});