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: confirm the retry budget against the live run, and make the sparse-checkout guard actually guard
[._.]/ Adam Eivy04c8cbe41fc9
diff --git a/scripts/ci-gate-report.js b/scripts/ci-gate-report.jsindex 1476ac5a27..9e042dfd84 100644--- a/scripts/ci-gate-report.js+++ b/scripts/ci-gate-report.js@@ -111,9 +111,11 @@ export function summarizeGateResults(results, label = DEFAULT_LABEL, requireSucc`🚫 ${label}: this run was CANCELLED, not failed — no job reported a failure.`,`Cancelled jobs: ${cancelled.join(', ')}`,finished(),- 'Do not go looking for a broken test. Either a newer push superseded this run'- + ' (cancel-in-progress), or GitHub cancelled it externally while several runs'- + ' were in flight.',+ 'No test failed, so start with why the job STOPPED. A job that hits the'+ + ' 6-hour limit is recorded as `cancelled`, not `timed_out` — check the'+ + ' cancelled jobs for a hang first. Otherwise a newer push superseded this'+ + ' run (cancel-in-progress), or GitHub cancelled it externally while several'+ + ' runs were in flight.',`Telling those apart, and what to do about each: ${TROUBLESHOOTING_ANCHOR}`,],};diff --git a/scripts/ci-retry-cancelled-run.js b/scripts/ci-retry-cancelled-run.jsindex f73394bd36..18584ed91b 100644--- a/scripts/ci-retry-cancelled-run.js+++ b/scripts/ci-retry-cancelled-run.js@@ -17,6 +17,10 @@** - `run_attempt === 1` IS the retry budget. `POST /rerun` re-runs the same* run id as attempt 2, so attempt 2's cancel sees attempt 2 and stops.+ * The budget is confirmed against the run's LIVE state, not only the+ * event payload, because the payload is a snapshot: a human can re-run+ * the same run, or the event can be redelivered, while this job is+ * still queued behind the very backlog it exists to survive.* - No job may have concluded `failure`/`timed_out`. This repository cancels* its own run from a failing job (scripts/cancel-current-ci-run.js), which* makes the RUN read `cancelled` while a job really did fail.@@ -144,6 +148,26 @@ async function fetchAttemptJobs(fetchImpl, target, logger) {return null;}+/**+ * The run's state as GitHub holds it NOW, or null when it cannot be read.+ *+ * Everything else here comes from the `workflow_run` payload, which is a+ * snapshot taken when the run completed. This job can start long after that —+ * it queues behind the same backlog that caused the cancel — so the payload+ * can say "attempt 1, cancelled" while a human has already re-run it. Spending+ * the one-retry budget on that stale reading is how one retry becomes three.+ */+async function fetchLiveRunState(fetchImpl, target, logger) {+ const url = `${target.repoPath}/actions/runs/${target.runId}`;+ const body = await readJson(fetchImpl, url, target.token, logger);+ if (!body) return null;+ return {+ runAttempt: Number(body.run_attempt),+ status: typeof body.status === 'string' ? body.status : '',+ conclusion: typeof body.conclusion === 'string' ? body.conclusion : '',+ };+}+/*** The run number of the newest sibling run, or null when the listing failed.* `run_number` increases monotonically per workflow, so taking the maximum@@ -230,6 +254,18 @@ export async function retryCancelledCiRun({{ outcome: 'skipped', reason: 'job-failed' });}+ const live = await fetchLiveRunState(fetchImpl, target, logger);+ if (!live) {+ return done('error', `⚠️ CI retry skipped: could not read the current state of run ${target.runId}`,+ { outcome: 'unavailable', reason: 'run-state-unavailable' });+ }+ if (live.runAttempt !== 1 || live.status !== 'completed' || live.conclusion !== 'cancelled') {+ return done('log', `ℹ️ CI retry skipped: run ${target.runId} has moved on since the event (attempt ${live.runAttempt}, ${live.status}/${live.conclusion || 'no conclusion'})`,+ { outcome: 'skipped', reason: 'run-state-moved-on' });+ }++ // Listed LAST, immediately before the POST, so the window in which a fresh+ // push could create a successor we do not see is as small as it can be.const newestSibling = await fetchNewestSiblingRunNumber(fetchImpl, target, logger);if (newestSibling === null) {return done('error', `⚠️ CI retry skipped: could not list sibling runs for run ${target.runId}`,diff --git a/scripts/ci-retry-cancelled-run.test.js b/scripts/ci-retry-cancelled-run.test.jsindex bc8494e923..450f2da14f 100644--- a/scripts/ci-retry-cancelled-run.test.js+++ b/scripts/ci-retry-cancelled-run.test.js@@ -41,11 +41,13 @@ 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 } = {}) {+function stubFetch({ jobs = [], runs = [], rerunStatus = 201, live } = {}) {const calls = [];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 });+ // 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('/runs?')) {return json({total_count: runs.length,@@ -53,6 +55,9 @@ function stubFetch({ jobs = [], runs = [], rerunStatus = 201 } = {}) {});}if (url.endsWith('/rerun')) return { ok: rerunStatus < 300, status: rerunStatus };+ 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')) };@@ -198,6 +203,30 @@ describe('retryCancelledCiRun guards', () => {expect(fetchStub.impl).not.toHaveBeenCalled();});+ it.each([+ ['a human already re-ran it', { run_attempt: 2 }],+ ['it is running again', { status: 'in_progress', conclusion: '' }],+ ['the re-run has since succeeded', { conclusion: 'success' }],+ ])('never spends the budget when the live run says %s', async (_label, live) => {+ // The workflow_run payload is a snapshot; this job can start long after it.+ const fetchStub = stubFetch({ live });+ await expect(run(BASE_ENV, fetchStub))+ .resolves.toMatchObject({ outcome: 'skipped', reason: 'run-state-moved-on' });+ expect(fetchStub.rerunRequested()).toBe(false);+ });++ it('does not retry when the live run state cannot be read', async () => {+ const impl = vi.fn(async (url) => {+ if (url.includes('/jobs?')) return json({ total_count: 0, jobs: [] });+ if (url.includes('/runs?')) return json({ workflow_runs: [] });+ return { ok: false, status: 500 };+ });+ await expect(retryCancelledCiRun({+ env: BASE_ENV, fetchImpl: impl, logger: silent, writeSummary: noSummary,+ })).resolves.toMatchObject({ outcome: 'unavailable', reason: 'run-state-unavailable' });+ expect(impl.mock.calls.some(([url]) => url.endsWith('/rerun'))).toBe(false);+ });+it('encodes the branch name into the query, never into a path', async () => {// The head branch is attacker-controlled on a fork PR.const fetchStub = stubFetch();@@ -231,9 +260,11 @@ describe('retryCancelledCiRun guards', () => {});it('does not retry when the sibling-run listing cannot be read', async () => {- const impl = vi.fn(async (url) => (url.includes('/runs?')- ? { ok: false, status: 403 }- : json({ total_count: 0, jobs: [] })));+ const impl = vi.fn(async (url) => {+ if (url.includes('/runs?')) return { ok: false, status: 403 };+ if (url.includes('/jobs?')) return json({ total_count: 0, jobs: [] });+ return json({ run_attempt: 1, status: 'completed', conclusion: 'cancelled' });+ });await expect(retryCancelledCiRun({env: BASE_ENV, fetchImpl: impl, logger: silent, writeSummary: noSummary,})).resolves.toMatchObject({ outcome: 'unavailable', reason: 'sibling-runs-unavailable' });@@ -290,11 +321,22 @@ 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_REPOSITORY_ID',- 'CI_RUN_HEAD_SHA']) {- expect(jobs.retry, key).toContain(`${key}: \${{ github.event.workflow_run.`);+ it('passes the run identity the script validates, each from the right field', () => {+ // The exact expression, not just the prefix: mapping CI_RUN_NUMBER to+ // `.id` would be a silently wrong supersession comparison.+ const FIELDS = {+ CI_RUN_ID: 'id',+ CI_RUN_ATTEMPT: 'run_attempt',+ CI_RUN_NUMBER: 'run_number',+ CI_WORKFLOW_ID: 'workflow_id',+ CI_RUN_EVENT: 'event',+ CI_RUN_CONCLUSION: 'conclusion',+ CI_RUN_HEAD_BRANCH: 'head_branch',+ CI_RUN_HEAD_REPOSITORY_ID: 'head_repository.id',+ CI_RUN_HEAD_SHA: 'head_sha',+ };+ for (const [key, field] of Object.entries(FIELDS)) {+ expect(jobs.retry, key).toContain(`${key}: \${{ github.event.workflow_run.${field} }}`);}});diff --git a/scripts/pre-install-entrypoints.test.js b/scripts/pre-install-entrypoints.test.jsindex e53e5de058..4841f59254 100644--- a/scripts/pre-install-entrypoints.test.js+++ b/scripts/pre-install-entrypoints.test.js@@ -68,13 +68,16 @@ function importSpecifiers(source) {return [...code.matchAll(/(?:from|import)\s*['"]([^'"]+)['"]/g)].map(([, s]) => s);}-/** Every bare (non-relative) specifier reachable from `entry`, transitively. */-function bareSpecifiersReachableFrom(entry) {- const seen = new Set();+/**+ * Every specifier reachable from `entry`, transitively, split into the bare+ * ones and the repo-relative FILES the walk visited (`entry` included).+ */+function specifiersReachableFrom(entry) {+ const files = new Set();const bare = new Set();const walk = (relativePath) => {- if (seen.has(relativePath)) return;- seen.add(relativePath);+ if (files.has(relativePath)) return;+ files.add(relativePath);for (const specifier of importSpecifiers(readFileSync(join(REPO_ROOT, relativePath), 'utf8'))) {if (!specifier.startsWith('.')) {bare.add(specifier);@@ -84,9 +87,11 @@ function bareSpecifiersReachableFrom(entry) {}};walk(entry);- return [...bare];+ return { bare: [...bare], files: [...files] };}+const bareSpecifiersReachableFrom = (entry) => specifiersReachableFrom(entry).bare;+describe('scripts that must load from a bare checkout', () => {// The walker decides whether the assertions below mean anything, so it is// verified against this file's own known imports rather than trusted.@@ -112,3 +117,47 @@ describe('scripts that must load from a bare checkout', () => {},);});++/**+ * Builtin-only is NOT the same contract as fits-in-a-sparse-checkout, and the+ * difference is invisible until CI breaks: `scripts/run-ci-tests.js` reaches+ * `../server/lib/bufferedSpawn.js` today, which is builtin-only and would be+ * ABSENT under `sparse-checkout: scripts`. One such import added to a gate+ * script blocks every pull request with a module-not-found error, or leaves+ * the cancel-recovery workflow erroring instead of recovering.+ */+describe('scripts that run from a sparse checkout of scripts/', () => {+ /** Jobs that pass `sparse-checkout: scripts` → the script each one runs. */+ const SPARSE_CHECKOUT_SCRIPTS = [+ 'scripts/ci-gate-report.js',+ 'scripts/ci-retry-cancelled-run.js',+ ];++ it('the sparse jobs are exactly the ones claiming a sparse checkout', () => {+ // Discovery floor: a THIRD sparse job added without a row above would+ // never be held to the cone contract below.+ const workflows = ['.github/workflows/ci.yml', '.github/workflows/ci-cancel-recovery.yml']+ .map((rel) => readFileSync(join(REPO_ROOT, rel), 'utf8'))+ .join('\n');+ const sparseJobs = workflows.split('sparse-checkout: scripts').length - 1;+ // ci.yml's two gate jobs both run ci-gate-report.js; the recovery workflow+ // runs the other one.+ expect(sparseJobs).toBe(3);+ for (const entry of SPARSE_CHECKOUT_SCRIPTS) {+ expect(workflows, entry).toContain(`node ${entry}`);+ }+ });++ it.each(SPARSE_CHECKOUT_SCRIPTS)('%s reaches no file outside scripts/', (entry) => {+ const outside = specifiersReachableFrom(entry).files+ .filter((file) => !file.startsWith('scripts/'));++ expect(outside).toEqual([]);+ });++ it('the cone assertion can fail', () => {+ // Negative control against the exact escape it exists to catch.+ expect(specifiersReachableFrom('scripts/run-ci-tests.js').files)+ .toContain('server/lib/bufferedSpawn.js');+ });+});