diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 25f3659603..429d9cedaa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,6 +41,7 @@ jobs: run_browser: ${{ steps.reuse.outputs.run_browser }} run_layout: ${{ steps.reuse.outputs.run_layout }} reuse: ${{ steps.reuse.outputs.reuse }} + red_main_oid: ${{ steps.plan.outputs.red_main_oid }} steps: - uses: actions/checkout@v7 with: @@ -50,6 +51,13 @@ jobs: with: bun-version: "1.4.2" - run: bun install --frozen-lockfile + # Fail fast while main is red (#2942): hosted proof whose merge ref contains + # the recorded bad commit is refused, except declared fixes. Drafts run cheap gates only. + - name: Refuse doomed proof while main is red + if: github.event_name == 'pull_request' && !github.event.pull_request.draft + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: bun scripts/red-main-cli.ts gate - name: Plan affected fast and local checks id: plan env: @@ -66,6 +74,14 @@ jobs: - name: Discover product scenario and assertion ownership if: steps.plan.outputs.cadence != 'draft' run: bun scripts/proof-inventory.ts + # Plan outputs and retention decisions are set before any metadata gate can + # fail, so a main push still runs its complete selected proof (#2942). + - name: Retain only validated equivalent automatic proof + id: reuse + env: + GH_TOKEN: ${{ github.token }} + PR_DRAFT: ${{ github.event.pull_request.draft }} + run: bun scripts/proof-reuse.ts - name: Lint, leakage and contribution workflow guards run: bun run lint - name: Env documentation matches its descriptors @@ -82,12 +98,6 @@ jobs: elif [ "$GITHUB_EVENT_NAME" = push ]; then bun scripts/check-changeset.ts "$BEFORE_SHA" fi - - name: Retain only validated equivalent automatic proof - id: reuse - env: - GH_TOKEN: ${{ github.token }} - PR_DRAFT: ${{ github.event.pull_request.draft }} - run: bun scripts/proof-reuse.ts - name: Retention ledger and diagnostics if: always() uses: actions/upload-artifact@v7 @@ -102,7 +112,7 @@ jobs: verify: # Packaging and verification are independent after cheap rejection gates. needs: changeset - if: needs.changeset.outputs.verify == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.verify == 'true' }} runs-on: ubuntu-24.04 timeout-minutes: 7 steps: @@ -123,6 +133,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Strict types and curated fast tests concurrently on this runner id: verify_proof @@ -142,7 +153,7 @@ jobs: pack: needs: changeset - if: needs.changeset.outputs.pack == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.pack == 'true' }} timeout-minutes: 5 runs-on: ubuntu-24.04 env: @@ -170,7 +181,7 @@ jobs: unit: needs: changeset - if: needs.changeset.outputs.unit == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.unit == 'true' }} runs-on: ubuntu-24.04 # Separate network setup from the unchanged proof budget (#2658). # 12 minutes setup + 30 minutes proof + 3 minutes for other steps. @@ -194,6 +205,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Real Chrome and offline Linux namespace prerequisites id: runtime_setup @@ -250,7 +262,7 @@ jobs: runtime: needs: changeset - if: needs.changeset.outputs.runtime == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.runtime == 'true' }} runs-on: ubuntu-24.04 # 12 minutes setup + unchanged 15 minutes proof + 3 minutes for other steps (#2658). timeout-minutes: 30 @@ -268,6 +280,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Real Chrome and offline Linux namespace prerequisites id: runtime_setup @@ -318,7 +331,7 @@ jobs: runtime_host: needs: changeset - if: needs.changeset.outputs.runtime_host == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.runtime_host == 'true' }} runs-on: ubuntu-24.04 # 12 minutes setup + unchanged 15 minutes proof + 3 minutes for other steps (#2658). timeout-minutes: 30 @@ -336,6 +349,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Real Chrome and offline Linux namespace prerequisites id: runtime_setup @@ -407,7 +421,7 @@ jobs: browser: needs: changeset - if: needs.changeset.outputs.browser == 'true' && needs.changeset.outputs.run_browser == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.browser == 'true' && needs.changeset.outputs.run_browser == 'true' }} runs-on: ubuntu-24.04 timeout-minutes: 20 strategy: @@ -428,6 +442,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Complete browser proof run: bun scripts/ci-proof.ts browser --shard=${{ matrix.shard }}/3 @@ -471,7 +486,7 @@ jobs: layout: needs: changeset - if: needs.changeset.outputs.layout == 'true' && needs.changeset.outputs.run_layout == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.layout == 'true' && needs.changeset.outputs.run_layout == 'true' }} runs-on: ubuntu-24.04 timeout-minutes: 25 strategy: @@ -492,6 +507,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Complete layout proof run: bun scripts/ci-proof.ts layout --shard=${{ matrix.shard }}/2 @@ -529,7 +545,7 @@ jobs: captures: needs: changeset - if: needs.changeset.outputs.captures == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.captures == 'true' }} runs-on: ubuntu-24.04 timeout-minutes: 20 steps: @@ -546,6 +562,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Complete captures proof run: bun scripts/ci-proof.ts captures @@ -581,7 +598,7 @@ jobs: endurance: needs: changeset - if: needs.changeset.outputs.endurance == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.endurance == 'true' }} runs-on: ubuntu-24.04 timeout-minutes: 20 steps: @@ -598,6 +615,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Complete endurance proof run: bun scripts/ci-proof.ts endurance diff --git a/.github/workflows/heavy-feedback.yml b/.github/workflows/heavy-feedback.yml index 3c6a8c3afe..fae427bf7b 100644 --- a/.github/workflows/heavy-feedback.yml +++ b/.github/workflows/heavy-feedback.yml @@ -53,6 +53,7 @@ jobs: pack: "${{ steps.plan.outputs.pack }}" run_browser: "${{ steps.reuse.outputs.run_browser }}" run_layout: "${{ steps.reuse.outputs.run_layout }}" + red_main_oid: "${{ steps.plan.outputs.red_main_oid }}" base_sha: "${{ steps.admit.outputs.base_sha }}" steps: - uses: actions/checkout@v7 @@ -76,6 +77,10 @@ jobs: fetch-depth: 0 ref: "${{ inputs.head_sha }}" - run: bun install --frozen-lockfile + - name: Refuse doomed proof while main is red + env: + PR_NUMBER: "${{ inputs.pr }}" + run: bun scripts/red-main-cli.ts gate - name: "Plan the PR's affected selection with feedback-heavy cadence" id: plan env: @@ -88,7 +93,7 @@ jobs: run: bun scripts/proof-reuse.ts verify: needs: changeset - if: "needs.changeset.outputs.verify == 'true'" + if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.verify == 'true' }}" runs-on: ubuntu-24.04 timeout-minutes: 7 steps: @@ -127,7 +132,7 @@ jobs: run: bun scripts/ci-verify-summary.ts pack: needs: changeset - if: "needs.changeset.outputs.pack == 'true'" + if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.pack == 'true' }}" timeout-minutes: 5 runs-on: ubuntu-24.04 env: @@ -150,7 +155,7 @@ jobs: run: bun scripts/ci-pack.ts unit: needs: changeset - if: "needs.changeset.outputs.unit == 'true'" + if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.unit == 'true' }}" runs-on: ubuntu-24.04 timeout-minutes: 45 strategy: @@ -200,7 +205,7 @@ jobs: retention-days: 7 runtime: needs: changeset - if: "needs.changeset.outputs.runtime == 'true'" + if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.runtime == 'true' }}" runs-on: ubuntu-24.04 timeout-minutes: 30 steps: @@ -244,7 +249,7 @@ jobs: retention-days: 7 runtime_host: needs: changeset - if: "needs.changeset.outputs.runtime_host == 'true'" + if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.runtime_host == 'true' }}" runs-on: ubuntu-24.04 timeout-minutes: 30 steps: @@ -300,7 +305,7 @@ jobs: retention-days: 7 browser: needs: changeset - if: "needs.changeset.outputs.browser == 'true' && needs.changeset.outputs.run_browser == 'true'" + if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.browser == 'true' && needs.changeset.outputs.run_browser == 'true' }}" runs-on: ubuntu-24.04 timeout-minutes: 20 strategy: @@ -339,7 +344,7 @@ jobs: retention-days: 7 layout: needs: changeset - if: "needs.changeset.outputs.layout == 'true' && needs.changeset.outputs.run_layout == 'true'" + if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.layout == 'true' && needs.changeset.outputs.run_layout == 'true' }}" runs-on: ubuntu-24.04 timeout-minutes: 25 strategy: @@ -377,7 +382,7 @@ jobs: retention-days: 7 captures: needs: changeset - if: "needs.changeset.outputs.captures == 'true'" + if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.captures == 'true' }}" runs-on: ubuntu-24.04 timeout-minutes: 20 steps: @@ -409,7 +414,7 @@ jobs: retention-days: 7 endurance: needs: changeset - if: "needs.changeset.outputs.endurance == 'true'" + if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.endurance == 'true' }}" runs-on: ubuntu-24.04 timeout-minutes: 20 steps: diff --git a/.github/workflows/red-main-probe.yml b/.github/workflows/red-main-probe.yml new file mode 100644 index 0000000000..ecd3b26f85 --- /dev/null +++ b/.github/workflows/red-main-probe.yml @@ -0,0 +1,66 @@ +# Triage probe for the red-main coordinator (#2942). Reruns only the named test +# files at one SHA. A probe never counts as proof and never makes anything +# mergeable; the coordinator reads its result to decide whether main is red. +name: red-main-probe +run-name: red-main probe ${{ inputs.purpose }} ${{ inputs.source_run }} ${{ inputs.sha }} + +on: + workflow_dispatch: + inputs: + purpose: + description: flake or bisect + required: true + type: choice + options: [flake, bisect] + source_run: + description: The main CI run whose failure is triaged + required: true + sha: + description: The commit to probe + required: true + tests: + description: JSON array of test files to rerun + required: true + +permissions: + contents: read + +jobs: + probe: + runs-on: ubuntu-24.04 + # 12 minutes setup + 30 minutes proof + 3 minutes for other steps, as unit proof. + timeout-minutes: 45 + steps: + - name: Validate dispatch identities + env: + SOURCE_RUN: ${{ inputs.source_run }} + PROBE_SHA: ${{ inputs.sha }} + run: | + [[ "$SOURCE_RUN" =~ ^[1-9][0-9]*$ ]] && [[ "$PROBE_SHA" =~ ^[a-f0-9]{40}$ ]] + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.repository.default_branch }} + path: tooling + persist-credentials: false + - uses: actions/checkout@v7 + with: + ref: ${{ inputs.sha }} + path: target + persist-credentials: false + fetch-depth: 0 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: "1.4.2" + - run: bun install --frozen-lockfile + working-directory: tooling + - run: bun install --frozen-lockfile --backend=copyfile + working-directory: target + - name: Real Chrome and offline Linux namespace prerequisites + timeout-minutes: 12 + working-directory: target + run: bash scripts/ci-runtime-setup.sh + - name: Rerun only the failing test files + timeout-minutes: 30 + env: + PROBE_TESTS: ${{ inputs.tests }} + run: bun tooling/scripts/red-main-cli.ts probe --target target diff --git a/.github/workflows/red-main.yml b/.github/workflows/red-main.yml new file mode 100644 index 0000000000..a5543048a3 --- /dev/null +++ b/.github/workflows/red-main.yml @@ -0,0 +1,52 @@ +# Red-main coordinator (#2942). Runs trusted default-branch tooling after every +# main CI run and every triage probe; candidate logs and artifacts are parsed as +# data, never executed. Writes only the shared coordination ref, incident and +# flake issues, PR reports, probe dispatches and cancellations of doomed PR proof. +name: red-main + +on: + workflow_run: + workflows: [CI, red-main-probe] + types: [completed] + +permissions: {} + +# One coordinator at a time: records and incident issues are never raced. +concurrency: + group: red-main-coordinator + cancel-in-progress: false + +jobs: + coordinate: + if: >- + (github.event.workflow_run.name == 'CI' && github.event.workflow_run.event == 'push' && + github.event.workflow_run.head_branch == 'main') || + (github.event.workflow_run.name == 'red-main-probe' && github.event.workflow_run.event == 'workflow_dispatch') + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: write # compare-and-swap push of the shared coordination ref + actions: write # cancel doomed PR runs, dispatch triage probes, read logs and artifacts + issues: write # one incident issue per record; flake issues + pull-requests: write # report squashes that landed while red + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.repository.default_branch }} + fetch-depth: 0 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: "1.4.2" + - run: bun install --frozen-lockfile + - name: Coordinate the red-main record + env: + GH_TOKEN: ${{ github.token }} + run: bun scripts/red-main-cli.ts coordinate + - name: Retain recorded incident events + if: always() + uses: actions/upload-artifact@v7 + with: + name: red-main-events + path: tmp/red-main-events/ + if-no-files-found: ignore + retention-days: 90 diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 4cfcd14633..3e361a4f69 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1423,6 +1423,70 @@ Each implementation task is tracked separately: - automatic epochs: [#3270](https://github.com/schlessera/brain-kit/issues/3270); - off-main qualification evidence: [#3271](https://github.com/schlessera/brain-kit/issues/3271). +### Red-main record and coordinator + +The [2026-10-25 red-main and coordination decisions](https://github.com/schlessera/brain-kit/issues/2934#issuecomment-6402400614) +are implemented by [#2942](https://github.com/schlessera/brain-kit/issues/2942): + +- **Strict flake handling.** A rerun is only a triage probe that decides whether + main is declared red. It never turns proof green or makes anything mergeable. + It always files or updates an issue on the test, and a second suspected flake + on one test within seven days is treated as real. "Never rerun a real failure" + stays. +- **A red main stops doomed work.** Hosted proof whose merge ref contains the + bad commit is refused or cancelled, except declared fixes. Draft heavy + feedback runs the same gate on its requested head. Each machine keeps its own + resources for a fix it is building. +- **Coordination runs on GitHub.** A coordinator workflow on main CI completion + and the shared reservation ref hold the repository-level record. Orchestrators + read and enforce it and never message each other. +- **Merge blocking while red is cooperative, plus detection.** `integrate.ts` + refuses non-fix confirmation and merges. Any squash that lands anyway is + reported on its PR and on the incident. There is no repository ruleset. +- **Several declared fixes** may exist for one incident; the first whose fix is + confirmed wins. +- **One incident issue per record**, created once by the coordinator. + +The record is `red-main.json`, stored beside `reservation.json` in the same +coordination ref and updated with the same exact `--force-with-lease` +compare-and-swap. A write to either file preserves the other. It holds the +first bad SHA, the failing tests and categories with the estimator's reasons, +the opening run, the incident issue, the declared fix PRs, the squashes already +reported, and a bounded ledger of suspected flakes. +`bun scripts/integrate.ts main-status --json` reads it, and +`declare-fix ` adds a fix. It is leakage-screened like the reservation. + +The estimator is deterministic. It decides from the failing test's membership +in the squash's own affected closure (an unknown closure counts as inside), +the error signature from JUnit (timeout or assertion), environment-setup step +failure, and earlier suspicions within the window. A suspected flake reruns +only its failing test files at that SHA through `red-main-probe.yml`. A real +failure opens the record. The first bad SHA is the first commit after the last +main run where the failing category actually ran green. When that range has +2–10 commits, probes rerun only the failing test files at each candidate and +narrow it; a wider range keeps the conservative first candidate. + +Main runs run their selected proof even when the metadata job fails. Each main +run selects its own affected set plus every test and category in the open +record. All of its jobs read one pinned coordination snapshot, and the +metadata job prints the included set. The record is cleared only by a green +main run that printed the same open record as included. The first step of a +non-draft PR run refuses with `main red at , incident #` when its merge +ref contains the bad commit and the PR is not a declared fix. Draft runs keep +their cheap gates. The coordinator also cancels queued and running PR proof +created after the bad commit landed, except declared fixes. A non-fix squash +that lands while red is reported once on its PR and on the incident, and +recorded as an `incident` event through `scripts/ci-timings.ts record` in the +coordinator's `red-main-events` artifact. + +`red-main.yml` declares no workflow-level permissions. Its one job has +`contents: write` (the coordination ref), `actions: write` (cancel doomed PR +runs, dispatch probes, read logs and artifacts), `issues: write` (incident and +flake issues) and `pull-requests: write` (landed-while-red reports). It runs +trusted default-branch tooling and parses candidate logs and artifacts as data. +`red-main-probe.yml` has `contents: read` only. The incident workflow in the +skills is #2944, and the expedited fix merge is #2940. + ### Hosted heavy feedback on draft heads The [#2939 ruling](https://github.com/schlessera/brain-kit/issues/2939#issuecomment-6403978097) diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 5cf4074f1a..30d9115f97 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -318,7 +318,7 @@ name instead of repeating the numbers. Two mechanisms hang off it: fails in both. A path hard-coded to the root `node_modules` could read a different copy from the one the backend loads. CI installs with `--frozen-lockfile` (`bun install --frozen-lockfile`, - `.github/workflows/ci.yml:52`), so the guard compares the lockfile-installed pair. + `.github/workflows/ci.yml:53`), so the guard compares the lockfile-installed pair. This fast version guard remains an affected automatic check under [the current CI policy](ci-utility.md); changing the SDK requires fresh local runtime measurements before updating the constant. It needs no key and no diff --git a/scripts/check-ci-workflows.ts b/scripts/check-ci-workflows.ts index 53c1246203..d8ba1a0082 100644 --- a/scripts/check-ci-workflows.ts +++ b/scripts/check-ci-workflows.ts @@ -57,7 +57,9 @@ export function workflowProblems(text: string, file: string): string[] { const job = workflow.jobs?.[name]; if (job?.needs !== "changeset") fail(`${name}: independent proof must depend only on metadata`); const selection = `needs.changeset.outputs.${name} == 'true'` + (["browser", "layout"].includes(name) ? ` && needs.changeset.outputs.run_${name} == 'true'` : ""); - if (job?.if !== selection) fail(`${name}: proof must use its explicit planner selection and validated retention`); + // Main pushes run selected proof even when the metadata job fails (#2942); + // PR proof still requires a successful metadata job. + if (job?.if !== `\${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && ${selection} }}`) fail(`${name}: proof must use its explicit planner selection and validated retention`); } const verify = workflow.jobs?.verify; const verifySteps = verify?.steps ?? []; @@ -126,11 +128,12 @@ export function checkCIWorkflows(root: string): string[] { const problems: string[] = []; const directory = join(root, ".github/workflows"); const files = existsSync(directory) ? readdirSync(directory).sort() : []; - const expected = ["ci.yml", "contract.yml", "project-sync.yml"]; + // The red-main coordinator and its triage probe are authoritative coordination (#2942). + const expected = ["ci.yml", "contract.yml", "project-sync.yml", "red-main.yml", "red-main-probe.yml"]; if (files.includes("publish-pages.yml")) expected.push("publish-pages.yml"); if (files.includes("ci-timings.yml")) expected.push("ci-timings.yml"); if (files.includes("heavy-feedback.yml")) expected.push("heavy-feedback.yml"); - if (JSON.stringify(files) !== JSON.stringify(expected.sort())) problems.push("GitHub must contain only authoritative CI, contract, project-sync and optional Pages/timing workflows"); + if (JSON.stringify(files) !== JSON.stringify(expected.sort())) problems.push("GitHub must contain only authoritative CI, contract, project-sync, red-main coordination and optional Pages/timing/heavy-feedback workflows"); const depot = join(root, ".depot/workflows"); if (existsSync(depot) && readdirSync(depot).some(file => /\.ya?ml$/.test(file))) problems.push("Active Depot CI workflow definitions must be removed"); for (const file of CI_WORKFLOWS) { diff --git a/scripts/ci-coordination.ts b/scripts/ci-coordination.ts index d965261006..20fbd2cc66 100644 --- a/scripts/ci-coordination.ts +++ b/scripts/ci-coordination.ts @@ -67,6 +67,8 @@ export function collectReservationHistory(repository: string, since: string): Re const commits = run(["rev-list", "--first-parent", remote]).split("\n"), rows: { source: string; state: any }[] = []; for (const source of commits) { const state = parseReservation(run(["show", `${source}:reservation.json`])); + // Red-main record writes (#2942) share this ref and leave reservation.json unchanged. + if (rows.length && JSON.stringify(rows.at(-1)!.state) === JSON.stringify(state)) { rows[rows.length - 1] = { source, state }; continue; } rows.push({ source, state }); // The protocol caps leases at one hour. Keep the preceding source record. // Server timestamps drive this bound; commit author clocks do not. diff --git a/scripts/ci-plan.ts b/scripts/ci-plan.ts index c9aaf7cb89..ce7130ee3b 100644 --- a/scripts/ci-plan.ts +++ b/scripts/ci-plan.ts @@ -4,6 +4,8 @@ import { basename, dirname, join, relative, resolve } from "node:path"; import ts from "typescript"; import { closureSelects, discoverBrowserClosures, type BrowserClosures } from "./browser-input-closure"; import { addUnitImportConsumers, type UnitImportGraph } from "./unit-test-consumers"; +import { coordinationFiles, RESERVATION_REF } from "./integration-reservation"; +import { includeRedSet, type IncludedRedSet, type RedMainRecord } from "./red-main"; export interface Workspace { dir: string; @@ -144,6 +146,8 @@ export interface CheckPlan { unitTests?: string[]; // Complete proof categories, shared by hosted CI and opt-in full local checks. local: { fullTests: boolean; browser: boolean; layout: boolean; captures: boolean; runtime: boolean; endurance: boolean }; + /** Main pushes also prove the open red-main record's failures (#2942). */ + redMain?: IncludedRedSet; } export function workspaces(root: string): Workspace[] { @@ -443,20 +447,40 @@ export function changedFiles(root: string, base: string, head = "HEAD", mergeBas return [...new Set(paths)].sort(); } -export function planFromEnvironment(root: string, env: NodeJS.ProcessEnv): CheckPlan { +export function planFromEnvironment(root: string, env: NodeJS.ProcessEnv, redMain: RedMainRecord | null = null): CheckPlan { // Draft heavy feedback plans its PR's affected selection against the PR base (#3272). const feedback = env.GITHUB_EVENT_NAME === "workflow_dispatch" && Boolean(env.FEEDBACK_PR); if (!feedback && ["api", "schedule", "workflow_dispatch"].includes(env.GITHUB_EVENT_NAME ?? "")) return planChecks(["package.json"], workspaces(root), root); const pr = feedback || env.GITHUB_EVENT_NAME === "pull_request"; const base = pr ? env.BASE_SHA : env.BEFORE_SHA; if (!base || !env.HEAD_SHA) throw new Error("CI requires BASE_SHA/BEFORE_SHA and HEAD_SHA"); - return planChecks(changedFiles(root, base, env.HEAD_SHA, pr), workspaces(root), root, pr); + const packages = workspaces(root), plan = planChecks(changedFiles(root, base, env.HEAD_SHA, pr), packages, root, pr); + return env.GITHUB_EVENT_NAME === "push" ? includeRedSet(plan, redMain, changed => planChecks(changed, packages, root, false)) : plan; +} + +/** + * Every job of one main run reads the same coordination snapshot: the + * metadata job resolves it once and later jobs receive its object ID. + */ +export function redMainSnapshot(root: string, requested: string | undefined): { oid: string; record: RedMainRecord | null } { + const attempt = (args: string[]) => { + for (let index = 0; ; index++) { + try { return git(root, args).trim(); } catch (error) { if (index === 2) throw error; Bun.sleepSync(1000 * 2 ** index); } + } + }; + let oid = requested; + if (!oid) oid = attempt(["ls-remote", "--refs", "origin", RESERVATION_REF]).split(/\s+/)[0] || "none"; + if (oid === "none") return { oid, record: null }; + if (!/^[a-f0-9]{40}$/.test(oid)) throw new Error("Invalid red-main coordination snapshot"); + attempt(["fetch", "--no-tags", "origin", oid]); + return { oid, record: coordinationFiles(git(root, ["ls-tree", oid]), name => git(root, ["show", `${oid}:${name}`])).redMain }; } if (import.meta.main) { try { const root = resolve(import.meta.dir, ".."); - const plan = planFromEnvironment(root, process.env); + const red = process.env.GITHUB_EVENT_NAME === "push" ? redMainSnapshot(root, process.env.RED_MAIN_OID) : null; + const plan = planFromEnvironment(root, process.env, red?.record ?? null); if (process.env.GITHUB_ACTIONS === "true" && !process.env.GITHUB_EVENT_PATH) throw new Error("Hosted proof requires GITHUB_EVENT_PATH"); // Standalone planner diagnostics preserve complete selection; only an actual // event requests hosted confirmation, enforced again by the final gate. @@ -468,12 +492,14 @@ if (import.meta.main) { const selections = proofSelections(plan, draft); if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `unit_shards=${JSON.stringify(unitShards(plan))}\n` + - `cadence=${plan.cadence ?? "diagnostic"}\n` + Object.entries(selections).map(([name, selected]) => `${name}=${selected}\n`).join("")); + `cadence=${plan.cadence ?? "diagnostic"}\n` + `red_main_oid=${red?.oid ?? ""}\n` + Object.entries(selections).map(([name, selected]) => `${name}=${selected}\n`).join("")); console.log(JSON.stringify({ ...plan, draft, event: event && { name: process.env.GITHUB_EVENT_NAME, action: event.action, head: event.pull_request?.head?.sha ?? process.env.GITHUB_SHA, base: event.pull_request?.base?.sha ?? event.before, } }, null, 2)); + // The coordinator clears a record only from a green run that printed it here. + if (plan.redMain) console.log(`BRAIN_RED_MAIN_INCLUDED ${JSON.stringify(plan.redMain)}`); if (event) console.log(`BRAIN_TIMING_CONTEXT ${JSON.stringify({ cadence: plan.cadence, global: plan.global, head: event.pull_request?.head?.sha ?? process.env.GITHUB_SHA })}`); } catch (error) { console.error(error); process.exit(1); } diff --git a/scripts/heavy-feedback-workflow.ts b/scripts/heavy-feedback-workflow.ts index cf70ec5d1a..c5d32b331c 100644 --- a/scripts/heavy-feedback-workflow.ts +++ b/scripts/heavy-feedback-workflow.ts @@ -45,6 +45,9 @@ export function renderHeavyFeedbackWorkflow(ciText: string): string { const checkout = pinned(metadata, "actions/checkout"), bun = pinned(metadata, "oven-sh/setup-bun"); const install = metadata.steps.find(s => s.run === "bun install --frozen-lockfile"); if (!install) throw new Error("ci.yml changeset job lost its frozen install"); + // Feedback on a head that contains main's recorded bad commit is doomed too (#2942). + const redMain = metadata.steps.find(s => s.run === "bun scripts/red-main-cli.ts gate"); + if (!redMain) throw new Error("ci.yml changeset job lost its red-main gate"); const request = { FEEDBACK_PR: "${{ inputs.pr }}", FEEDBACK_HEAD_SHA: HEAD, GH_TOKEN: "${{ github.token }}" }; const outputs = { ...clone(metadata.outputs), base_sha: "${{ steps.admit.outputs.base_sha }}" }; delete outputs.reuse; // Feedback never retains or records proof. @@ -79,6 +82,7 @@ export function renderHeavyFeedbackWorkflow(ciText: string): string { { name: "Refuse a stale, ready, closed or foreign head; yield to ready confirmation", id: "admit", env: request, run: "bun scripts/heavy-feedback.ts admit" }, { ...clone(checkout), with: { ...checkout.with, "fetch-depth": 0, ref: HEAD } }, clone(install), + { name: redMain.name, env: { PR_NUMBER: "${{ inputs.pr }}" }, run: redMain.run }, { name: "Plan the PR's affected selection with feedback-heavy cadence", id: "plan", env: { BASE_SHA: "${{ steps.admit.outputs.base_sha }}", HEAD_SHA: HEAD, FEEDBACK_PR: "${{ inputs.pr }}" }, run: "bun scripts/ci-plan.ts" }, { name: "Select fresh browser and layout execution", id: "reuse", run: "bun scripts/proof-reuse.ts" }, diff --git a/scripts/integrate.ts b/scripts/integrate.ts index d84eec0d59..7ce6539951 100644 --- a/scripts/integrate.ts +++ b/scripts/integrate.ts @@ -4,6 +4,7 @@ import { scanText } from "./check-leakage"; import { GitReservationStore, assertLease, liveLease, reservationServerTime, reservationTransition, RENEW_MS, sameCandidate, type Candidate, type Operation, type Lease } from "./integration-reservation"; import { latestIntegrationRun, verifyIntegrationProof } from "./integration-proof"; +import { declareFix, type RedMainRecord } from "./red-main"; import type { API } from "./proof-reuse"; async function gh(...args: string[]): Promise { @@ -53,6 +54,21 @@ if (import.meta.main) { } throw new Error("Bounded acquisition exhausted"); } + /** Cooperative merge blocking while red (#2942): only a declared fix proceeds. */ + function refuseWhileRed(pr: number) { + const open = store!.read().redMain.open; + if (open && !open.fixes.includes(pr)) throw new Error(`main red at ${open.firstBad}, ${open.incident ? `incident #${open.incident}` : "incident pending"}; only a declared fix may confirm or merge (bun scripts/integrate.ts declare-fix )`); + } + async function changeRedMain(update: (record: RedMainRecord, now: number) => RedMainRecord) { + for (let attempt = 0; attempt < 3; attempt++) { + const snapshot = store!.read(), record = update(snapshot.redMain, await clock()); + if (record === snapshot.redMain) return record; + if (scanText("coordination", JSON.stringify(record)).length) throw new Error("Public coordination state failed the leakage gate"); + if (store!.publishRedMain(snapshot, record)) return record; + await Bun.sleep(100 * 2 ** attempt); + } + throw new Error("Concurrent coordination update; bounded retries exhausted"); + } function heartbeat() { timer = setInterval(() => { pending = pending.then(async () => { if (!lost) try { await renew(); } catch (error) { lost = error; } }); return pending; }, RENEW_MS); } @@ -79,6 +95,7 @@ if (import.meta.main) { await milestones(desired.pr, issueRefs); await stopHeartbeat(); if (lost) throw lost; + refuseWhileRed(desired.pr); if (!sameCandidate(await candidate(desired.pr), desired)) throw new Error("Candidate changed before merge"); assertLease(store!.read().state, own.id, actor, desired, await clock()); await gh("pr", "merge", String(desired.pr), "--repo", repository, "--squash", "--match-head-commit", desired.head); @@ -109,7 +126,16 @@ if (import.meta.main) { store = new GitReservationStore(process.cwd()); const remote = store.git(["remote", "get-url", "origin"]).replace(/^git@github.com:/, "https://github.com/").replace(/\.git$/, ""); if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) || remote !== `https://github.com/${repository}`) throw new Error("Authenticated repository and origin differ"); - if (command === "inspect") { + if (command === "main-status") { + if (target !== undefined && target !== "--json") throw new Error("usage: bun scripts/integrate.ts main-status [--json]"); + const snapshot = store.read(); + console.log(JSON.stringify({ red: snapshot.redMain.open !== null, source: snapshot.oid, record: snapshot.redMain })); + } else if (command === "declare-fix") { + if (!/^[1-9]\d*$/.test(target ?? "") || !Number.isSafeInteger(Number(target))) throw new Error("A PR number is required"); + const live = await api.json(`pulls/${target}`); + if (live.state !== "open" || live.base?.ref !== "main" || live.base?.repo?.full_name !== repository) throw new Error("Only an open PR against main can be declared a red-main fix"); + console.log(JSON.stringify(await changeRedMain((record, now) => declareFix(record, Number(target), now)))); + } else if (command === "inspect") { const snapshot = store.read(), now = await clock(); console.log(JSON.stringify({ ...snapshot, live: liveLease(snapshot.state.active, now), serverTime: now })); } else if (command === "revoke") { @@ -128,6 +154,7 @@ if (import.meta.main) { if (current && current.id === values.get("--lease") && current.actor === actor && current.candidate.pr === Number(target) && current.candidate.repository === `https://github.com/${repository}`) own = current; } const desired = await candidate(Number(target)); + refuseWhileRed(desired.pr); if (command === "merge") { const lease = values.get("--lease"); if (!lease) throw new Error("Explicit --lease required"); @@ -162,7 +189,7 @@ if (import.meta.main) { if (lost) throw lost; } } - } else throw new Error("usage: bun scripts/integrate.ts inspect | acquire/confirm/merge [--lease id] [--issues owner/repo#N,...] | renew/release | revoke "); + } else throw new Error("usage: bun scripts/integrate.ts inspect | main-status [--json] | declare-fix | acquire/confirm/merge [--lease id] [--issues owner/repo#N,...] | renew/release | revoke "); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; } finally { diff --git a/scripts/integration-reservation.ts b/scripts/integration-reservation.ts index d5716406c6..27b05e2338 100644 --- a/scripts/integration-reservation.ts +++ b/scripts/integration-reservation.ts @@ -1,5 +1,6 @@ /** Cooperative integration ownership: remote Git CAS, never a branch lock. */ import { randomBytes } from "node:crypto"; +import { emptyRedMain, parseRedMain, RED_MAIN_FILE, type RedMainRecord } from "./red-main"; export const RESERVATION_REF = "refs/heads/brain-integration-reservation"; export const LEASE_MS = 5 * 60_000, RENEW_MS = 60_000, MAX_MS = 60 * 60_000; @@ -9,7 +10,8 @@ export interface ReservationState { version: 1; updated: number; active: Lease | null; last: { action: "acquire" | "renew" | "release" | "revoke"; actor: number; at: number; previous: Lease | null; reason?: string } | null; } -export interface Snapshot { oid: string | null; state: ReservationState; } +/** One ref commit holds both coordination files; every write preserves the other one. */ +export interface Snapshot { oid: string | null; state: ReservationState; redMain?: RedMainRecord; } export type Operation = { kind: "acquire"; candidate: Candidate; id?: string } | { kind: "renew"; id: string } | { kind: "release"; id: string } | { kind: "revoke"; reason: string; maintainer: boolean }; const hash = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{40}$/.test(value); @@ -94,19 +96,25 @@ export class GitReservationStore { if (!hash(oid) || ref !== this.ref || extra.length) throw new Error("Invalid remote reservation ref"); return oid; } - read(): Snapshot { + read(): Snapshot & { redMain: RedMainRecord } { const oid = this.remoteOid(); - if (!oid) return { oid, state: emptyReservation() }; + if (!oid) return { oid, state: emptyReservation(), redMain: emptyRedMain() }; this.git(["fetch", "--no-tags", this.remote, oid]); - const tree = this.git(["ls-tree", oid]); - if (!/^100644 blob [a-f0-9]{40}\treservation\.json$/.test(tree)) throw new Error("Unknown shared coordination tree"); - return { oid, state: parseReservation(this.git(["show", `${oid}:reservation.json`])) }; + return { oid, ...coordinationFiles(this.git(["ls-tree", oid]), name => this.git(["show", `${oid}:${name}`])) }; } publish(snapshot: Snapshot, state: ReservationState): boolean { - const content = JSON.stringify(parseReservation(JSON.stringify(state))) + "\n"; - const blob = this.git(["hash-object", "-w", "--stdin"], content); - const tree = this.git(["mktree"], `100644 blob ${blob}\treservation.json\n`); - const oid = this.git(["commit-tree", tree, ...(snapshot.oid ? ["-p", snapshot.oid] : []), "-m", `integration: ${state.last?.action ?? "state"}`]); + return this.write(snapshot, parseReservation(JSON.stringify(state)), snapshot.redMain ?? emptyRedMain(), `integration: ${state.last?.action ?? "state"}`); + } + publishRedMain(snapshot: Snapshot, record: RedMainRecord): boolean { + return this.write(snapshot, snapshot.state, parseRedMain(JSON.stringify(record)), `red-main: ${record.last?.action ?? "state"}`); + } + private write(snapshot: Snapshot, state: ReservationState, redMain: RedMainRecord, message: string): boolean { + const blob = (value: unknown) => this.git(["hash-object", "-w", "--stdin"], JSON.stringify(value) + "\n"); + const entries = [`100644 blob ${blob(state)}\treservation.json`]; + // An untouched red-main record is not materialized, so reservation-only history keeps its shape. + if (redMain.last !== null) entries.unshift(`100644 blob ${blob(redMain)}\t${RED_MAIN_FILE}`); + const tree = this.git(["mktree"], entries.join("\n") + "\n"); + const oid = this.git(["commit-tree", tree, ...(snapshot.oid ? ["-p", snapshot.oid] : []), "-m", message]); try { this.git(["push", "--porcelain", `--force-with-lease=${this.ref}:${snapshot.oid ?? ""}`, this.remote, `${oid}:${this.ref}`]); return true; @@ -116,3 +124,14 @@ export class GitReservationStore { } } } + +/** Accepts exactly the known coordination files; anything else fails closed. */ +export function coordinationFiles(tree: string, show: (name: string) => string): { state: ReservationState; redMain: RedMainRecord } { + const names = tree.split("\n").filter(Boolean).map(line => { + const match = /^100644 blob [a-f0-9]{40}\t(reservation\.json|red-main\.json)$/.exec(line); + if (!match) throw new Error("Unknown shared coordination tree"); + return match[1]!; + }); + if (!names.includes("reservation.json") || new Set(names).size !== names.length) throw new Error("Unknown shared coordination tree"); + return { state: parseReservation(show("reservation.json")), redMain: names.includes(RED_MAIN_FILE) ? parseRedMain(show(RED_MAIN_FILE)) : emptyRedMain() }; +} diff --git a/scripts/red-main-cli.ts b/scripts/red-main-cli.ts new file mode 100644 index 0000000000..89f3dacbf0 --- /dev/null +++ b/scripts/red-main-cli.ts @@ -0,0 +1,135 @@ +/** + * Red-main entry points (#2942): + * gate first step of PR proof: refuse doomed hosted proof while main is red + * coordinate workflow_run handler for main CI and triage probes + * probe rerun only the named test files at one SHA (triage, never proof) + */ +import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { changedFiles, planChecks, proofSelections, redMainSnapshot, workspaces } from "./ci-plan"; +import { GitReservationStore, reservationServerTime, type Snapshot as StoreSnapshot } from "./integration-reservation"; +import { coordinate, type CoordinatorIO, type WorkflowRun } from "./red-main-coordinator"; +import { gateDecision, type Category } from "./red-main"; + +// Hosted jobs run from the checkout root; fixtures run from their own repository. +const root = process.cwd(); + +function run(argv: string[], cwd = root, input?: string): { code: number; out: string; err: string } { + const result = Bun.spawnSync(argv, { cwd, stdout: "pipe", stderr: "pipe", stdin: input === undefined ? "ignore" : new TextEncoder().encode(input) }); + return { code: result.exitCode ?? 1, out: new TextDecoder().decode(result.stdout), err: new TextDecoder().decode(result.stderr) }; +} +function must(argv: string[], cwd = root, input?: string): string { + const result = run(argv, cwd, input); + if (result.code !== 0) throw new Error(`${argv.slice(0, 3).join(" ")} failed: ${result.err.trim()}`); + return result.out.trim(); +} + +/** Ancestry with an on-demand fetch; anything other than a definite answer fails closed. */ +export function isAncestor(ancestor: string, descendant: string, cwd = root): boolean { + for (const sha of [ancestor, descendant]) if (sha !== "HEAD" && run(["git", "cat-file", "-e", `${sha}^{commit}`], cwd).code !== 0) must(["git", "fetch", "--no-tags", "origin", sha], cwd); + const result = run(["git", "merge-base", "--is-ancestor", ancestor, descendant], cwd); + if (result.code === 0 || result.code === 1) return result.code === 0; + throw new Error(`Cannot determine ancestry: ${result.err.trim()}`); +} + +/** Whether a failure belongs to the squash's own affected closure; null when the graph cannot say. */ +export function inClosure(sha: string, failure: { test: string | null; category: Category }): boolean | null { + try { + const parent = must(["git", "rev-parse", `${sha}^`]); + const plan = planChecks(changedFiles(root, parent, sha, false), workspaces(root), root, true); + if (plan.global) return null; + if (failure.test) { + if (plan.unitTests) return plan.unitTests.includes(failure.test); + const dir = /^packages\/([^/]+)\//.exec(failure.test)?.[1]; + return dir ? plan.local.fullTests && plan.affected.includes(dir) : null; + } + if (failure.category === "changeset") return true; + return proofSelections({ ...plan, cadence: "integrated" })[failure.category] ?? null; + } catch { return null; } +} + +async function gh(args: string[], input?: string): Promise { + const child = Bun.spawn(["gh", ...args], { stdout: "pipe", stderr: "pipe", stdin: input === undefined ? "ignore" : new TextEncoder().encode(input) }); + const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + if (code !== 0) throw new Error(`gh ${args.slice(0, 2).join(" ")} failed: ${err.trim()}`); + return out; +} + +function liveIO(repository: string): CoordinatorIO { + const store = new GitReservationStore(root); + return { + repository, + async json(path) { return JSON.parse(await gh(["api", path])); }, + async write(method, path, body) { + const out = await gh(["api", "-X", method, path, ...(body === undefined ? [] : ["--input", "-"])], body === undefined ? undefined : JSON.stringify(body)); + return out.trim() ? JSON.parse(out) : {}; + }, + async now() { return reservationServerTime(await gh(["api", "--include", "-H", "Cache-Control: no-cache", `repos/${repository}/git/ref/heads/main?red_main_clock=${crypto.randomUUID()}`])); }, + read() { return store.read(); }, + publish(snapshot, record) { return store.publishRedMain(snapshot as StoreSnapshot, record); }, + async artifactFiles(runId, name, file) { + const listing = JSON.parse(await gh(["api", `repos/${repository}/actions/runs/${runId}/artifacts?per_page=100`])); + if (!(listing.artifacts ?? []).some((artifact: { name: string; expired: boolean }) => artifact.name === name && !artifact.expired)) return []; + const dir = mkdtempSync(join(tmpdir(), "red-main-artifact-")); + try { + await gh(["run", "download", String(runId), "--repo", repository, "--name", name, "--dir", dir]); + const found: string[] = []; + const walk = (path: string) => { for (const entry of readdirSync(path)) { const full = join(path, entry); if (statSync(full).isDirectory()) walk(full); else if (entry === file) found.push(readFileSync(full, "utf8")); } }; + walk(dir); + return found; + } finally { rmSync(dir, { recursive: true, force: true }); } + }, + async log(job) { return gh(["api", "--allow-escape-sequences", `repos/${repository}/actions/jobs/${job}/logs`]); }, + inClosure, + range(since, until) { return must(["git", "rev-list", "--first-parent", "--reverse", `${since}..${until}`]).split("\n").filter(Boolean); }, + isAncestor: (a, b) => isAncestor(a, b), + commitTime(sha) { return Number(must(["git", "show", "-s", "--format=%ct", sha])) * 1000; }, + async recordEvent(event) { + const dir = join(root, "tmp/red-main-events"), file = join(dir, `input-${crypto.randomUUID()}.json`); + await Bun.write(file, JSON.stringify(event)); + must([process.execPath, "scripts/ci-timings.ts", "record", "--repo", repository, "--event", file, "--out", dir]); + rmSync(file); + }, + print(line) { console.log(line); }, + }; +} + +if (import.meta.main) { + try { + const [command, ...rest] = process.argv.slice(2); + if (command === "gate") { + const pr = Number(process.env.PR_NUMBER); + if (!Number.isSafeInteger(pr) || pr <= 0) throw new Error("PR_NUMBER is required"); + const { record } = redMainSnapshot(root, undefined); + const decision = record ? gateDecision({ record, pr, contains: sha => isAncestor(sha, "HEAD") }) : { refuse: false, message: "main green: no coordination record" }; + if (decision.refuse) { console.error(`::error::${decision.message}`); console.error(decision.message); process.exit(1); } + console.log(decision.message); + } else if (command === "coordinate" && rest[0] === "--dry-run") { + // Read-only replay against a recorded run: every write is printed, none is sent. + const id = rest[rest.indexOf("--run") + 1] ?? "", repository = must(["gh", "repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"]); + if (!/^[1-9]\d*$/.test(id)) throw new Error("usage: coordinate --dry-run --run "); + const io = liveIO(repository), seen = io.read(); + let record = seen.redMain; + const run = await io.json(`repos/${repository}/actions/runs/${id}`) as WorkflowRun; + await coordinate({ ...io, + read: () => ({ ...seen, redMain: record }), + publish(_snapshot, next) { record = next; console.log(`DRY_RUN record ${JSON.stringify(next)}`); return true; }, + async write(method, path, body) { console.log(`DRY_RUN ${method} ${path} ${JSON.stringify(body ?? null)}`); return { number: 999_999 }; }, + async recordEvent(event) { console.log(`DRY_RUN event ${JSON.stringify(event)}`); }, + }, run); + } else if (command === "coordinate") { + const event = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH!, "utf8")); + const repository = process.env.GITHUB_REPOSITORY!; + if (!event.workflow_run || !/^[\w.-]+\/[\w.-]+$/.test(repository ?? "")) throw new Error("A workflow_run event and repository are required"); + await coordinate(liveIO(repository), event.workflow_run as WorkflowRun); + } else if (command === "probe") { + const target = resolve(rest[rest.indexOf("--target") + 1] ?? ""); + const tests = JSON.parse(process.env.PROBE_TESTS ?? "[]") as unknown; + if (!Array.isArray(tests) || !tests.length || tests.length > 50 || tests.some(test => typeof test !== "string" || + !/^[A-Za-z0-9_./@-]+\.test\.[cm]?[jt]sx?$/.test(test) || test.split("/").includes("..") || !existsSync(join(target, test)))) throw new Error("Probe tests must be existing test files at the probed SHA"); + const child = Bun.spawn([process.execPath, "run", "test", ...tests], { cwd: target, stdout: "inherit", stderr: "inherit" }); + process.exit(await child.exited); + } else throw new Error("usage: bun scripts/red-main-cli.ts gate | coordinate [--dry-run --run ] | probe --target "); + } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); } +} diff --git a/scripts/red-main-coordinator.ts b/scripts/red-main-coordinator.ts new file mode 100644 index 0000000000..67b23f45e4 --- /dev/null +++ b/scripts/red-main-coordinator.ts @@ -0,0 +1,281 @@ +/** + * Red-main coordinator (#2942): runs on every completed main CI run and every + * triage probe. It records a red main in the shared coordination ref, files one + * incident issue, cancels doomed PR proof and reports squashes that land while red. + * A rerun is only a triage probe: it never turns proof green or makes anything mergeable. + */ +import { scanText } from "./check-leakage"; +import { addSuspect, attachIncident, CATEGORIES, classifyFailure, clearRed, coversRedSet, failureKey, junitFailures, openRed, refineFirstBad, + reportLanded, settleSuspect, type Category, type FailureEvidence, type IncludedRedSet, type RedFailure, type RedMainRecord, type Signature } from "./red-main"; + +export const PROBE_WORKFLOW = "red-main-probe.yml"; +/** Bisect only bounded ranges; a wider range keeps the conservative first red. */ +export const MAX_BISECT = 10; +const SETUP_STEP = /prerequisites|environment setup/i; + +export interface WorkflowRun { + id: number; name: string; event: string; head_branch: string; head_sha: string; status: string; conclusion: string | null; + run_attempt: number; display_title: string; created_at: string; pull_requests?: { number: number }[]; +} +export interface Job { id: number; name: string; conclusion: string | null; steps?: { name: string; conclusion: string | null }[]; } +export interface Snapshot { oid: string | null; redMain: RedMainRecord; } +export interface CoordinatorIO { + repository: string; + json(path: string): Promise; + write(method: "POST" | "PATCH", path: string, body?: unknown): Promise; + /** Authoritative GitHub server time. */ + now(): Promise; + read(): Snapshot; + publish(snapshot: Snapshot, record: RedMainRecord): boolean; + /** Text of every named file inside the run's artifacts matching the prefix. */ + artifactFiles(run: number, prefix: string, file: string): Promise; + log(job: number): Promise; + /** Whether a failing test or category belongs to the commit's own affected closure; null when unknown. */ + inClosure(sha: string, failure: { test: string | null; category: Category }): boolean | null; + /** First-parent main commits after `since` (exclusive) up to `until` (inclusive), oldest first. */ + range(since: string, until: string): string[]; + isAncestor(ancestor: string, descendant: string): boolean; + commitTime(sha: string): number; + recordEvent(event: { kind: "incident"; pr: number; run: number; evidence: string }): Promise; + print(line: string): void; +} + +const short = (sha: string) => sha.slice(0, 12); +const issueUrl = (io: CoordinatorIO, number: number) => `https://github.com/${io.repository}/issues/${number}`; +const runUrl = (io: CoordinatorIO, run: number) => `https://github.com/${io.repository}/actions/runs/${run}`; +/** Keyed by the record's opening run: bisect may later move its first bad SHA. */ +export const incidentMarker = (run: number) => ``; +export const flakeMarker = (key: string) => ``; + +/** Retries a compare-and-swap update of the shared record; an unchanged result writes nothing. */ +export async function updateRecord(io: CoordinatorIO, update: (record: RedMainRecord, now: number) => RedMainRecord): Promise<{ before: RedMainRecord; after: RedMainRecord }> { + for (let attempt = 0; attempt < 5; attempt++) { + const snapshot = io.read(), after = update(snapshot.redMain, await io.now()); + if (after === snapshot.redMain) return { before: snapshot.redMain, after }; + if (scanText("coordination", JSON.stringify(after)).length) throw new Error("Public coordination state failed the leakage gate"); + if (io.publish(snapshot, after)) return { before: snapshot.redMain, after }; + await Bun.sleep(200 * 2 ** attempt); + } + throw new Error("Concurrent red-main update; bounded retries exhausted"); +} + +export function jobCategory(name: string): Category | null { + const base = name.split(" ")[0]!; + return CATEGORIES.includes(base as Category) ? base as Category : null; +} + +/** Failures of one completed main run, with their deterministic estimator evidence. */ +export async function runFailures(io: CoordinatorIO, run: WorkflowRun, jobs: Job[]): Promise { + const out: FailureEvidence[] = []; + for (const job of jobs.filter(job => job.conclusion === "failure" || job.conclusion === "timed_out")) { + const category = jobCategory(job.name); + if (!category) continue; + const setup = job.steps?.some(step => SETUP_STEP.test(step.name) && step.conclusion === "failure"); + const fallback: Signature = setup ? "setup" : job.conclusion === "timed_out" ? "timeout" : "unknown"; + if (category === "unit" && !setup) { + const shard = /\((\d+)\)/.exec(job.name)?.[1]; + const reports = shard ? await io.artifactFiles(run.id, `unit-proof-${shard}`, "unit-report.xml") : []; + const tests = reports.flatMap(junitFailures); + if (tests.length) { + for (const { test, signature } of tests) out.push({ test, category, signature, inClosure: io.inClosure(run.head_sha, { test, category }) }); + continue; + } + } + if (!out.some(f => f.test === null && f.category === category)) out.push({ test: null, category, signature: fallback, inClosure: io.inClosure(run.head_sha, { test: null, category }) }); + } + return out; +} + +/** Parses the exact record snapshot a main run printed as included in its selection. */ +export function includedRedSet(log: string): IncludedRedSet | null { + const line = log.split("\n").find(entry => entry.includes("BRAIN_RED_MAIN_INCLUDED ")); + if (!line) return null; + try { return JSON.parse(line.slice(line.indexOf("BRAIN_RED_MAIN_INCLUDED ") + 24)); } catch { return null; } +} + +async function search(io: CoordinatorIO, query: string): Promise<{ number: number; title: string; body?: string }[]> { + const result = await io.json(`search/issues?q=${encodeURIComponent(`repo:${io.repository} is:issue is:open ${query}`)}&per_page=20`); + return result.items ?? []; +} + +/** Exactly one incident issue per record: the record and a body marker both deduplicate. */ +export async function ensureIncident(io: CoordinatorIO, record: RedMainRecord): Promise { + const open = record.open; + if (!open || open.incident !== null) return record; + const marker = incidentMarker(open.run); + let number = (await search(io, `"brain-red-main: run ${open.run}" in:body`)).find(issue => issue.body?.includes(marker))?.number; + if (!number) { + const related = new Set(); + for (const failure of open.failures.filter(f => f.test)) for (const issue of await search(io, `"${failure.test}" in:title,body`)) related.add(issue.number); + const lines = [ + marker, + `Main is red at \`${open.firstBad}\` (first failing main run: ${runUrl(io, open.run)}).`, + "", + "Failing tests and categories:", + ...open.failures.map(f => `- \`${f.test ?? f.category}\` (${f.category}; ${f.reasons.join(", ")}; run ${runUrl(io, f.run)})`), + "", + "Hosted proof whose merge ref contains this commit is refused or cancelled, and `integrate.ts` refuses ordinary confirmation and merges, until a main run that includes this failing set is green. Declare a fix PR with `bun scripts/integrate.ts declare-fix `; the first confirmed fix wins. Only a green main run that includes this failing set clears the record, so a failure that does not reproduce still needs a declared fix to land.", + ...(related.size ? ["", `Possibly related open issues: ${[...related].sort((a, b) => a - b).map(n => `#${n}`).join(", ")}.`] : []), + ]; + const issue = await io.write("POST", `repos/${io.repository}/issues`, { + title: `ci: main red at ${short(open.firstBad)}: ${open.failures[0]!.test ?? open.failures[0]!.category}`, + body: lines.join("\n"), labels: ["type: fix", "area: ci"] }); + number = issue.number as number; + } + const { after } = await updateRecord(io, (current, now) => current.open?.run === open.run && current.open.incident === null ? attachIncident(current, number!, now) : current); + return after; +} + +/** Files or updates the issue of a suspected flake, whatever the probe result. */ +export async function noteFlake(io: CoordinatorIO, key: string, text: string, existing: number | null): Promise { + const marker = flakeMarker(key); + const number = existing ?? (await search(io, `"brain-flake: ${key}" in:body`)).find(issue => issue.body?.includes(marker))?.number; + if (number) { await io.write("POST", `repos/${io.repository}/issues/${number}/comments`, { body: text }); return number; } + const issue = await io.write("POST", `repos/${io.repository}/issues`, { + title: `test: suspected flake in ${key}`, labels: ["type: test", "area: ci"], + body: `${marker}\nThe red-main coordinator suspected a flake in \`${key}\`. A rerun is only a triage probe: it never turns proof green. A second suspected flake within the window is treated as a real failure.\n\n${text}` }); + return issue.number as number; +} + +/** Cancels in-progress PR proof created after the bad commit landed, except declared fixes. */ +export async function cancelDoomed(io: CoordinatorIO, record: RedMainRecord): Promise { + const open = record.open; + if (!open) return []; + const landed = io.commitTime(open.firstBad), cancelled: number[] = []; + for (const status of ["queued", "in_progress"]) { + const runs = await io.json(`repos/${io.repository}/actions/workflows/ci.yml/runs?event=pull_request&status=${status}&per_page=100`); + for (const run of (runs.workflow_runs ?? []) as WorkflowRun[]) { + const prs = (run.pull_requests ?? []).map(pr => pr.number); + if (!prs.length || prs.some(pr => open.fixes.includes(pr)) || Date.parse(run.created_at) < landed) continue; + await io.write("POST", `repos/${io.repository}/actions/runs/${run.id}/cancel`); + cancelled.push(run.id); + } + } + return cancelled; +} + +/** Reports a non-fix squash that landed on main while the record was open. */ +export async function detectLanded(io: CoordinatorIO, record: RedMainRecord, run: WorkflowRun): Promise { + const open = record.open, sha = run.head_sha; + if (!open || sha === open.firstBad || open.reported.includes(sha) || !io.isAncestor(open.firstBad, sha)) return false; + const pulls = await io.json(`repos/${io.repository}/commits/${sha}/pulls`); + const pr = (pulls as { number: number; merged_at: string | null }[]).find(p => p.merged_at)?.number; + if (!pr || open.fixes.includes(pr)) return false; + const incident = open.incident ? `incident #${open.incident}` : "the open red-main record"; + await io.write("POST", `repos/${io.repository}/issues/${pr}/comments`, { body: `This PR's squash \`${sha}\` landed on main while main was red at \`${open.firstBad}\` (${incident}) without being a declared fix. Merge blocking while red is cooperative; this report is the detection.` }); + if (open.incident) await io.write("POST", `repos/${io.repository}/issues/${open.incident}/comments`, { body: `Squash \`${sha}\` from #${pr} landed while red without being a declared fix (main run ${runUrl(io, run.id)}).` }); + await io.recordEvent({ kind: "incident", pr, run: run.id, evidence: open.incident ? issueUrl(io, open.incident) : runUrl(io, run.id) }); + await updateRecord(io, (current, now) => reportLanded(current, sha, now)); + return true; +} + +export async function dispatchProbe(io: CoordinatorIO, purpose: "flake" | "bisect", source: number, sha: string, tests: string[]) { + await io.write("POST", `repos/${io.repository}/actions/workflows/${PROBE_WORKFLOW}/dispatches`, { + ref: "main", inputs: { purpose, source_run: String(source), sha, tests: JSON.stringify(tests) } }); +} + +/** Last earlier main run where the failing category's job actually ran green. */ +async function lastGreen(io: CoordinatorIO, run: WorkflowRun, category: Category): Promise { + const runs = await io.json(`repos/${io.repository}/actions/workflows/ci.yml/runs?event=push&branch=main&status=completed&per_page=30`); + for (const earlier of ((runs.workflow_runs ?? []) as WorkflowRun[]).filter(r => r.id !== run.id && r.head_sha !== run.head_sha && io.isAncestor(r.head_sha, run.head_sha))) { + const jobs: Job[] = (await io.json(`repos/${io.repository}/actions/runs/${earlier.id}/attempts/${earlier.run_attempt}/jobs?per_page=100`)).jobs ?? []; + if (jobs.some(job => jobCategory(job.name) === category && job.conclusion === "success") && + !jobs.some(job => jobCategory(job.name) === category && job.conclusion !== "success" && job.conclusion !== "skipped")) return earlier.head_sha; + } + return null; +} + +async function handleMainRun(io: CoordinatorIO, run: WorkflowRun) { + const jobs: Job[] = (await io.json(`repos/${io.repository}/actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100`)).jobs ?? []; + const start = io.read().redMain; + // Detection uses the record as it stood before this run's own result. + if (start.open) await detectLanded(io, start, run); + if (run.conclusion === "success") { + const metadata = jobs.find(job => job.name === "changeset"); + const included = metadata ? includedRedSet(await io.log(metadata.id)) : null; + if (start.open && coversRedSet(start, included)) { + const { after } = await updateRecord(io, (current, now) => coversRedSet(current, included) + ? clearRed(current, { id: run.id, conclusion: "success", included }, now) : current); + if (!after.open && start.open.incident) await io.write("POST", `repos/${io.repository}/issues/${start.open.incident}/comments`, { body: `Main is green again: run ${runUrl(io, run.id)} at \`${run.head_sha}\` included the failing set and passed. The red-main record is cleared.` }); + io.print(`cleared red-main record ${start.open.firstBad}`); + } + return; + } + if (run.conclusion !== "failure") return; + const evidence = await runFailures(io, run, jobs), now = await io.now(); + const real: RedFailure[] = [], suspects: FailureEvidence[] = []; + for (const failure of evidence) { + const verdict = classifyFailure(failure, io.read().redMain, now); + io.print(`BRAIN_FLAKE_ESTIMATE ${JSON.stringify({ test: failure.test, category: failure.category, ...verdict })}`); + if (verdict.verdict === "real") real.push({ test: failure.test, category: failure.category, verdict: "real", reasons: verdict.reasons, run: run.id, sha: run.head_sha }); + else suspects.push(failure); + } + for (const suspect of suspects) { + const key = failureKey(suspect); + await updateRecord(io, (current, at) => addSuspect(current, { test: key, category: suspect.category, run: run.id, sha: run.head_sha, at }, at)); + const issue = await noteFlake(io, key, `Suspected flake in main run ${runUrl(io, run.id)} at \`${run.head_sha}\` (${suspect.signature} signature, ${suspect.inClosure === false ? "outside" : "inside"} the commit's affected closure).${suspect.test ? " A triage probe reruns only this test file at that SHA." : " No single-file probe exists for this category; the next suspected flake escalates to real."}`, null); + await updateRecord(io, (current, at) => settleSuspect(current, { test: key, run: run.id }, { issue, ...(suspect.test ? {} : { probe: "unavailable" }) }, at)); + } + const probeTests = suspects.flatMap(s => s.test ? [s.test] : []); + if (probeTests.length) await dispatchProbe(io, "flake", run.id, run.head_sha, probeTests); + if (!real.length) return; + // First bad: the first red after the last run where the failing category actually ran green. + // With several failing categories, the oldest of their last greens bounds the range; + // a category with no green run in the window keeps the conservative current SHA. + let firstBad = run.head_sha, range: string[] = []; + const greens = await Promise.all([...new Set(real.map(f => f.category))].map(category => lastGreen(io, run, category))); + if (greens.length && greens.every(green => green !== null)) { + const oldest = greens.find(green => greens.every(other => other === green || io.isAncestor(green!, other!)))!; + range = oldest ? io.range(oldest, run.head_sha) : []; + if (range.length) firstBad = range[0]!; + } + const { after } = await updateRecord(io, (current, at) => openRed(current, { firstBad, run: run.id, failures: real }, at)); + const withIncident = await ensureIncident(io, after); + const tests = real.flatMap(f => f.test ? [f.test] : []); + // Probe each candidate commit with only the failing test files. + if (range.length > 1 && range.length <= MAX_BISECT && tests.length) for (const sha of range) await dispatchProbe(io, "bisect", run.id, sha, tests); + const cancelled = await cancelDoomed(io, withIncident); + io.print(`BRAIN_RED_MAIN ${JSON.stringify({ firstBad: withIncident.open?.firstBad, incident: withIncident.open?.incident, cancelled })}`); +} + +/** Probe run names carry their purpose, source run and SHA; tests come from the record. */ +export function probeIdentity(title: string): { purpose: "flake" | "bisect"; source: number; sha: string } | null { + const match = /^red-main probe (flake|bisect) ([1-9]\d*) ([a-f0-9]{40})$/.exec(title); + return match ? { purpose: match[1] as "flake" | "bisect", source: Number(match[2]), sha: match[3]! } : null; +} + +async function handleProbe(io: CoordinatorIO, run: WorkflowRun) { + const identity = probeIdentity(run.display_title); + if (!identity || run.status !== "completed") return; + const failed = run.conclusion === "failure", result = failed ? "failed" : run.conclusion === "success" ? "passed" : "unavailable"; + if (identity.purpose === "bisect") { + // Starts at the earliest candidate after the last green run. A passing probe proves the + // first bad commit is later; a failing probe proves it is no later than the probed SHA. + if (result === "unavailable") return; + const { before, after } = await updateRecord(io, (current, now) => { + const open = current.open; + if (!open || open.run !== identity.source) return current; + if (failed) return io.isAncestor(identity.sha, open.firstBad) && identity.sha !== open.firstBad ? refineFirstBad(current, identity.sha, run.id, now) : current; + if (!io.isAncestor(open.firstBad, identity.sha)) return current; + const later = io.range(identity.sha, open.failures[0]!.sha)[0]; + return later ? refineFirstBad(current, later, run.id, now) : current; + }); + if (after !== before && after.open?.incident) await io.write("POST", `repos/${io.repository}/issues/${after.open.incident}/comments`, { body: `Bisect probe ${runUrl(io, run.id)} ${failed ? "reproduced" : "passed"} at \`${identity.sha}\`; the record's first bad SHA is now \`${after.open.firstBad}\`.` }); + return; + } + const pending = io.read().redMain.suspects.filter(s => s.run === identity.source && s.sha === identity.sha && s.probe === "pending"); + const real: RedFailure[] = []; + for (const suspect of pending) { + await updateRecord(io, (current, now) => settleSuspect(current, { test: suspect.test, run: suspect.run }, { probe: result }, now)); + await noteFlake(io, suspect.test, `Triage probe ${runUrl(io, run.id)} at \`${identity.sha}\`: **${result}**. ${failed ? "The failure reproduced; main is declared red." : "A passing probe does not turn the original run green."}`, suspect.issue); + if (failed) real.push({ test: suspect.test.startsWith("category:") ? null : suspect.test, category: suspect.category, verdict: "real", reasons: ["probe-reproduced"], run: identity.source, sha: identity.sha }); + } + if (!real.length) return; + const { after } = await updateRecord(io, (current, now) => openRed(current, { firstBad: identity.sha, run: identity.source, failures: real }, now)); + await cancelDoomed(io, await ensureIncident(io, after)); +} + +export async function coordinate(io: CoordinatorIO, run: WorkflowRun) { + if (run.name === "CI" && run.event === "push" && run.head_branch === "main" && run.status === "completed") await handleMainRun(io, run); + else if (run.name === "red-main-probe") await handleProbe(io, run); +} diff --git a/scripts/red-main.ts b/scripts/red-main.ts new file mode 100644 index 0000000000..15f54c7209 --- /dev/null +++ b/scripts/red-main.ts @@ -0,0 +1,186 @@ +/** + * Repository-level red-main record (#2942): shared through the coordination ref, + * written by the coordinator workflow, read by CI, `integrate.ts` and orchestrators. + */ +import type { CheckPlan } from "./ci-plan"; + +export const RED_MAIN_FILE = "red-main.json"; +/** Two suspected flakes on one test within this window make the second real. */ +export const FLAKE_WINDOW_MS = 7 * 24 * 60 * 60_000; +const MAX_SUSPECTS = 200, MAX_REPORTED = 200, MAX_FAILURES = 100, MAX_FIXES = 20; +const SHA = /^[a-f0-9]{40}$/; +/** `changeset` is the metadata/lint gate; it always runs and widens no selection. */ +export const CATEGORIES = ["changeset", "verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"] as const; +export type Category = typeof CATEGORIES[number]; +export type Signature = "timeout" | "assertion" | "setup" | "unknown"; +export type Verdict = "real" | "suspected-flake"; + +export interface RedFailure { test: string | null; category: Category; verdict: "real"; reasons: string[]; run: number; sha: string; } +export interface RedIncident { + /** First red after the last run where the failing set actually ran green. */ + firstBad: string; run: number; opened: number; + failures: RedFailure[]; incident: number | null; fixes: number[]; reported: string[]; +} +export interface Suspect { test: string; category: Category; run: number; sha: string; at: number; probe: "pending" | "passed" | "failed" | "unavailable"; issue: number | null; } +export interface RedMainRecord { + version: 1; updated: number; open: RedIncident | null; suspects: Suspect[]; + last: { action: "open" | "update" | "refine" | "incident" | "declare-fix" | "report" | "clear" | "suspect" | "probe"; at: number; run: number | null } | null; +} + +export const emptyRedMain = (): RedMainRecord => ({ version: 1, updated: 0, open: null, suspects: [], last: null }); +const positive = (value: unknown) => Number.isSafeInteger(value) && Number(value) > 0; +const testPath = (value: unknown) => typeof value === "string" && value.length <= 300 && /^[A-Za-z0-9_./@-]+$/.test(value) && !value.split("/").includes(".."); +const category = (value: unknown): value is Category => CATEGORIES.includes(value as Category); + +export function parseRedMain(text: string): RedMainRecord { + if (text.length > 64_000) throw new Error("Unbounded red-main record"); + const r = JSON.parse(text) as RedMainRecord; + if (r?.version !== 1 || !Number.isSafeInteger(r.updated) || r.updated < 0 || !Array.isArray(r.suspects) || r.suspects.length > MAX_SUSPECTS || + !Object.hasOwn(r, "open") || !Object.hasOwn(r, "last")) throw new Error("Invalid red-main record"); + for (const s of r.suspects) if (!s || !testPath(s.test) || !category(s.category) || !positive(s.run) || !SHA.test(s.sha) || !Number.isSafeInteger(s.at) || + !["pending", "passed", "failed", "unavailable"].includes(s.probe) || !(s.issue === null || positive(s.issue))) throw new Error("Invalid red-main suspect"); + const o = r.open; + if (o !== null && (!o || !SHA.test(o.firstBad) || !positive(o.run) || !Number.isSafeInteger(o.opened) || !Array.isArray(o.failures) || + !o.failures.length || o.failures.length > MAX_FAILURES || !(o.incident === null || positive(o.incident)) || + !Array.isArray(o.fixes) || o.fixes.length > MAX_FIXES || !o.fixes.every(positive) || + !Array.isArray(o.reported) || o.reported.length > MAX_REPORTED || !o.reported.every(sha => SHA.test(sha)) || + o.failures.some(f => !f || !(f.test === null || testPath(f.test)) || !category(f.category) || f.verdict !== "real" || + !Array.isArray(f.reasons) || !f.reasons.length || f.reasons.some(x => typeof x !== "string" || !/^[a-z0-9-]{1,60}$/.test(x)) || !positive(f.run) || !SHA.test(f.sha)))) throw new Error("Invalid red-main incident"); + if (r.last !== null && (!r.last || r.last.at !== r.updated || !(r.last.run === null || positive(r.last.run)) || + !["open", "update", "refine", "incident", "declare-fix", "report", "clear", "suspect", "probe"].includes(r.last.action))) throw new Error("Invalid red-main audit"); + return r; +} + +const key = (f: { test: string | null; category: Category }) => f.test ?? `category:${f.category}`; +function next(record: RedMainRecord, now: number, action: NonNullable["action"], run: number | null, change: Partial): RedMainRecord { + if (!Number.isSafeInteger(now) || now < record.updated) throw new Error("Backwards or unavailable clock"); + return parseRedMain(JSON.stringify({ ...record, ...change, version: 1, updated: now, last: { action, at: now, run } })); +} + +/** Opens the record, or adds new failures to the open one; never changes its first bad SHA. */ +export function openRed(record: RedMainRecord, input: { firstBad: string; run: number; failures: RedFailure[] }, now: number): RedMainRecord { + if (!input.failures.length) throw new Error("A red record needs at least one real failure"); + if (record.open) { + const known = new Set(record.open.failures.map(key)), added = input.failures.filter(f => !known.has(key(f))); + if (!added.length) return record; + return next(record, now, "update", input.run, { open: { ...record.open, failures: [...record.open.failures, ...added].slice(0, MAX_FAILURES) } }); + } + return next(record, now, "open", input.run, { open: { firstBad: input.firstBad, run: input.run, opened: now, failures: input.failures.slice(0, MAX_FAILURES), incident: null, fixes: [], reported: [] } }); +} + +/** Bisect probes narrow the first bad SHA within the recorded range; the caller proves ancestry. */ +export function refineFirstBad(record: RedMainRecord, sha: string, run: number, now: number): RedMainRecord { + if (!record.open || record.open.firstBad === sha) return record; + if (!SHA.test(sha)) throw new Error("Invalid first bad SHA"); + return next(record, now, "refine", run, { open: { ...record.open, firstBad: sha } }); +} + +export function attachIncident(record: RedMainRecord, incident: number, now: number): RedMainRecord { + if (!record.open) throw new Error("No open red-main record"); + if (record.open.incident === incident) return record; + if (record.open.incident !== null) throw new Error(`Red-main record already names incident #${record.open.incident}`); + return next(record, now, "incident", record.open.run, { open: { ...record.open, incident } }); +} + +export function declareFix(record: RedMainRecord, pr: number, now: number): RedMainRecord { + if (!record.open) throw new Error("Main is not red; there is nothing to declare a fix for"); + if (!positive(pr)) throw new Error("Invalid fix PR"); + if (record.open.fixes.includes(pr)) return record; + return next(record, now, "declare-fix", null, { open: { ...record.open, fixes: [...record.open.fixes, pr] } }); +} + +export function reportLanded(record: RedMainRecord, sha: string, now: number): RedMainRecord { + if (!record.open || record.open.reported.includes(sha)) return record; + return next(record, now, "report", null, { open: { ...record.open, reported: [...record.open.reported, sha].slice(-MAX_REPORTED) } }); +} + +export interface IncludedRedSet { run: number; firstBad: string; failures: RedFailure[]; } +/** Whether a main run's printed selection covered every failure of this open record. */ +export function coversRedSet(record: RedMainRecord, included: IncludedRedSet | null): boolean { + if (!record.open || !included || included.run !== record.open.run) return false; + const keys = new Set(included.failures.map(key)); + return record.open.failures.every(f => keys.has(key(f))); +} + +/** Clears only on a green main run whose selection included this exact open record. */ +export function clearRed(record: RedMainRecord, run: { id: number; conclusion: string; included: IncludedRedSet | null }, now: number): RedMainRecord { + if (!record.open) return record; + if (run.conclusion !== "success" || !coversRedSet(record, run.included)) throw new Error("Only a green main run that included the open red set clears it"); + return next(record, now, "clear", run.id, { open: null }); +} + +export function addSuspect(record: RedMainRecord, suspect: Omit & Partial>, now: number): RedMainRecord { + return next(record, now, "suspect", suspect.run, { suspects: [...record.suspects, { probe: "pending" as const, issue: null, ...suspect }].slice(-MAX_SUSPECTS) }); +} + +export function settleSuspect(record: RedMainRecord, match: { test: string; run: number }, update: Partial>, now: number): RedMainRecord { + let found = false; + const suspects = record.suspects.map(s => s.test === match.test && s.run === match.run ? (found = true, { ...s, ...update }) : s); + if (!found) throw new Error("Unknown suspected flake"); + return next(record, now, "probe", match.run, { suspects }); +} + +export interface FailureEvidence { test: string | null; category: Category; signature: Signature; inClosure: boolean | null; } + +/** + * Deterministic flake estimator. A rerun never turns proof green; this only + * decides whether main is declared red now or after a triage probe. + */ +export function classifyFailure(failure: FailureEvidence, record: RedMainRecord, now: number, windowMs = FLAKE_WINDOW_MS): { verdict: Verdict; reasons: string[] } { + const id = key(failure); + const prior = record.suspects.filter(s => s.test === id && now - s.at <= windowMs); + if (prior.length) return { verdict: "real", reasons: ["repeated-suspected-flake", `prior-suspect-run-${prior.at(-1)!.run}`] }; + if (failure.signature === "setup") return { verdict: "suspected-flake", reasons: ["setup-failure"] }; + if (failure.inClosure === null) return { verdict: "real", reasons: ["closure-unknown"] }; + if (failure.inClosure) return { verdict: "real", reasons: ["in-affected-closure", `${failure.signature}-signature`] }; + if (failure.signature === "timeout") return { verdict: "suspected-flake", reasons: ["outside-affected-closure", "timeout-signature"] }; + return { verdict: "real", reasons: ["outside-affected-closure", `${failure.signature}-signature`] }; +} + +export const failureKey = key; + +export interface GateInput { record: RedMainRecord; pr: number; contains: (sha: string) => boolean; } +/** The hosted gate: refuse doomed proof, admit declared fixes and unaffected merge refs. */ +export function gateDecision({ record, pr, contains }: GateInput): { refuse: boolean; message: string } { + const open = record.open; + if (!open) return { refuse: false, message: "main green: no open red-main record" }; + const incident = open.incident ? `incident #${open.incident}` : "incident pending"; + if (open.fixes.includes(pr)) return { refuse: false, message: `main red at ${open.firstBad}, ${incident}; PR #${pr} is a declared fix` }; + if (!contains(open.firstBad)) return { refuse: false, message: `main red at ${open.firstBad}, ${incident}; this merge ref does not contain it` }; + return { refuse: true, message: `main red at ${open.firstBad}, ${incident}` }; +} + +/** Main runs select their affected set plus every test and category in the open red record. */ +export function includeRedSet(plan: CheckPlan, record: RedMainRecord | null, replan: (changed: string[]) => CheckPlan): CheckPlan { + const open = record?.open; + if (!open) return plan; + const tests = open.failures.flatMap(f => f.test ? [f.test] : []); + const widened = tests.length ? replan([...new Set([...plan.changed, ...tests])].sort()) : { ...plan, local: { ...plan.local } }; + const local = { ...widened.local }; + for (const f of open.failures) { + if (f.category === "unit") local.fullTests = true; + else if (f.category === "runtime" || f.category === "runtime_host") local.runtime = true; + else if (f.category === "browser" || f.category === "layout" || f.category === "captures" || f.category === "endurance") local[f.category] = true; + } + const typecheck = widened.typecheck || open.failures.some(f => f.category === "verify"); + const pack = widened.pack || open.failures.some(f => f.category === "pack"); + // The file inventory, when narrowed, must still name each red test. + const unitTests = widened.unitTests && [...new Set([...widened.unitTests, ...tests])].sort(); + return { ...widened, changed: plan.changed, typecheck, pack, local, ...(unitTests ? { unitTests } : {}), redMain: { run: open.run, firstBad: open.firstBad, failures: open.failures } }; +} + +/** Extracts failing test files and their signature from Bun JUnit output. */ +export function junitFailures(xml: string): { test: string; signature: Signature }[] { + const out = new Map(); + const suites = xml.split(/(?=]*>/.exec(suite)?.[0]; + const file = tag && /\sfile="([^"]*)"/.exec(tag)?.[1]; + if (!file || !testPath(file) || out.has(file)) continue; + const failures = [...suite.matchAll(/<(failure|error)\b([^>]*)>([\s\S]*?)<\/\1>|<(failure|error)\b([^>]*)\/>/g)]; + if (!failures.length) continue; + const text = failures.map(m => `${m[2] ?? m[5] ?? ""} ${m[3] ?? ""}`).join("\n"); + out.set(file, /timed? ?out|timeout|deadline exceeded/i.test(text) ? "timeout" : /expect|assert|toBe|toEqual|received|expected/i.test(text) ? "assertion" : "unknown"); + } + return [...out].map(([test, signature]) => ({ test, signature })); +} diff --git a/tests/ci-plan.test.ts b/tests/ci-plan.test.ts index c0db06949d..e56bb17de4 100644 --- a/tests/ci-plan.test.ts +++ b/tests/ci-plan.test.ts @@ -212,6 +212,7 @@ describe("affected CI checks", () => { const f = fixture(); f.write("scripts/ci-plan.ts", readFileSync(join(import.meta.dir, "../scripts/ci-plan.ts"), "utf8").replace('"typescript"', JSON.stringify(import.meta.resolve("typescript")))); f.write("scripts/browser-input-closure.ts", `export * from ${JSON.stringify(resolve(import.meta.dir, "../scripts/browser-input-closure.ts"))};\n`); f.write("scripts/unit-test-consumers.ts", `export * from ${JSON.stringify(resolve(import.meta.dir, "../scripts/unit-test-consumers.ts"))};\n`); + for (const name of ["integration-reservation", "red-main"]) f.write(`scripts/${name}.ts`, `export * from ${JSON.stringify(resolve(import.meta.dir, `../scripts/${name}.ts`))};\n`); f.write("packages/core/src/note.ts", "export const note = 2;\n"); f.git("add", "."); f.git("commit", "-qm", "planner fixture"); for (const draft of ["true", "false"]) { @@ -224,7 +225,7 @@ describe("affected CI checks", () => { const [code, err] = await Promise.all([child.exited, new Response(child.stderr).text()]); expect(code, err).toBe(0); const expected = proofSelections(JSON.parse(readFileSync(plan, "utf8")), draft === "true"); - expect(readFileSync(output, "utf8")).toBe(`unit_shards=[1,2,3,4]\ncadence=${draft === "true" ? "draft" : "confirmation"}\n` + Object.entries(expected).map(([name, value]) => `${name}=${value}\n`).join("")); + expect(readFileSync(output, "utf8")).toBe(`unit_shards=[1,2,3,4]\ncadence=${draft === "true" ? "draft" : "confirmation"}\nred_main_oid=\n` + Object.entries(expected).map(([name, value]) => `${name}=${value}\n`).join("")); expect(expected.unit).toBe(draft === "false"); expect(expected.runtime).toBe(draft === "false"); expect(JSON.parse(readFileSync(plan, "utf8")).tests.length).toBeGreaterThan(0); diff --git a/tests/ci-throughput.test.ts b/tests/ci-throughput.test.ts index d4b29e1735..a847ba6223 100644 --- a/tests/ci-throughput.test.ts +++ b/tests/ci-throughput.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { collectPullObservation, concurrency, summarizeThroughput, validateWorkEvent, type PullObservation, type WorkEvent } from "../scripts/ci-throughput"; import { attachTimingEvidence, type TimingSnapshot } from "../scripts/ci-timings"; +import { declareFix, emptyRedMain, openRed } from "../scripts/red-main"; import { collectReservationHistory, mergeLeaseObservations, reservationObservations, type LeaseObservation } from "../scripts/ci-coordination"; import { emptyReservation, reservationTransition, GitReservationStore } from "../scripts/integration-reservation"; @@ -139,10 +140,15 @@ test("native reservation collection reads an explicitly local offline Git remote const store = new GitReservationStore(work); const state = reservationTransition(emptyReservation(), { kind: "acquire", candidate: { repository: `https://github.com/${repo}`, pr: 42, head, base }, id: "2".repeat(32) }, 1, Date.parse(at(0))); expect(store.publish({ oid: null, state: emptyReservation() }, state)).toBe(true); + // Red-main record writes share the ref and leave reservation.json unchanged (#2942). + const failure = { test: "tests/raft.test.ts", category: "unit" as const, verdict: "real" as const, reasons: ["in-affected-closure"], run: 7, sha: head }; + expect(store.publishRedMain(store.read(), openRed(emptyRedMain(), { firstBad: head, run: 7, failures: [failure] }, Date.parse(at(0)) + 1))).toBe(true); + expect(store.publishRedMain(store.read(), declareFix(store.read().redMain, 43, Date.parse(at(0)) + 2))).toBe(true); // The production collector uses Git argv against this local remote only. process.chdir(work); const history = collectReservationHistory(repo, at(0)); expect(history.leases.length).toBe(1); expect(history.leases[0]!.pr).toBe(42); + expect(history.leases[0]!.sources, "RED_MAIN_WRITES_ARE_NOT_LEASE_SOURCES").toHaveLength(1); } finally { process.chdir(cwd); rmSync(dir, { recursive: true, force: true }); } }); diff --git a/tests/ci-workflows.test.ts b/tests/ci-workflows.test.ts index e374ec8c43..5cad2fc6e9 100644 --- a/tests/ci-workflows.test.ts +++ b/tests/ci-workflows.test.ts @@ -131,7 +131,7 @@ describe("the authoritative jobs retain their important phases", () => { expect(ci.on.push).toEqual({ branches: ["main"] }); expect(ci.on.pull_request).toEqual({ types: ["opened", "synchronize", "reopened", "ready_for_review", "converted_to_draft"] }); expect(Object.keys(ci.jobs)).toEqual(["changeset", "verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "proof"]); - expect(ci.jobs.changeset!.outputs).toEqual({ ...Object.fromEntries(["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "cadence", "unit_shards"].map(name => [name, `\${{ steps.plan.outputs.${name} }}`])), + expect(ci.jobs.changeset!.outputs).toEqual({ ...Object.fromEntries(["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "cadence", "unit_shards", "red_main_oid"].map(name => [name, `\${{ steps.plan.outputs.${name} }}`])), ...Object.fromEntries(["run_browser", "run_layout", "reuse"].map(name => [name, `\${{ steps.reuse.outputs.${name} }}`])) }); const metadata = ci.jobs.changeset!.steps.filter(s => s.run).map(s => s.run); expect(metadata).toContain("bun scripts/ci-plan.ts"); expect(metadata).toContain("bun run lint"); @@ -662,3 +662,18 @@ test("verify successful step requires final marker and zero unsignalled finishes } } finally { rmSync(dir, { recursive: true, force: true }); } }); + +test("a main push whose metadata job fails still runs its selected proof (#2942)", () => { + const ci = Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8")) as { jobs: Record }; + for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"]) { + const condition = ci.jobs[name]!.if ?? ""; + // No implicit success(): a status function plus an explicit push alternative. + expect(condition, `PUSH_PROOF_SURVIVES_METADATA_FAILURE:${name}`).toContain("!cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push')"); + } + const steps = ci.jobs.changeset!.steps!.map(step => step.id ?? step.name ?? ""); + const gate = steps.indexOf("Refuse doomed proof while main is red"), plan = steps.indexOf("plan"), reuse = steps.indexOf("reuse"); + expect(gate, "RED_MAIN_GATE_RUNS_FIRST").toBeGreaterThan(-1); expect(gate).toBeLessThan(plan); + // Every output-producing step precedes every metadata gate that can fail. + for (const gateStep of ["Lint, leakage and contribution workflow guards", "Env documentation matches its descriptors", "Validate all pending changeset package names", "Require a changeset for shipped package changes"]) + expect(steps.indexOf(gateStep), `OUTPUTS_BEFORE_${gateStep}`).toBeGreaterThan(reuse); +}); diff --git a/tests/heavy-feedback.test.ts b/tests/heavy-feedback.test.ts index 834f92e0a9..38201cc64c 100644 --- a/tests/heavy-feedback.test.ts +++ b/tests/heavy-feedback.test.ts @@ -119,6 +119,12 @@ test("the workflow is ci.yml's category jobs with per-PR cancellation and an agg expect(workflow.jobs.aggregate.name).toBe(FEEDBACK_AGGREGATE); expect(Object.entries(workflow.jobs).map(([id, job]: [string, any]) => job.name ?? id)).not.toContain("proof"); expect(workflow.on.pull_request.types, "PUSH_CANCELS_FEEDBACK").toContain("synchronize"); + // Feedback on a head containing main's recorded bad commit is refused like proof (#2942). + const admission = workflow.jobs.changeset.steps.map((step: any) => step.run ?? step.uses); + expect(admission.indexOf("bun scripts/red-main-cli.ts gate"), "RED_MAIN_GATE").toBeGreaterThan(admission.lastIndexOf("bun install --frozen-lockfile")); + expect(admission.indexOf("bun scripts/red-main-cli.ts gate"), "GATE_BEFORE_PLAN").toBeLessThan(admission.indexOf("bun scripts/ci-plan.ts")); + expect(workflow.jobs.changeset.steps.find((step: any) => step.run === "bun scripts/red-main-cli.ts gate").env).toEqual({ PR_NUMBER: "${{ inputs.pr }}" }); + expect(() => renderHeavyFeedbackWorkflow(ci.replace("run: bun scripts/red-main-cli.ts gate", "run: bun scripts/red-main-cli.ts noop")), "GATE_REQUIRED").toThrow("lost its red-main gate"); for (const name of ["unit", "runtime_host", "browser"]) { const pins = (job: any) => job.steps.filter((step: any) => step.uses).map((step: any) => `${step.uses} ${JSON.stringify({ ...step.with, ref: undefined })}`); expect(pins(workflow.jobs[name]), `${name}_SAME_PINS`).toEqual(pins(source.jobs[name])); diff --git a/tests/integration-command.test.ts b/tests/integration-command.test.ts index 9a73095e54..1756f8876b 100644 --- a/tests/integration-command.test.ts +++ b/tests/integration-command.test.ts @@ -3,6 +3,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, wr import { join, resolve } from "node:path"; import { tmpdir } from "node:os"; import { GitReservationStore, emptyReservation, reservationTransition, MAX_MS } from "../scripts/integration-reservation"; +import { declareFix, emptyRedMain, openRed } from "../scripts/red-main"; import { invocationChild } from "../scripts/test-invocation-child"; import { processIdentity } from "../scripts/workspace-lease.mjs"; @@ -72,6 +73,11 @@ async function runScenario(mode: string, owner: Scenario): Promise { + const refused = await scenario("red-main"); + expect(refused.dispatched, "NO_NON_FIX_MERGE_WHILE_RED").toBe(false); + expect(refused.code, refused.err).toBe(1); + expect(refused.err).toContain("main red at"); + expect(refused.err).toContain("only a declared fix may confirm or merge"); + const fix = await scenario("red-main-fix"); + expect(fix.code, `DECLARED_FIX_MERGES: ${fix.err}`).toBe(2); + expect(fix.dispatched).toBe(true); +}); diff --git a/tests/red-main.test.ts b/tests/red-main.test.ts new file mode 100644 index 0000000000..df0225b9b3 --- /dev/null +++ b/tests/red-main.test.ts @@ -0,0 +1,281 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import type { CheckPlan } from "../scripts/ci-plan"; +import { GitReservationStore } from "../scripts/integration-reservation"; +import { addSuspect, classifyFailure, clearRed, declareFix, emptyRedMain, FLAKE_WINDOW_MS, gateDecision, includeRedSet, junitFailures, + openRed, parseRedMain, type RedFailure, type RedMainRecord } from "../scripts/red-main"; +import { coordinate, includedRedSet, incidentMarker, type CoordinatorIO, type Job, type Snapshot, type WorkflowRun } from "../scripts/red-main-coordinator"; + +const ROOT = resolve(import.meta.dir, ".."); +const scratch: string[] = []; +afterEach(() => { for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); }); +const NOW = Date.parse("2026-07-12T00:00:00Z"); +const A = "a".repeat(40), B = "b".repeat(40), C = "c".repeat(40); +const failure = (test: string | null, category: RedFailure["category"] = "unit"): RedFailure => + ({ test, category, verdict: "real", reasons: ["in-affected-closure"], run: 11, sha: B }); + +function repo() { + const dir = mkdtempSync(join(tmpdir(), "odysseus-red-main-")); scratch.push(dir); + const git = (cwd: string, ...args: string[]) => { + const p = Bun.spawnSync(["git", "-c", "commit.gpgsign=false", ...args], { cwd, stdout: "pipe", stderr: "pipe", env: { ...process.env, + GIT_AUTHOR_NAME: "Odysseus", GIT_AUTHOR_EMAIL: "odysseus@example.invalid", GIT_COMMITTER_NAME: "Odysseus", GIT_COMMITTER_EMAIL: "odysseus@example.invalid", + GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null" } }); + expect(p.exitCode, new TextDecoder().decode(p.stderr)).toBe(0); + return new TextDecoder().decode(p.stdout).trim(); + }; + return { dir, git }; +} + +describe("flake estimator", () => { + test("an out-of-closure timeout is a suspected flake, an in-closure assertion is real, and a second suspicion is real", () => { + const record = emptyRedMain(); + expect(classifyFailure({ test: "tests/raft.test.ts", category: "unit", signature: "timeout", inClosure: false }, record, NOW).verdict, "OUTSIDE_CLOSURE_TIMEOUT_SUSPECTED").toBe("suspected-flake"); + expect(classifyFailure({ test: "tests/raft.test.ts", category: "unit", signature: "assertion", inClosure: true }, record, NOW).verdict, "IN_CLOSURE_ASSERTION_REAL").toBe("real"); + const suspected = addSuspect(record, { test: "tests/raft.test.ts", category: "unit", run: 9, sha: A, at: NOW - 1000 }, NOW - 1000); + const second = classifyFailure({ test: "tests/raft.test.ts", category: "unit", signature: "timeout", inClosure: false }, suspected, NOW); + expect(second.verdict, "SECOND_SUSPECTED_FLAKE_ESCALATES").toBe("real"); + expect(second.reasons).toContain("repeated-suspected-flake"); + // Outside the configured window the earlier suspicion no longer escalates. + expect(classifyFailure({ test: "tests/raft.test.ts", category: "unit", signature: "timeout", inClosure: false }, suspected, NOW + FLAKE_WINDOW_MS).verdict).toBe("suspected-flake"); + // An unknown closure fails closed to real, never to a flake. + expect(classifyFailure({ test: "tests/raft.test.ts", category: "unit", signature: "timeout", inClosure: null }, record, NOW).verdict).toBe("real"); + }); + + test("JUnit failures name each failing file with its signature", () => { + const xml = ` + expect(received).toBe(expected) + `; + expect(junitFailures(xml)).toEqual([{ test: "tests/a.test.ts", signature: "timeout" }, { test: "tests/b.test.ts", signature: "assertion" }]); + }); +}); + +describe("red-main record", () => { + test("records validate, merge new failures, clear only from a green run that included the set", () => { + let record = openRed(emptyRedMain(), { firstBad: B, run: 11, failures: [failure("tests/raft.test.ts")] }, NOW); + record = openRed(record, { firstBad: C, run: 12, failures: [failure("tests/raft.test.ts"), failure(null, "browser")] }, NOW + 1); + expect(record.open?.firstBad).toBe(B); expect(record.open?.failures).toHaveLength(2); + expect(parseRedMain(JSON.stringify(record))).toEqual(record); + expect(() => parseRedMain(JSON.stringify({ ...record, open: { ...record.open, firstBad: "nope" } }))).toThrow("Invalid red-main incident"); + expect(() => clearRed(record, { id: 13, conclusion: "success", included: { run: 11, firstBad: B, failures: [failure("tests/raft.test.ts")] } }, NOW + 2)).toThrow("included the open red set"); + expect(() => clearRed(record, { id: 13, conclusion: "failure", included: { run: 11, firstBad: B, failures: record.open!.failures } }, NOW + 2)).toThrow(); + expect(clearRed(record, { id: 13, conclusion: "success", included: { run: 11, firstBad: B, failures: record.open!.failures } }, NOW + 2).open).toBeNull(); + }); + + test("two concurrent coordinators cannot both write the record through the remote compare-and-swap", async () => { + const { dir, git } = repo(); + const remote = join(dir, "remote.git"); git(dir, "init", "--bare", remote); + for (const name of ["one", "two"]) { mkdirSync(join(dir, name)); git(join(dir, name), "init"); git(join(dir, name), "remote", "add", "origin", remote); } + const script = join(dir, "contender.ts"); + writeFileSync(script, `import { existsSync, writeFileSync } from "node:fs"; + import { GitReservationStore } from ${JSON.stringify(join(ROOT, "scripts/integration-reservation.ts"))}; + import { openRed, emptyRedMain } from ${JSON.stringify(join(ROOT, "scripts/red-main.ts"))}; + const [root, number, barrier] = process.argv.slice(2), store = new GitReservationStore(root), snapshot = store.read(); + writeFileSync(barrier + number, "ready"); while (!existsSync(barrier + "1") || !existsSync(barrier + "2")) await Bun.sleep(5); + if (number === "2") while (!existsSync(barrier + "published")) await Bun.sleep(5); + const record = openRed(emptyRedMain(), { firstBad: "${B}", run: Number(number), failures: [{ test: "tests/raft.test.ts", category: "unit", verdict: "real", reasons: ["in-affected-closure"], run: Number(number), sha: "${B}" }] }, ${NOW}); + const published = store.publishRedMain(snapshot, record); if (number === "1") writeFileSync(barrier + "published", "done"); + console.log(JSON.stringify({ published }));`); + const children = ["1", "2"].map((id, index) => Bun.spawn([process.execPath, script, join(dir, index ? "two" : "one"), id, join(dir, "barrier-")], { stdout: "pipe", stderr: "pipe" })); + const results = await Promise.all(children.map(async child => { + const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(code, err).toBe(0); return JSON.parse(out).published as boolean; + })); + expect(results, "ONLY_ONE_RED_MAIN_WRITER_SUCCEEDS").toEqual([true, false]); + const store = new GitReservationStore(join(dir, "two")), snapshot = store.read(); + expect(snapshot.redMain.open?.run).toBe(1); + // The reservation file is preserved beside the record, and clearing writes through the same ref. + expect(snapshot.state.active).toBeNull(); + const cleared = clearRed(snapshot.redMain, { id: 3, conclusion: "success", included: { run: 1, firstBad: B, failures: snapshot.redMain.open!.failures } }, NOW + 1); + expect(store.publishRedMain(snapshot, cleared)).toBe(true); + expect(store.read().redMain.open).toBeNull(); + expect(store.read().redMain.last?.action).toBe("clear"); + }); +}); + +describe("main selection includes the open red set", () => { + test("a later main run that does not touch the red test's closure still runs it", () => { + // The planner itself runs end to end in the executable test below; this one + // pins how the open set widens a narrow docs-only plan. + const plan = { changed: ["docs/README.md"], typecheck: false, pack: false, unitTests: ["tests/docs.test.ts"], + local: { fullTests: false, runtime: false, browser: false, layout: false, captures: false, endurance: false } } as unknown as CheckPlan; + const replanned: string[][] = []; + const replan = (changed: string[]) => { replanned.push(changed); return { ...plan, changed, local: { ...plan.local } } as CheckPlan; }; + const record = openRed(emptyRedMain(), { firstBad: B, run: 11, failures: [failure("packages/core/tests/frontmatter.test.ts"), failure(null, "browser")] }, NOW); + const widened = includeRedSet(plan, record, replan); + expect(replanned, "RED_TEST_JOINS_THE_CLOSURE").toEqual([["docs/README.md", "packages/core/tests/frontmatter.test.ts"]]); + expect(widened.local.fullTests, "RED_UNIT_TEST_SELECTED_WITHOUT_CLOSURE_CHANGE").toBe(true); + expect(widened.local.browser, "RED_CATEGORY_SELECTED").toBe(true); + expect(widened.unitTests, "NARROWED_INVENTORY_NAMES_THE_RED_TEST").toEqual(["packages/core/tests/frontmatter.test.ts", "tests/docs.test.ts"]); + expect(widened.changed).toEqual(["docs/README.md"]); + expect(widened.redMain).toEqual({ run: 11, firstBad: B, failures: record.open!.failures }); + expect(includeRedSet(plan, emptyRedMain(), replan)).toBe(plan); + }); + + test("the planner executable pins one coordination snapshot and prints the included set", () => { + const { dir, git } = repo(); + git(dir, "init", "-q"); git(dir, "remote", "add", "origin", dir); + for (const name of ["core", "ui-sdk"]) { mkdirSync(join(dir, "packages", name, "src"), { recursive: true }); + writeFileSync(join(dir, "packages", name, "package.json"), JSON.stringify({ name: `@fixture/${name}`, files: ["src"] })); writeFileSync(join(dir, "packages", name, "src/index.ts"), "export {};\n"); } + mkdirSync(join(dir, "scripts")); mkdirSync(join(dir, "docs")); + writeFileSync(join(dir, "scripts/ci-plan.ts"), readFileSync(join(ROOT, "scripts/ci-plan.ts"), "utf8").replace('"typescript"', JSON.stringify(import.meta.resolve("typescript")))); + for (const name of ["browser-input-closure", "unit-test-consumers", "integration-reservation", "red-main"]) writeFileSync(join(dir, `scripts/${name}.ts`), `export * from ${JSON.stringify(join(ROOT, `scripts/${name}.ts`))};\n`); + writeFileSync(join(dir, "docs/notes.md"), "Ithaca.\n"); git(dir, "add", "."); git(dir, "commit", "-qm", "base"); + const before = git(dir, "rev-parse", "HEAD"); + writeFileSync(join(dir, "docs/notes.md"), "Ithaca, again.\n"); git(dir, "commit", "-qam", "docs only"); + const store = new GitReservationStore(dir); + expect(store.publishRedMain(store.read(), openRed(emptyRedMain(), { firstBad: before, run: 11, failures: [failure("packages/core/src/index.test.ts")] }, NOW))).toBe(true); + const oid = git(dir, "rev-parse", "refs/heads/brain-integration-reservation"); + const plan = (requested?: string) => { + const output = join(dir, `out-${requested ?? "resolve"}`), event = join(dir, "event.json"); + writeFileSync(event, JSON.stringify({ before })); + const p = Bun.spawnSync([process.execPath, join(dir, "scripts/ci-plan.ts")], { cwd: dir, stdout: "pipe", stderr: "pipe", env: { ...process.env, + GITHUB_EVENT_NAME: "push", GITHUB_EVENT_PATH: event, BEFORE_SHA: before, HEAD_SHA: "HEAD", GITHUB_OUTPUT: output, CI_PLAN_PATH: join(dir, "plan.json"), + ...(requested ? { RED_MAIN_OID: requested } : {}) } }); + expect(p.exitCode, new TextDecoder().decode(p.stderr)).toBe(0); + return { outputs: readFileSync(output, "utf8"), stdout: new TextDecoder().decode(p.stdout) }; + }; + const resolved = plan(); + expect(resolved.outputs).toContain(`red_main_oid=${oid}\n`); + expect(resolved.outputs, "PUSH_RUNS_RED_UNIT_TEST").toContain("unit=true\n"); + expect(includedRedSet(resolved.stdout)?.run).toBe(11); + // A later job receives the same snapshot even after the record changes. + expect(store.publishRedMain(store.read(), clearRed(store.read().redMain, { id: 12, conclusion: "success", included: { run: 11, firstBad: before, failures: store.read().redMain.open!.failures } }, NOW + 1))).toBe(true); + expect(plan(oid).outputs, "PINNED_SNAPSHOT").toContain("unit=true\n"); + expect(plan("none").outputs).toContain("unit=false\n"); + }); +}); + +describe("hosted gate", () => { + test("refuses a non-fix PR whose merge ref contains the bad SHA and admits a declared fix", () => { + const { dir, git } = repo(); + git(dir, "init", "-q"); git(dir, "remote", "add", "origin", dir); + writeFileSync(join(dir, "raft.md"), "1\n"); git(dir, "add", "."); git(dir, "commit", "-qm", "good"); + const good = git(dir, "rev-parse", "HEAD"); + writeFileSync(join(dir, "raft.md"), "2\n"); git(dir, "commit", "-qam", "bad"); + const bad = git(dir, "rev-parse", "HEAD"); + const store = new GitReservationStore(dir); + expect(store.publishRedMain(store.read(), declareFix(openRed(emptyRedMain(), { firstBad: bad, run: 11, failures: [failure("tests/raft.test.ts")] }, NOW), 8, NOW + 1))).toBe(true); + const gate = (pr: number) => { + const p = Bun.spawnSync([process.execPath, join(ROOT, "scripts/red-main-cli.ts"), "gate"], { cwd: dir, stdout: "pipe", stderr: "pipe", env: { ...process.env, PR_NUMBER: String(pr) } }); + return { code: p.exitCode, text: new TextDecoder().decode(p.stdout) + new TextDecoder().decode(p.stderr) }; + }; + const refused = gate(7); + expect(refused.code, "NON_FIX_CONTAINING_BAD_SHA_REFUSED").toBe(1); + expect(refused.text).toContain(`main red at ${bad}, incident pending`); + expect(gate(8).code, "DECLARED_FIX_ADMITTED").toBe(0); + git(dir, "checkout", "-q", good); + expect(gate(7).code, "MERGE_REF_WITHOUT_BAD_SHA_ADMITTED").toBe(0); + expect(gateDecision({ record: emptyRedMain(), pr: 7, contains: () => true }).refuse).toBe(false); + }); +}); + +/** In-memory GitHub plus a real-shape record store for the coordinator. */ +function fakeGitHub(options: { jobs: Job[]; junit?: string; closure?: boolean | null; pulls?: Record; prRuns?: WorkflowRun[]; history?: WorkflowRun[]; historyJobs?: Record }) { + let snapshot: Snapshot = { oid: null, redMain: emptyRedMain() }, version = 0, clock = NOW; + const issues: { number: number; title: string; body: string; labels: string[] }[] = []; + const comments: { issue: number; body: string }[] = [], cancelled: number[] = [], dispatched: unknown[] = [], events: unknown[] = []; + const io: CoordinatorIO = { + repository: "odysseus/brain-kit", + async json(path) { + if (path.startsWith("search/issues")) { + const query = decodeURIComponent(path.split("q=")[1]!.split("&")[0]!); + const phrase = /"([^"]+)"/.exec(query)?.[1] ?? ""; + return { items: issues.filter(issue => issue.body.includes(phrase) || issue.title.includes(phrase)) }; + } + const jobsMatch = /actions\/runs\/(\d+)\/attempts\/\d+\/jobs/.exec(path); + if (jobsMatch) return { jobs: Number(jobsMatch[1]) >= 100 ? options.jobs : options.historyJobs?.[Number(jobsMatch[1])] ?? [] }; + if (path.includes("ci.yml/runs?event=pull_request")) return { workflow_runs: path.includes("in_progress") ? options.prRuns ?? [] : [] }; + if (path.includes("ci.yml/runs?event=push")) return { workflow_runs: options.history ?? [] }; + const pulls = /commits\/([a-f0-9]{40})\/pulls/.exec(path); + if (pulls) return options.pulls?.[pulls[1]!] ? [{ number: options.pulls[pulls[1]!], merged_at: "2026-07-12T00:00:00Z" }] : []; + throw new Error(`Unexpected offline API ${path}`); + }, + async write(method, path, body: any) { + if (path.endsWith("/issues")) { const issue = { number: 500 + issues.length, ...body }; issues.push(issue); return issue; } + const comment = /issues\/(\d+)\/comments$/.exec(path); + if (comment) { comments.push({ issue: Number(comment[1]), body: body.body }); return {}; } + const cancel = /actions\/runs\/(\d+)\/cancel$/.exec(path); + if (cancel) { cancelled.push(Number(cancel[1])); return {}; } + if (path.endsWith("/dispatches")) { dispatched.push(body); return {}; } + throw new Error(`Unexpected offline write ${method} ${path}`); + }, + async now() { return clock += 1000; }, + read() { return { oid: String(version), redMain: snapshot.redMain }; }, + publish(seen, record) { if (seen.oid !== String(version)) return false; version++; snapshot = { oid: String(version), redMain: parseRedMain(JSON.stringify(record)) }; return true; }, + async artifactFiles(_run, name) { return name === "unit-proof-2" && options.junit ? [options.junit] : []; }, + async log() { return ""; }, + inClosure: () => options.closure ?? true, + range: (since, until) => since === A && until === C ? [B, C] : [], + isAncestor: (a, b) => a === b || (a === A && b !== A) || (a === B && b === C), + commitTime: () => NOW, + async recordEvent(event) { events.push(event); }, + print() {}, + }; + return { io, issues, comments, cancelled, dispatched, events, record: () => snapshot.redMain, set: (record: RedMainRecord) => { snapshot = { oid: String(++version), redMain: record }; } }; +} +const mainRun = (sha: string, conclusion: string, id = 100): WorkflowRun => ({ id, name: "CI", event: "push", head_branch: "main", head_sha: sha, status: "completed", conclusion, + run_attempt: 1, display_title: "squash", created_at: "2026-07-12T00:00:00Z" }); +const junit = `expect(received).toBe(expected)`; + +describe("coordinator", () => { + test("two coordinator runs for the same bad SHA and test leave exactly one incident issue and cancel doomed PR proof", async () => { + const gh = fakeGitHub({ jobs: [{ id: 1, name: "changeset", conclusion: "success" }, { id: 2, name: "unit (2)", conclusion: "failure", steps: [] }], junit, + prRuns: [{ ...mainRun(A, "", 300), event: "pull_request", head_branch: "feat", status: "in_progress", pull_requests: [{ number: 7 }], created_at: "2026-07-12T00:00:01Z" }, + { ...mainRun(A, "", 301), event: "pull_request", head_branch: "fix", status: "in_progress", pull_requests: [{ number: 8 }], created_at: "2026-07-12T00:00:01Z" }] }); + await coordinate(gh.io, mainRun(B, "failure")); + gh.set(declareFix(gh.record(), 8, NOW + 100_000)); + await coordinate(gh.io, mainRun(B, "failure")); + expect(gh.issues, "EXACTLY_ONE_INCIDENT_ISSUE").toHaveLength(1); + expect(gh.issues[0]!.body).toContain(incidentMarker(100)); + expect(gh.issues[0]!.title).toContain("packages/core/tests/raft.test.ts"); + expect(gh.record().open).toMatchObject({ firstBad: B, incident: 500, failures: [{ test: "packages/core/tests/raft.test.ts", reasons: ["in-affected-closure", "assertion-signature"] }] }); + // Before PR #8 is declared a fix both runs are doomed; afterwards only the non-fix run is cancelled. + expect(gh.cancelled, "DOOMED_NON_FIX_RUN_CANCELLED_FIX_KEPT").toEqual([300, 301, 300]); + }); + + test("a suspected flake files its test issue and dispatches a probe without declaring main red", async () => { + const gh = fakeGitHub({ jobs: [{ id: 2, name: "unit (2)", conclusion: "failure", steps: [] }], closure: false, + junit: junit.replace("expect(received).toBe(expected)", "") }); + await coordinate(gh.io, mainRun(B, "failure")); + expect(gh.record().open).toBeNull(); + expect(gh.record().suspects).toMatchObject([{ test: "packages/core/tests/raft.test.ts", probe: "pending", issue: 500 }]); + expect(gh.issues[0]!.title).toBe("test: suspected flake in packages/core/tests/raft.test.ts"); + expect(gh.dispatched).toEqual([{ ref: "main", inputs: { purpose: "flake", source_run: "100", sha: B, tests: JSON.stringify(["packages/core/tests/raft.test.ts"]) } }]); + // The failed probe reproduces it: main is declared red and the flake issue is updated. + await coordinate(gh.io, { ...mainRun(B, "failure", 200), name: "red-main-probe", event: "workflow_dispatch", display_title: `red-main probe flake 100 ${B}` }); + expect(gh.record().open?.failures[0]?.reasons).toEqual(["probe-reproduced"]); + expect(gh.comments.some(comment => comment.issue === 500 && comment.body.includes("**failed**"))).toBe(true); + }); + + test("first bad is the first commit after the last green run, and a squash landed while red is reported", async () => { + const history = [mainRun(A, "success", 90)]; + const gh = fakeGitHub({ jobs: [{ id: 2, name: "unit (2)", conclusion: "failure", steps: [] }], junit, history, + historyJobs: { 90: [{ id: 9, name: "unit (1)", conclusion: "success" }] }, pulls: { [C]: 7 } }); + await coordinate(gh.io, mainRun(C, "failure")); + expect(gh.record().open?.firstBad, "FIRST_RED_AFTER_LAST_GREEN").toBe(B); + expect(gh.dispatched.filter((d: any) => d.inputs.purpose === "bisect")).toHaveLength(2); + // The next main run's squash C lands while red without being a declared fix. + await coordinate(gh.io, mainRun(C, "failure", 101)); + expect(gh.comments.filter(comment => comment.issue === 7), "LANDED_WHILE_RED_REPORTED_ON_PR").toHaveLength(1); + expect(gh.comments.some(comment => comment.issue === 500 && comment.body.includes("landed while red"))).toBe(true); + expect(gh.events).toEqual([{ kind: "incident", pr: 7, run: 101, evidence: "https://github.com/odysseus/brain-kit/issues/500" }]); + expect(gh.record().open?.reported).toEqual([C]); + await coordinate(gh.io, mainRun(C, "failure", 102)); + expect(gh.comments.filter(comment => comment.issue === 7), "REPORTED_ONCE").toHaveLength(1); + }); + + test("a green main run clears the record only when it included the open set", async () => { + const gh = fakeGitHub({ jobs: [{ id: 1, name: "changeset", conclusion: "success" }] }); + const record = openRed(emptyRedMain(), { firstBad: B, run: 11, failures: [failure("tests/raft.test.ts")] }, NOW); + gh.set(record); + gh.io.log = async () => ""; + await coordinate(gh.io, mainRun(C, "success")); + expect(gh.record().open, "GREEN_WITHOUT_RED_SET_DOES_NOT_CLEAR").not.toBeNull(); + gh.io.log = async () => `2026-07-12T00:00:00Z BRAIN_RED_MAIN_INCLUDED ${JSON.stringify({ run: 11, firstBad: B, failures: record.open!.failures })}`; + await coordinate(gh.io, mainRun(C, "success", 103)); + expect(gh.record().open).toBeNull(); + expect(existsSync(ROOT)).toBe(true); + }); +});