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
address review: close three fail-open paths in the cancel-recovery guards
[._.]/ Adam Eivy4bea57102959
diff --git a/.github/workflows/ci-cancel-recovery.yml b/.github/workflows/ci-cancel-recovery.ymlindex cb29a3a749..add2aadf58 100644--- a/.github/workflows/ci-cancel-recovery.yml+++ b/.github/workflows/ci-cancel-recovery.yml@@ -61,5 +61,6 @@ jobs:CI_RUN_EVENT: ${{ github.event.workflow_run.event }}CI_RUN_CONCLUSION: ${{ github.event.workflow_run.conclusion }}CI_RUN_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}+ CI_RUN_HEAD_REPOSITORY_ID: ${{ github.event.workflow_run.head_repository.id }}CI_RUN_HEAD_SHA: ${{ github.event.workflow_run.head_sha }}run: node scripts/ci-retry-cancelled-run.jsdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 62e30447e8..7e65f7e290 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -741,5 +741,10 @@ jobs:- name: Require the aggregate gate to have passedenv: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 doing+ # its job, this check is what lets release.yml skip re-running the+ # complete suite (scripts/verify-ci-status.js).+ CI_GATE_REQUIRE_SUCCESS: 'true'CI_GATE_RESULT_GATE: ${{ needs.gate.result }}run: node scripts/ci-gate-report.jsdiff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.mdindex fbedd6bc2b..0f144b3cdb 100644--- a/docs/GITHUB_ACTIONS.md+++ b/docs/GITHUB_ACTIONS.md@@ -331,10 +331,11 @@ own.### Shallow checkoutsNo job clones full history. `actions/checkout` runs at `fetch-depth: 2`-in every job that diffs against the base — the two gate jobs use `fetch-depth:-1`, because they check out only to run `scripts/ci-gate-report.js` and never-look at history. Depth 2 on a pull request is the merge ref plus both of its-parents — and the+in every job that diffs against the base. The two gate jobs set no depth at all+(the action's own default is 1) and pass `sparse-checkout: scripts` instead:+they check out only to run `scripts/ci-gate-report.js`, never look at history,+and sparse mode makes the action fetch with `--filter=blob:none`. Depth 2 on a+pull request is the merge ref plus both of its parents — and thefirst parent *is* the base-branch commit the pull request is diffed against.`scripts/ci-base-sha.js` reads it (`HEAD^1`) and exports `CI_BASE_SHA` for therest of the job, so the planner's `git diff <base>...HEAD` resolves withoutdiff --git a/scripts/ci-gate-report.js b/scripts/ci-gate-report.jsindex 4222dc531e..1476ac5a27 100644--- a/scripts/ci-gate-report.js+++ b/scripts/ci-gate-report.js@@ -34,6 +34,13 @@ import { writeStepSummary } from './lib/githubOutput.js';const RESULT_ENV_PREFIX = 'CI_GATE_RESULT_';/** GitHub's `needs.<job>.result` values that do not block the gate. */const PASSING_RESULTS = new Set(['success', 'skipped']);+/**+ * `Full CI Gate` sets `CI_GATE_REQUIRE_SUCCESS`, because a `skipped` input+ * must NOT satisfy it. `scripts/verify-ci-status.js` lets a release skip the+ * complete suite on the strength of that check, so accepting anything short of+ * `success` there would ship an untested tree.+ */+const STRICT_PASSING_RESULTS = new Set(['success']);const DEFAULT_LABEL = 'CI Gate';const TROUBLESHOOTING_ANCHOR = '"CI cancelled with no successor run" in docs/TROUBLESHOOTING.md';@@ -65,17 +72,19 @@ 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* @returns {{verdict: 'pass'|'cancelled'|'failure', lines: string[]}}*/-export function summarizeGateResults(results, label = DEFAULT_LABEL) {- const passed = results.filter(({ result }) => PASSING_RESULTS.has(result));+export function summarizeGateResults(results, label = DEFAULT_LABEL, requireSuccess = false) {+ 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);// Anything neither passing nor cancelled is a failure — `failure`, and also// the `unknown` above. Defaulting an unrecognised result to "failed" is the// safe direction: it blocks with a loud message instead of being waved// through as collateral of a cancel.const failed = results- .filter(({ result }) => !PASSING_RESULTS.has(result) && result !== 'cancelled')+ .filter(({ result }) => !passing.has(result) && result !== 'cancelled').map(pair);const finished = () => (passed.length? `Jobs that finished: ${passed.map(pair).join(', ')}`@@ -132,7 +141,11 @@ export function reportGate({writeSummary = writeStepSummary,} = {}) {const label = env.CI_GATE_LABEL?.trim() || DEFAULT_LABEL;- const { verdict, lines } = summarizeGateResults(collectGateResults(env), label);+ const { verdict, lines } = summarizeGateResults(+ collectGateResults(env),+ label,+ env.CI_GATE_REQUIRE_SUCCESS === 'true',+ );const ok = verdict === 'pass';for (const line of lines) (ok ? logger.log : logger.error)?.call(logger, line);diff --git a/scripts/ci-gate-report.test.js b/scripts/ci-gate-report.test.jsindex 120f919852..2d60a606fd 100644--- a/scripts/ci-gate-report.test.js+++ b/scripts/ci-gate-report.test.js@@ -86,6 +86,17 @@ describe('summarizeGateResults', () => {expect(summary.lines).toContain('Failed jobs: server=unknown');});+ it('accepts a skipped job by default, but never under requireSuccess', () => {+ // A per-job `skipped` is the impact plan working as designed, so the+ // aggregate gate passes on it. `Full CI Gate` must not: a release skips+ // 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);+ expect(strict.verdict).toBe('failure');+ expect(strict.lines).toContain('Failed jobs: gate=skipped');+ });+it('uses the supplied gate label so the two gates are distinguishable', () => {const summary = summarizeGateResults(results({ gate: 'cancelled' }), 'Full CI Gate');expect(summary.lines[0]).toContain('Full CI Gate');@@ -106,6 +117,15 @@ describe('reportGate', () => {};};+ it('turns CI_GATE_REQUIRE_SUCCESS on for the strict gate', () => {+ const { ...sinks } = capture();+ 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 });+ });+it('writes a pass to stdout and reports ok', () => {const { logged, errored, ...sinks } = capture();const outcome = reportGate({ env: { CI_GATE_RESULT_SERVER: 'success' }, ...sinks });@@ -148,6 +168,11 @@ describe('ci.yml gate wiring', () => {expect(jobs[id]).toContain('sparse-checkout: scripts');});+ 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');+ });+it('feeds the aggregate gate every job it waits on', () => {// A job added to `needs:` without its CI_GATE_RESULT_ line would be waited// for and then never checked — the silent hole this asserts away.diff --git a/scripts/ci-retry-cancelled-run.js b/scripts/ci-retry-cancelled-run.jsindex a678010d97..f73394bd36 100644--- a/scripts/ci-retry-cancelled-run.js+++ b/scripts/ci-retry-cancelled-run.js@@ -31,7 +31,7 @@*/import { isDirectlyInvoked } from './lib/directInvocation.js';-import { githubRequest, isSuccess, repoApiPath } from './lib/githubActionsApi.js';+import { githubRequest, isSuccess, repoApiPath, trimmed } from './lib/githubActionsApi.js';import { writeStepSummary } from './lib/githubOutput.js';const REQUEST_TIMEOUT_MS = 15_000;@@ -40,9 +40,31 @@ 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 job conclusion that means something really broke, not that it was stopped. */+/** A conclusion that means something really broke, not that it was stopped. */const FAILING_CONCLUSIONS = new Set(['failure', 'timed_out']);+/**+ * 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);+/*** Validate and normalise the run this invocation may retry.*@@ -54,13 +76,16 @@ const FAILING_CONCLUSIONS = new Set(['failure', 'timed_out']);* @returns {object|null}*/export function retryTargetFromEnv(env) {- const str = (key) => (typeof env[key] === 'string' ? env[key].trim() : '');+ const str = (key) => trimmed(env[key]);const token = str('GITHUB_TOKEN');const runId = str('CI_RUN_ID');const runAttempt = str('CI_RUN_ATTEMPT');const runNumber = str('CI_RUN_NUMBER');const workflowId = str('CI_WORKFLOW_ID');const headBranch = str('CI_RUN_HEAD_BRANCH');+ // Optional: absent on an older payload, so it narrows the sibling lookup+ // when present rather than invalidating the target when it is not.+ const headRepositoryId = str('CI_RUN_HEAD_REPOSITORY_ID');const repoPath = repoApiPath(env);if (!repoPath || !token || !headBranch) return null;@@ -74,6 +99,7 @@ export function retryTargetFromEnv(env) {runNumber: Number(runNumber),workflowId,headBranch,+ headRepositoryId: /^\d+$/.test(headRepositoryId) ? headRepositoryId : '',headSha: str('CI_RUN_HEAD_SHA'),conclusion: str('CI_RUN_CONCLUSION'),event: str('CI_RUN_EVENT'),@@ -132,6 +158,11 @@ async function fetchNewestSiblingRunNumber(fetchImpl, target, logger) {if (!body || !Array.isArray(body.workflow_runs)) return null;return body.workflow_runs.filter((run) => String(run?.id) !== target.runId)+ // `branch=` matches head_branch alone, so two forks pushing `patch-1`+ // land in the same listing and one would read as the other's successor.+ // Only a missed retry, but the numeric repository id rules it out.+ .filter((run) => !target.headRepositoryId+ || String(run?.head_repository?.id ?? target.headRepositoryId) === target.headRepositoryId).reduce((newest, run) => Math.max(newest, Number(run?.run_number) || 0), 0);}@@ -193,9 +224,7 @@ export async function retryCancelledCiRun({return done('error', `⚠️ CI retry skipped: could not list the jobs of run ${target.runId}`,{ outcome: 'unavailable', reason: 'jobs-unavailable' });}- const failedJobs = jobs- .filter((job) => FAILING_CONCLUSIONS.has(job?.conclusion))- .map((job) => job?.name || 'unnamed job');+ const failedJobs = jobs.filter(jobFailed).map(safeJobName);if (failedJobs.length) {return done('log', `ℹ️ CI retry skipped: run ${target.runId} cancelled after a real failure (${failedJobs.join(', ')})`,{ outcome: 'skipped', reason: 'job-failed' });diff --git a/scripts/ci-retry-cancelled-run.test.js b/scripts/ci-retry-cancelled-run.test.jsindex 0c6d44aaf5..bc8494e923 100644--- a/scripts/ci-retry-cancelled-run.test.js+++ b/scripts/ci-retry-cancelled-run.test.js@@ -31,6 +31,7 @@ const BASE_ENV = {CI_RUN_EVENT: 'pull_request',CI_RUN_CONCLUSION: 'cancelled',CI_RUN_HEAD_BRANCH: 'claim/issue-1',+ CI_RUN_HEAD_REPOSITORY_ID: '555',CI_RUN_HEAD_SHA: 'c'.repeat(40),};@@ -45,7 +46,12 @@ function stubFetch({ jobs = [], runs = [], rerunStatus = 201 } = {}) {const impl = vi.fn(async (url, init = {}) => {calls.push({ url, method: init.method || 'GET' });if (url.includes('/jobs?')) return json({ total_count: jobs.length, jobs });- if (url.includes('/runs?')) return json({ total_count: runs.length, workflow_runs: runs });+ if (url.includes('/runs?')) {+ return json({+ total_count: runs.length,+ workflow_runs: runs.map((r) => ({ head_repository: { id: 555 }, ...r })),+ });+ }if (url.endsWith('/rerun')) return { ok: rerunStatus < 300, status: rerunStatus };throw new Error(`unexpected url ${url}`);});@@ -115,6 +121,72 @@ describe('retryCancelledCiRun guards', () => {},);+ it('retries a job whose STEP failed but whose conclusion reads cancelled', async () => {+ // The fail-fast self-cancel can land while the failing job is still in its+ // post-steps, and GitHub then records that job as `cancelled`. Trusting the+ // job conclusion alone would re-run a genuinely red tree.+ const fetchStub = stubFetch({+ jobs: [{+ name: 'Server tests',+ conclusion: 'cancelled',+ steps: [{ conclusion: 'success' }, { conclusion: 'failure' }],+ }],+ });+ await expect(run(BASE_ENV, fetchStub))+ .resolves.toMatchObject({ outcome: 'skipped', reason: 'job-failed' });+ expect(fetchStub.rerunRequested()).toBe(false);+ });++ it('is not suppressed by an OLDER sibling run', async () => {+ // The supersession guard must compare, not merely detect a sibling.+ const fetchStub = stubFetch({ runs: [{ id: 4000, run_number: 899 }, { id: 4242, run_number: 900 }] });+ await expect(run(BASE_ENV, fetchStub)).resolves.toMatchObject({ outcome: 'requested' });+ });++ it('is not suppressed by a same-named branch on a different fork', async () => {+ // `?branch=` matches head_branch alone, so two forks pushing `patch-1`+ // share a listing. Only a missed retry, but it is avoidable.+ const fetchStub = stubFetch({+ runs: [{ id: 9001, run_number: 950, head_repository: { id: 999 } }],+ });+ await expect(run(BASE_ENV, fetchStub)).resolves.toMatchObject({ outcome: 'requested' });+ });++ it('reads a job listing that spans two pages before deciding', async () => {+ // A failing job on page 2 must still block the retry.+ const pages = {+ 1: { total_count: 2, jobs: [{ name: 'Client', conclusion: 'cancelled' }] },+ 2: { total_count: 2, jobs: [{ name: 'Server tests', conclusion: 'failure' }] },+ };+ const impl = vi.fn(async (url) => {+ if (url.includes('/jobs?')) return json(pages[new URL(url).searchParams.get('page')]);+ return json({ workflow_runs: [] });+ });+ await expect(retryCancelledCiRun({+ env: BASE_ENV, fetchImpl: impl, logger: silent, writeSummary: noSummary,+ })).resolves.toMatchObject({ outcome: 'skipped', reason: 'job-failed' });+ });++ it('never lets a pull-request job name forge an Actions workflow command', async () => {+ // `job.name` comes from the PR's own workflow file, and Actions parses a+ // line starting with `::` as a command.+ const logged = [];+ const fetchStub = stubFetch({+ jobs: [{ name: 'Server\n::add-mask::secret', conclusion: 'failure' }],+ });+ await retryCancelledCiRun({+ env: BASE_ENV,+ fetchImpl: fetchStub.impl,+ logger: { log: (l) => logged.push(l), error: (l) => logged.push(l) },+ writeSummary: noSummary,+ });++ const text = logged.join('\n');+ expect(text).toContain('Server');+ expect(text).not.toContain('::add-mask::');+ expect(text.split('\n').some((line) => line.startsWith('::'))).toBe(false);+ });+it.each([['a run that did not end cancelled', { CI_RUN_CONCLUSION: 'failure' }, 'not-cancelled'],['a nightly or dispatched run', { CI_RUN_EVENT: 'schedule' }, 'not-a-pull-request'],@@ -220,7 +292,8 @@ describe('ci-cancel-recovery.yml wiring', () => {it('passes the run identity the script validates', () => {for (const key of ['CI_RUN_ID', 'CI_RUN_ATTEMPT', 'CI_RUN_NUMBER', 'CI_WORKFLOW_ID',- 'CI_RUN_EVENT', 'CI_RUN_CONCLUSION', 'CI_RUN_HEAD_BRANCH', 'CI_RUN_HEAD_SHA']) {+ 'CI_RUN_EVENT', 'CI_RUN_CONCLUSION', 'CI_RUN_HEAD_BRANCH', 'CI_RUN_HEAD_REPOSITORY_ID',+ 'CI_RUN_HEAD_SHA']) {expect(jobs.retry, key).toContain(`${key}: \${{ github.event.workflow_run.`);}});diff --git a/scripts/lib/githubActionsApi.js b/scripts/lib/githubActionsApi.jsindex 6933bd7455..c30d6b9cc4 100644--- a/scripts/lib/githubActionsApi.js+++ b/scripts/lib/githubActionsApi.js@@ -16,7 +16,8 @@ const PUBLIC_API_BASE = 'https://api.github.com';const REPOSITORY_PATTERN = /^[^/\s]+\/[^/\s]+$/;const DEFAULT_TIMEOUT_MS = 10_000;-const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');+/** `String#trim` that tolerates a missing or non-string env value. */+export const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');/*** The API origin to send the token to, or null to send it nowhere.@@ -32,8 +33,17 @@ const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');export function resolveApiBase(configuredApiUrl) {const raw = trimmed(configuredApiUrl);if (!raw) return PUBLIC_API_BASE;- const parsed = URL.parse(raw);- if (!parsed || parsed.protocol !== 'https:' || parsed.username || parsed.password+ // `new URL` in try/catch rather than the tidier `URL.parse`: that landed in+ // Node 22.1, and the recovery workflow deliberately runs on the runner image's+ // DEFAULT node with no setup-node. A TypeError here would take out every+ // recovery run on an older image instead of returning null.+ let parsed;+ try {+ parsed = new URL(raw);+ } catch {+ return null;+ }+ if (parsed.protocol !== 'https:' || parsed.username || parsed.password|| parsed.search || parsed.hash) {return null;}