From ca39339c9f3b62a3f56f74e8abb6aa53063ea66b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 09:35:25 +0000 Subject: [PATCH 1/3] feat(ci): let a draft PR request its affected heavy categories as hosted feedback Adds a feedback-heavy cadence, a generated heavy-feedback.yml that reuses ci.yml's category jobs and pins, the live-head admission and its yielding to ready confirmation, the request script, and refusals in the candidate gate. The aggregate is named 'draft heavy feedback' and is never proof. Refs #3272 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/heavy-feedback.yml | 473 +++++++++++++++++++++++++++ scripts/candidate-proof.ts | 2 + scripts/check-ci-workflows.ts | 43 +++ scripts/ci-plan.ts | 19 +- scripts/heavy-feedback-workflow.ts | 114 +++++++ scripts/heavy-feedback.ts | 108 ++++++ scripts/request-heavy-feedback.ts | 53 +++ tests/candidate-proof.test.ts | 9 + tests/ci-plan.test.ts | 16 + tests/heavy-feedback.test.ts | 150 +++++++++ 10 files changed, 982 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/heavy-feedback.yml create mode 100644 scripts/heavy-feedback-workflow.ts create mode 100644 scripts/heavy-feedback.ts create mode 100644 scripts/request-heavy-feedback.ts create mode 100644 tests/heavy-feedback.test.ts diff --git a/.github/workflows/heavy-feedback.yml b/.github/workflows/heavy-feedback.yml new file mode 100644 index 0000000000..3c6a8c3afe --- /dev/null +++ b/.github/workflows/heavy-feedback.yml @@ -0,0 +1,473 @@ +# Generated by scripts/heavy-feedback-workflow.ts from ci.yml; do not edit. +# Draft heavy feedback (#3272) runs a draft PR's affected heavy categories with +# the same jobs and pins as confirmation. It is never `proof`; request it with +# `bun scripts/request-heavy-feedback.ts `. +name: Draft heavy feedback +"on": + workflow_dispatch: + inputs: + pr: + description: Draft PR number + required: true + type: string + head_sha: + description: Exact live head SHA of that PR + required: true + type: string + pull_request: + types: + - synchronize + - ready_for_review + - closed +permissions: + contents: read + actions: read + checks: read +concurrency: + group: "heavy-feedback-${{ github.event.pull_request.number || inputs.pr }}" + cancel-in-progress: true +jobs: + supersede: + if: "github.event_name == 'pull_request'" + runs-on: ubuntu-24.04 + timeout-minutes: 1 + steps: + - name: "Cancel this PR's in-flight draft heavy feedback" + run: "echo 'A newer head or readiness change superseded draft heavy feedback for this PR.'" + changeset: + name: heavy feedback admission + if: "github.event_name == 'workflow_dispatch'" + runs-on: ubuntu-24.04 + timeout-minutes: 40 + outputs: + cadence: "${{ steps.plan.outputs.cadence }}" + endurance: "${{ steps.plan.outputs.endurance }}" + runtime: "${{ steps.plan.outputs.runtime }}" + runtime_host: "${{ steps.plan.outputs.runtime_host }}" + captures: "${{ steps.plan.outputs.captures }}" + layout: "${{ steps.plan.outputs.layout }}" + browser: "${{ steps.plan.outputs.browser }}" + unit: "${{ steps.plan.outputs.unit }}" + unit_shards: "${{ steps.plan.outputs.unit_shards }}" + verify: "${{ steps.plan.outputs.verify }}" + pack: "${{ steps.plan.outputs.pack }}" + run_browser: "${{ steps.reuse.outputs.run_browser }}" + run_layout: "${{ steps.reuse.outputs.run_layout }}" + base_sha: "${{ steps.admit.outputs.base_sha }}" + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 1 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + - run: bun install --frozen-lockfile + - name: "Refuse a stale, ready, closed or foreign head; yield to ready confirmation" + id: admit + env: + FEEDBACK_PR: "${{ inputs.pr }}" + FEEDBACK_HEAD_SHA: "${{ inputs.head_sha }}" + GH_TOKEN: "${{ github.token }}" + run: bun scripts/heavy-feedback.ts admit + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + ref: "${{ inputs.head_sha }}" + - run: bun install --frozen-lockfile + - name: "Plan the PR's affected selection with feedback-heavy cadence" + id: plan + env: + BASE_SHA: "${{ steps.admit.outputs.base_sha }}" + HEAD_SHA: "${{ inputs.head_sha }}" + 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 + verify: + needs: changeset + if: "needs.changeset.outputs.verify == 'true'" + runs-on: ubuntu-24.04 + timeout-minutes: 7 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + ref: "${{ inputs.head_sha }}" + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + - id: verify_install + timeout-minutes: 1 + run: bun install --frozen-lockfile + - name: Recompute the same affected selection + id: verify_plan + timeout-minutes: 1 + env: + BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" + HEAD_SHA: "${{ inputs.head_sha }}" + FEEDBACK_PR: "${{ inputs.pr }}" + run: bun scripts/ci-plan.ts + - name: Strict types and curated fast tests concurrently on this runner + id: verify_proof + timeout-minutes: 4 + env: + CI_COMMAND_RECEIPTS: tmp/verify-commands.jsonl + run: bun scripts/ci-runner.ts + - name: Verify setup and proof outcomes (best effort) + if: always() + env: + INSTALL_OUTCOME: "${{ steps.verify_install.outcome }}" + PLAN_OUTCOME: "${{ steps.verify_plan.outcome }}" + PROOF_OUTCOME: "${{ steps.verify_proof.outcome }}" + CI_COMMAND_RECEIPTS: tmp/verify-commands.jsonl + run: bun scripts/ci-verify-summary.ts + pack: + needs: changeset + if: "needs.changeset.outputs.pack == 'true'" + timeout-minutes: 5 + runs-on: ubuntu-24.04 + env: + GEMINI_API_KEY: "" + ANTHROPIC_API_KEY: "" + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + ref: "${{ inputs.head_sha }}" + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + - uses: actions/setup-node@v7 + with: + node-version: "24" + - run: bun install --frozen-lockfile + - run: bun run build --jobs=2 + - name: "Pack, install and probe every publishable package" + run: bun scripts/ci-pack.ts + unit: + needs: changeset + if: "needs.changeset.outputs.unit == 'true'" + runs-on: ubuntu-24.04 + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + shard: "${{ fromJSON(needs.changeset.outputs.unit_shards) }}" + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + ref: "${{ inputs.head_sha }}" + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + - run: bun install --frozen-lockfile --backend=copyfile + - name: Recompute affected proof on the actual checkout + env: + BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" + HEAD_SHA: "${{ inputs.head_sha }}" + FEEDBACK_PR: "${{ inputs.pr }}" + run: bun scripts/ci-plan.ts + - name: Real Chrome and offline Linux namespace prerequisites + id: runtime_setup + timeout-minutes: 12 + run: bash scripts/ci-runtime-setup.sh + - name: Complete unit proof + id: runtime_proof + timeout-minutes: 30 + env: + UNIT_SHARDS: "${{ strategy.job-total }}" + run: "bun scripts/ci-proof.ts unit --shard=${{ matrix.shard }}/\"$UNIT_SHARDS\"" + - name: Environment setup and proof outcomes + if: always() + env: + SETUP_OUTCOME: "${{ steps.runtime_setup.outcome }}" + PROOF_OUTCOME: "${{ steps.runtime_proof.outcome }}" + run: "printf 'Environment setup (infrastructure prerequisite, 12-minute limit): %s\\nProof (30-minute limit): %s\\n' \\\n \"$SETUP_OUTCOME\" \"$PROOF_OUTCOME\" >> \"$GITHUB_STEP_SUMMARY\"\n" + - name: Proof receipts and failure diagnostics + if: always() + uses: actions/upload-artifact@v7 + with: + name: "unit-proof-${{ matrix.shard }}" + path: "tmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/unit-memory.jsonl\ntmp/unit-report.xml\ntmp/unit-report-summary.json\ntmp/unit-worker-*.xml\ntmp/unit-worker-*.json\ntmp/unit-worker-diagnostics/\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 + runtime: + needs: changeset + if: "needs.changeset.outputs.runtime == 'true'" + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + ref: "${{ inputs.head_sha }}" + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + - run: bun install --frozen-lockfile + - name: Recompute affected proof on the actual checkout + env: + BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" + HEAD_SHA: "${{ inputs.head_sha }}" + FEEDBACK_PR: "${{ inputs.pr }}" + run: bun scripts/ci-plan.ts + - name: Real Chrome and offline Linux namespace prerequisites + id: runtime_setup + timeout-minutes: 12 + run: bash scripts/ci-runtime-setup.sh --native + - name: Complete runtime proof + id: runtime_proof + timeout-minutes: 15 + run: bun scripts/ci-proof.ts runtime + - name: Environment setup and proof outcomes + if: always() + env: + SETUP_OUTCOME: "${{ steps.runtime_setup.outcome }}" + PROOF_OUTCOME: "${{ steps.runtime_proof.outcome }}" + run: "printf 'Environment setup (infrastructure prerequisite, 12-minute limit): %s\\nProof (15-minute limit): %s\\n' \\\n \"$SETUP_OUTCOME\" \"$PROOF_OUTCOME\" >> \"$GITHUB_STEP_SUMMARY\"\n" + - name: Proof receipts and failure diagnostics + if: always() + uses: actions/upload-artifact@v7 + with: + name: runtime-proof + path: "tmp/native-host-proof/\ntmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/unit-report.xml\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 + runtime_host: + needs: changeset + if: "needs.changeset.outputs.runtime_host == 'true'" + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + ref: "${{ inputs.head_sha }}" + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + - run: bun install --frozen-lockfile + - name: Recompute affected proof on the actual checkout + env: + BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" + HEAD_SHA: "${{ inputs.head_sha }}" + FEEDBACK_PR: "${{ inputs.pr }}" + run: bun scripts/ci-plan.ts + - name: Real Chrome and offline Linux namespace prerequisites + id: runtime_setup + timeout-minutes: 12 + run: bash scripts/ci-runtime-setup.sh --native + - name: Start btrfs dead-root kernel trace + run: "mkdir -p tmp/native-host-proof\nsudo bash scripts/native-proof/dead-root-trace.sh start tmp/native-host-proof/dead-root-trace.txt\n" + - name: Start optional owned-loop kernel trace + continue-on-error: true + run: sudo python3 -I -S scripts/native-proof/loop-trace.py start tmp/native-host-proof/owned-loop-trace.json + - name: Complete native hosted runtime proof + id: runtime_proof + timeout-minutes: 15 + run: bun scripts/ci-proof.ts runtime_host + - name: Stop optional owned-loop kernel trace + continue-on-error: true + if: always() + run: sudo python3 -I -S scripts/native-proof/loop-trace.py stop + - name: Stop and classify btrfs dead-root kernel trace + if: always() + run: "sudo bash scripts/native-proof/dead-root-trace.sh stop\nif [ -f tmp/native-host-proof/dead-root-trace.txt ]; then\n bun scripts/native-proof/dead-root-trace.ts tmp/native-host-proof/dead-root-trace.txt tmp/native-host-proof\nfi\n" + - name: Environment setup and proof outcomes + if: always() + env: + SETUP_OUTCOME: "${{ steps.runtime_setup.outcome }}" + PROOF_OUTCOME: "${{ steps.runtime_proof.outcome }}" + run: "printf 'Environment setup (infrastructure prerequisite, 12-minute limit): %s\\nProof (15-minute limit): %s\\n' \\\n \"$SETUP_OUTCOME\" \"$PROOF_OUTCOME\" >> \"$GITHUB_STEP_SUMMARY\"\n" + - name: Proof receipts and failure diagnostics + if: always() + uses: actions/upload-artifact@v7 + with: + name: runtime-host-proof + path: "tmp/native-host-proof/\ntmp/reference-pool-proof/\ntmp/worker-identity-proof/\ntmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/unit-report.xml\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 + browser: + needs: changeset + if: "needs.changeset.outputs.browser == 'true' && needs.changeset.outputs.run_browser == 'true'" + runs-on: ubuntu-24.04 + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + shard: + - 1 + - 2 + - 3 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + ref: "${{ inputs.head_sha }}" + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + - run: bun install --frozen-lockfile + - name: Recompute affected proof on the actual checkout + env: + BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" + HEAD_SHA: "${{ inputs.head_sha }}" + FEEDBACK_PR: "${{ inputs.pr }}" + run: bun scripts/ci-plan.ts + - name: Complete browser proof + run: "bun scripts/ci-proof.ts browser --shard=${{ matrix.shard }}/3" + - name: Proof receipts and failure diagnostics + if: always() + uses: actions/upload-artifact@v7 + with: + name: "browser-proof-${{ matrix.shard }}" + path: "tmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/proof-cases.json\ntmp/unit-report.xml\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/diagram-export-native-prepared/*/*/release.svg\ntmp/diagram-export-native-prepared/*/*/release.png\ntmp/diagram-export-native-prepared/*/*/release.pdf\ntmp/diagram-export-native-prepared/*/*/origin.svg\ntmp/diagram-export-native-prepared/*/*/origin.png\ntmp/diagram-export-native-prepared/*/*/origin.pdf\ntmp/diagram-export-native-prepared/*/*/producer.json\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 + layout: + needs: changeset + if: "needs.changeset.outputs.layout == 'true' && needs.changeset.outputs.run_layout == 'true'" + runs-on: ubuntu-24.04 + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + shard: + - 1 + - 2 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + ref: "${{ inputs.head_sha }}" + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + - run: bun install --frozen-lockfile + - name: Recompute affected proof on the actual checkout + env: + BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" + HEAD_SHA: "${{ inputs.head_sha }}" + FEEDBACK_PR: "${{ inputs.pr }}" + run: bun scripts/ci-plan.ts + - name: Complete layout proof + run: "bun scripts/ci-proof.ts layout --shard=${{ matrix.shard }}/2" + - name: Proof receipts and failure diagnostics + if: always() + uses: actions/upload-artifact@v7 + with: + name: "layout-proof-${{ matrix.shard }}" + path: "tmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/proof-cases.json\ntmp/unit-report.xml\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/hygiene-proof/\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 + captures: + needs: changeset + if: "needs.changeset.outputs.captures == 'true'" + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + ref: "${{ inputs.head_sha }}" + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + - run: bun install --frozen-lockfile + - name: Recompute affected proof on the actual checkout + env: + BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" + HEAD_SHA: "${{ inputs.head_sha }}" + FEEDBACK_PR: "${{ inputs.pr }}" + run: bun scripts/ci-plan.ts + - name: Complete captures proof + run: bun scripts/ci-proof.ts captures + - name: Proof receipts and failure diagnostics + if: always() + uses: actions/upload-artifact@v7 + with: + name: captures-proof + path: "tmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/unit-report.xml\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 + endurance: + needs: changeset + if: "needs.changeset.outputs.endurance == 'true'" + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + ref: "${{ inputs.head_sha }}" + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + - run: bun install --frozen-lockfile + - name: Recompute affected proof on the actual checkout + env: + BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" + HEAD_SHA: "${{ inputs.head_sha }}" + FEEDBACK_PR: "${{ inputs.pr }}" + run: bun scripts/ci-plan.ts + - name: Complete endurance proof + run: bun scripts/ci-proof.ts endurance + - name: Proof receipts and failure diagnostics + if: always() + uses: actions/upload-artifact@v7 + with: + name: endurance-proof + path: "tmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/proof-cases.json\ntmp/unit-report.xml\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 + aggregate: + name: draft heavy feedback + needs: + - changeset + - verify + - pack + - unit + - runtime + - runtime_host + - browser + - layout + - captures + - endurance + if: "${{ always() && !cancelled() && github.event_name == 'workflow_dispatch' }}" + runs-on: ubuntu-24.04 + timeout-minutes: 3 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + - run: bun install --frozen-lockfile + - name: "Report every selected category; this is feedback, never proof" + env: + FEEDBACK_PR: "${{ inputs.pr }}" + FEEDBACK_HEAD_SHA: "${{ inputs.head_sha }}" + GH_TOKEN: "${{ github.token }}" + PROOF_NEEDS: "${{ toJSON(needs) }}" + run: bun scripts/heavy-feedback.ts aggregate \ No newline at end of file diff --git a/scripts/candidate-proof.ts b/scripts/candidate-proof.ts index 5c83b8a291..4ffd24d64b 100644 --- a/scripts/candidate-proof.ts +++ b/scripts/candidate-proof.ts @@ -8,6 +8,8 @@ const CONFIRMATION_REQUIRED = "Candidate confirmation required: convert this PR export async function validateCandidate(root: string, event: any, env: NodeJS.ProcessEnv, api?: API, actual: Checkout = checkout(root)): Promise { const cadence = proofCadence(env, event); + // Draft heavy feedback is never proof; only an exact-head ready confirmation is (#3272). + if (cadence === "feedback-heavy") throw new Error(`Draft heavy feedback is never proof. ${CONFIRMATION_REQUIRED}`); if (cadence === "feedback") throw new Error(CONFIRMATION_REQUIRED); if (cadence === "draft") return requireLiveDraft(event, api); if (cadence !== "confirmation") return; diff --git a/scripts/check-ci-workflows.ts b/scripts/check-ci-workflows.ts index 6cec99915b..cb71130b2e 100644 --- a/scripts/check-ci-workflows.ts +++ b/scripts/check-ci-workflows.ts @@ -2,6 +2,8 @@ import { existsSync, readFileSync, readdirSync } from "node:fs"; import { join, resolve } from "node:path"; import { PROOF_SHARDS, shardNumbers, type ShardedDomain } from "./proof-shards"; +import { FEEDBACK_AGGREGATE } from "./heavy-feedback"; +import { CATEGORY_JOBS, FEEDBACK_GROUP, renderHeavyFeedbackWorkflow } from "./heavy-feedback-workflow"; export const CI_WORKFLOWS = ["ci.yml", "contract.yml"] as const; const RUN_EXPRESSIONS = new Set(["matrix.shard", "github.event_name", "github.base_ref", "github.event.before"]); @@ -127,6 +129,7 @@ export function checkCIWorkflows(root: string): string[] { const expected = ["ci.yml", "contract.yml", "project-sync.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"); 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"); @@ -137,11 +140,51 @@ export function checkCIWorkflows(root: string): string[] { } const pages = join(directory, "publish-pages.yml"); if (existsSync(pages)) problems.push(...publicationWorkflowProblems(readFileSync(pages, "utf8"))); + const feedback = join(directory, "heavy-feedback.yml"); + if (existsSync(feedback) && existsSync(join(directory, "ci.yml"))) problems.push(...heavyFeedbackWorkflowProblems(readFileSync(feedback, "utf8"), readFileSync(join(directory, "ci.yml"), "utf8"))); const timings = join(directory, "ci-timings.yml"); if (existsSync(timings)) problems.push(...timingWorkflowProblems(readFileSync(timings, "utf8"))); return problems; } +/** Draft heavy feedback (#3272): ci.yml's own category jobs, per-PR cancellation, never `proof`. */ +export function heavyFeedbackWorkflowProblems(text: string, ciText: string): string[] { + const errors: string[] = [], fail = (message: string) => errors.push(`heavy-feedback.yml: ${message}`); + let workflow: Workflow & { concurrency?: Record }; + try { workflow = Bun.YAML.parse(text) as typeof workflow; } + catch { return ["heavy-feedback.yml: invalid YAML"]; } + if (!workflow || typeof workflow !== "object") return ["heavy-feedback.yml: workflow must be a mapping"]; + let rendered = ""; + try { rendered = renderHeavyFeedbackWorkflow(ciText); } catch (error) { fail(`cannot derive from ci.yml: ${String(error)}`); } + if (rendered && text !== rendered) fail("stale copy of ci.yml's category jobs and pins; run bun scripts/heavy-feedback-workflow.ts"); + if (/\bsecrets\.|\bpull_request_target\b|\bworkflow_run\b/.test(text)) fail("feedback must not expose secrets or privileged triggers"); + if (JSON.stringify(workflow.permissions) !== JSON.stringify({ contents: "read", actions: "read", checks: "read" })) fail("token must stay read-only"); + if (JSON.stringify(Object.keys(workflow.on ?? {}).sort()) !== JSON.stringify(["pull_request", "workflow_dispatch"])) fail("only a dispatch requests feedback; pull_request only cancels it"); + const inputs = (workflow.on?.workflow_dispatch as any)?.inputs; + if (inputs?.pr?.required !== true || inputs?.head_sha?.required !== true) fail("dispatch must name the PR and its exact head"); + if (workflow.concurrency?.group !== FEEDBACK_GROUP || workflow.concurrency?.["cancel-in-progress"] !== true) fail("at most one draft heavy run per PR: per-PR group with cancel-in-progress"); + const jobs = workflow.jobs ?? {}; + // A job's check name is its `name`, or its id when unnamed. + if (Object.entries(jobs).some(([id, job]) => String(job.name ?? id).trim().toLowerCase() === "proof")) fail("feedback must never be named proof"); + if (jobs.aggregate?.name !== FEEDBACK_AGGREGATE) fail(`aggregate must be named ${FEEDBACK_AGGREGATE}`); + if (JSON.stringify(jobs.aggregate?.needs) !== JSON.stringify(["changeset", ...CATEGORY_JOBS])) fail("aggregate must observe every selected category"); + if (!jobs.aggregate?.steps?.some(step => step.run === "bun scripts/heavy-feedback.ts aggregate") || + jobs.aggregate?.steps?.some(step => /ci-proof\.ts aggregate|candidate-proof/.test(step.run ?? ""))) fail("aggregate must report feedback without candidate receipts"); + const admission = jobs.changeset?.steps ?? []; + const admit = admission.findIndex(step => step.run === "bun scripts/heavy-feedback.ts admit"); + const headCheckout = admission.findIndex(step => step.uses?.startsWith("actions/checkout@") && step.with?.ref === "${{ inputs.head_sha }}"); + if (admit < 0 || headCheckout <= admit) fail("admission must refuse a stale, ready, closed or foreign head before checking it out"); + for (const [name, job] of Object.entries(jobs)) { + if (job["runs-on"] !== "ubuntu-24.04") fail(`${name}: unmapped GitHub-hosted runner`); + if (job.permissions !== undefined) fail(`${name}: job permissions must inherit the read-only workflow token`); + for (const step of job.steps ?? []) { + if (step.uses?.startsWith("actions/checkout@") && step.with?.["persist-credentials"] !== false) fail(`${name}: checkout credentials must not persist`); + for (const match of (step.run ?? "").matchAll(/\$\{\{\s*([^}]*?)\s*\}\}/g)) if (!RUN_EXPRESSIONS.has(match[1]!)) fail(`${name}: untrusted expression in run script: ${match[1]}`); + } + } + return errors; +} + /** Measurement is scheduled trusted code with no product-proof authority. */ export function timingWorkflowProblems(text: string): string[] { const errors: string[] = [], fail = (message: string) => errors.push(`ci-timings.yml: ${message}`); diff --git a/scripts/ci-plan.ts b/scripts/ci-plan.ts index f8907b640d..c9aaf7cb89 100644 --- a/scripts/ci-plan.ts +++ b/scripts/ci-plan.ts @@ -25,7 +25,7 @@ export const FAST_TESTS: Readonly> = { "tests/candidate-proof.test.ts", "tests/proof-inventory.test.ts", "tests/proof-reuse.test.ts", // 4.47s immutable source/input ownership controls (#1333). "tests/measurement-fixture-lifetime.test.ts", // 0.13s owner/exit regression (#1330). - "tests/ci-workflows.test.ts", "tests/release-manifest.test.ts", "tests/ci-pack.test.ts", + "tests/ci-workflows.test.ts", "tests/heavy-feedback.test.ts", "tests/release-manifest.test.ts", "tests/ci-pack.test.ts", "tests/lockfile.test.ts", "tests/changeset-gate.test.ts", "tests/contract-gate.test.ts", "tests/decision-citations.test.ts", "tests/dependency-edges.test.ts", @@ -391,10 +391,17 @@ export function unitShards(plan: CheckPlan): number[] { return Array.from({length: Math.min(4, count)}, (_, i) => i + 1); } -export type ProofCadence = "draft" | "feedback" | "confirmation" | "integrated" | "exhaustive"; +export type ProofCadence = "draft" | "feedback" | "feedback-heavy" | "confirmation" | "integrated" | "exhaustive"; -/** A request is an event, never a sticky label that can approve a later head. */ +/** A draft heavy feedback dispatch names its PR and head; ci.yml's bare dispatch declares no inputs. */ +export function heavyFeedbackDispatch(env: NodeJS.ProcessEnv, event: any): boolean { + return env.GITHUB_EVENT_NAME === "workflow_dispatch" && event?.inputs?.pr !== undefined && event?.inputs?.head_sha !== undefined; +} + +/** A request is an event, never a sticky label that can approve a later head. + * `feedback-heavy` selects like confirmation but is never proof (#3272). */ export function proofCadence(env: NodeJS.ProcessEnv, event: any): ProofCadence { + if (heavyFeedbackDispatch(env, event)) return "feedback-heavy"; if (env.GITHUB_EVENT_NAME === "pull_request") { if (event.pull_request?.draft === true) return "draft"; if (["opened", "reopened", "ready_for_review"].includes(event.action)) return "confirmation"; @@ -437,8 +444,10 @@ export function changedFiles(root: string, base: string, head = "HEAD", mergeBas } export function planFromEnvironment(root: string, env: NodeJS.ProcessEnv): CheckPlan { - if (["api", "schedule", "workflow_dispatch"].includes(env.GITHUB_EVENT_NAME ?? "")) return planChecks(["package.json"], workspaces(root), root); - const pr = env.GITHUB_EVENT_NAME === "pull_request"; + // 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); diff --git a/scripts/heavy-feedback-workflow.ts b/scripts/heavy-feedback-workflow.ts new file mode 100644 index 0000000000..8f3fe60e8e --- /dev/null +++ b/scripts/heavy-feedback-workflow.ts @@ -0,0 +1,114 @@ +/** Generates `.github/workflows/heavy-feedback.yml` from `ci.yml` (#3272). + * + * Draft heavy feedback must run the same category jobs and pins as candidate + * confirmation. Rather than a hand-maintained copy, the category jobs are + * copied from ci.yml and only their checkout ref and planner environment are + * replaced. `bun run lint` refuses a stale file through check-ci-workflows.ts. + * + * bun scripts/heavy-feedback-workflow.ts # rewrite the workflow + * bun scripts/heavy-feedback-workflow.ts --check # fail if it is stale + */ +import { readFileSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { FEEDBACK_AGGREGATE } from "./heavy-feedback"; + +export const CATEGORY_JOBS = ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"] as const; +export const FEEDBACK_GROUP = "heavy-feedback-${{ github.event.pull_request.number || inputs.pr }}"; +const HEAD = "${{ inputs.head_sha }}"; +const DISPATCH = "github.event_name == 'workflow_dispatch'"; + +type Step = Record & { uses?: string; run?: string; with?: Record; env?: Record }; +type Job = Record & { steps: Step[] }; + +const clone = (value: T): T => JSON.parse(JSON.stringify(value)); +const pinned = (job: Job, action: string): Step => { + const step = job.steps.find(s => s.uses?.startsWith(`${action}@`)); + if (!step) throw new Error(`ci.yml changeset job lost its ${action} pin`); + return clone(step); +}; + +/** Category jobs check out the requested head and plan it against the admitted PR base. */ +function categoryJob(job: Job): Job { + const copy = clone(job); + for (const step of copy.steps) { + if (step.uses?.startsWith("actions/checkout@")) step.with = { ...step.with, ref: HEAD }; + if (step.run === "bun scripts/ci-plan.ts") step.env = { + BASE_SHA: "${{ needs.changeset.outputs.base_sha }}", HEAD_SHA: HEAD, FEEDBACK_PR: "${{ inputs.pr }}", + }; + } + return copy; +} + +export function renderHeavyFeedbackWorkflow(ciText: string): string { + const ci = Bun.YAML.parse(ciText) as { jobs: Record }; + const metadata = ci.jobs.changeset!; + 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"); + 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. + const workflow = { + name: "Draft heavy feedback", + on: { + workflow_dispatch: { inputs: { + pr: { description: "Draft PR number", required: true, type: "string" }, + head_sha: { description: "Exact live head SHA of that PR", required: true, type: "string" }, + } }, + // A push, a ready transition or closing the PR cancels its in-flight feedback run. + pull_request: { types: ["synchronize", "ready_for_review", "closed"] }, + }, + permissions: { contents: "read", actions: "read", checks: "read" }, + concurrency: { group: FEEDBACK_GROUP, "cancel-in-progress": true }, + jobs: { + supersede: { + if: "github.event_name == 'pull_request'", + "runs-on": "ubuntu-24.04", "timeout-minutes": 1, + steps: [{ name: "Cancel this PR's in-flight draft heavy feedback", run: "echo 'A newer head or readiness change superseded draft heavy feedback for this PR.'" }], + }, + changeset: { + name: "heavy feedback admission", + if: DISPATCH, + "runs-on": "ubuntu-24.04", + // 30 minutes of bounded yielding to ready confirmation + planning. + "timeout-minutes": 40, + outputs, + steps: [ + { ...clone(checkout), with: { ...checkout.with, "fetch-depth": 1 } }, + clone(bun), clone(install), + { 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: "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" }, + ], + }, + ...Object.fromEntries(CATEGORY_JOBS.map(name => [name, categoryJob(ci.jobs[name]!)])), + aggregate: { + name: FEEDBACK_AGGREGATE, + needs: ["changeset", ...CATEGORY_JOBS], + if: `\${{ always() && !cancelled() && ${DISPATCH} }}`, + "runs-on": "ubuntu-24.04", "timeout-minutes": 3, + steps: [clone(checkout), clone(bun), clone(install), + { name: "Report every selected category; this is feedback, never proof", + env: { ...request, PROOF_NEEDS: "${{ toJSON(needs) }}" }, run: "bun scripts/heavy-feedback.ts aggregate" }], + }, + }, + }; + return "# Generated by scripts/heavy-feedback-workflow.ts from ci.yml; do not edit.\n" + + "# Draft heavy feedback (#3272) runs a draft PR's affected heavy categories with\n" + + "# the same jobs and pins as confirmation. It is never `proof`; request it with\n" + + "# `bun scripts/request-heavy-feedback.ts `.\n" + Bun.YAML.stringify(workflow, null, 2); +} + +if (import.meta.main) { + const root = resolve(import.meta.dir, ".."); + const target = join(root, ".github/workflows/heavy-feedback.yml"); + const rendered = renderHeavyFeedbackWorkflow(readFileSync(join(root, ".github/workflows/ci.yml"), "utf8")); + if (process.argv.includes("--check")) { + let current = ""; + try { current = readFileSync(target, "utf8"); } catch {} + if (current !== rendered) { console.error("heavy-feedback.yml is stale: run bun scripts/heavy-feedback-workflow.ts"); process.exit(1); } + } else writeFileSync(target, rendered); +} diff --git a/scripts/heavy-feedback.ts b/scripts/heavy-feedback.ts new file mode 100644 index 0000000000..abd8fde70d --- /dev/null +++ b/scripts/heavy-feedback.ts @@ -0,0 +1,108 @@ +/** Draft heavy feedback: affected heavy categories on a draft head, never proof (#3272). + * + * `admit` runs first in `.github/workflows/heavy-feedback.yml`. It reads the + * live PR and refuses unless it is open, a draft, from this repository and at + * exactly the requested head. It then yields to ready confirmation: it waits + * while the exact-candidate integration reservation holds a live lease, and + * while another feedback run already occupies the repository-wide slot. + * `aggregate` reports the selected categories under the `draft heavy + * feedback` check. It prints no candidate receipt, and the merge gate never + * reads this workflow. Policy: docs/decisions/ci-utility.md, "Hosted heavy + * feedback on draft heads". + */ +import { appendFileSync } from "node:fs"; +import { proofProblems } from "./ci-proof"; +import { liveLease, parseReservation, RESERVATION_REF } from "./integration-reservation"; +import { GitHubProofAPI, type API } from "./proof-reuse"; + +export const FEEDBACK_WORKFLOW = "heavy-feedback.yml"; +export const FEEDBACK_AGGREGATE = "draft heavy feedback"; +/** Feedback runs allowed in flight repository-wide, counting the admitted run. */ +export const FEEDBACK_SLOTS = 2; +export const ADMISSION_WAIT_MS = 30 * 60_000, ADMISSION_POLL_MS = 30_000; + +export interface FeedbackRequest { repository: string; pr: number; head: string; } +export interface LiveDraft { base: string; head: string; } + +/** Parses workflow inputs; strings arrive from `workflow_dispatch`, never trusted as shell text. */ +export function feedbackRequest(env: NodeJS.ProcessEnv): FeedbackRequest { + const pr = Number(env.FEEDBACK_PR), head = env.FEEDBACK_HEAD_SHA ?? "", repository = env.GITHUB_REPOSITORY ?? ""; + if (!/^[1-9]\d{0,9}$/.test(env.FEEDBACK_PR ?? "") || !Number.isSafeInteger(pr)) throw new Error("Draft heavy feedback requires a positive PR number"); + if (!/^[a-f0-9]{40}$/.test(head)) throw new Error("Draft heavy feedback requires the exact 40-character head SHA"); + if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) throw new Error("Draft heavy feedback requires GITHUB_REPOSITORY"); + return { repository, pr, head }; +} + +/** The live PR must be an open same-repository draft at exactly the requested head. */ +export async function requireLiveDraftHead(api: API, request: FeedbackRequest): Promise { + const live = await api.json(`pulls/${request.pr}`); + if (live?.state !== "open") throw new Error(`Draft heavy feedback refused: PR #${request.pr} is not open`); + if (live.draft !== true) throw new Error(`Draft heavy feedback refused: PR #${request.pr} is ready; ready PRs get proof through candidate confirmation`); + if (live.head?.repo?.full_name !== request.repository || live.base?.repo?.full_name !== request.repository) throw new Error(`Draft heavy feedback refused: PR #${request.pr} is not a branch of ${request.repository}`); + if (live.head?.sha !== request.head) throw new Error(`Draft heavy feedback refused: the live head ${String(live.head?.sha)} differs from the requested ${request.head}`); + if (!/^[a-f0-9]{40}$/.test(live.base?.sha ?? "")) throw new Error("Draft heavy feedback refused: the live PR base is unavailable"); + return { base: live.base.sha, head: live.head.sha }; +} + +/** Why this run must wait for ready confirmation or another feedback run, or undefined when admitted. */ +export async function yieldReason(api: API, ownRun: number, now: number): Promise { + let reservation: any; + try { reservation = await api.json(`contents/reservation.json?ref=${encodeURIComponent(RESERVATION_REF.replace("refs/heads/", ""))}`); } + catch (error) { if (!/\b404\b/.test(String(error))) throw error; } + if (reservation) { + if (reservation.encoding !== "base64" || typeof reservation.content !== "string") throw new Error("Unreadable integration reservation state"); + const state = parseReservation(Buffer.from(reservation.content, "base64").toString("utf8")); + if (liveLease(state.active, now)) return `ready confirmation holds the integration reservation for PR #${state.active.candidate.pr}`; + } + const others: number[] = []; + for (const status of ["in_progress", "queued"]) { + const result = await api.json(`actions/workflows/${FEEDBACK_WORKFLOW}/runs?event=workflow_dispatch&status=${status}&per_page=100`); + if (!Array.isArray(result?.workflow_runs)) throw new Error("Missing draft heavy feedback run inventory"); + for (const run of result.workflow_runs) if (Number.isSafeInteger(run?.id) && run.id !== ownRun && !others.includes(run.id)) others.push(run.id); + } + if (others.length >= FEEDBACK_SLOTS - 1) return `${others.length} other draft heavy feedback run(s) in flight (${others.join(", ")}); at most ${FEEDBACK_SLOTS} run at once`; + return undefined; +} + +export interface AdmitOptions { ownRun: number; clock?: () => number; sleep?: (ms: number) => Promise; log?: (line: string) => void; waitMs?: number; pollMs?: number; } + +/** Bounded admission: the head is rechecked on every poll, so a push refuses a waiting run. + * Each poll gets a fresh client, because one proof API client has a short request budget. */ +export async function admit(client: () => API, request: FeedbackRequest, options: AdmitOptions): Promise { + const clock = options.clock ?? Date.now, sleep = options.sleep ?? Bun.sleep, log = options.log ?? console.log; + const deadline = clock() + (options.waitMs ?? ADMISSION_WAIT_MS); + for (;;) { + const api = client(); + const live = await requireLiveDraftHead(api, request); + const reason = await yieldReason(api, options.ownRun, clock()); + if (!reason) return live; + if (clock() >= deadline) throw new Error(`Draft heavy feedback yielded for the whole admission window: ${reason}. Request it again later.`); + log(`Waiting: ${reason}.`); + await sleep(options.pollMs ?? ADMISSION_POLL_MS); + } +} + +/** Same category policy as the proof aggregate, without its candidate identity: this is feedback. */ +export function feedbackProblems(needs: Parameters[0]): string[] { + if (needs?.changeset?.outputs?.cadence !== "feedback-heavy") return ["admission did not plan a feedback-heavy selection"]; + return proofProblems(needs); +} + +if (import.meta.main) { + try { + const command = process.argv[2]; + const request = feedbackRequest(process.env); + if (process.env.GITHUB_EVENT_NAME !== "workflow_dispatch") throw new Error("Draft heavy feedback runs only from its dispatch"); + if (!process.env.GH_TOKEN) throw new Error("Draft heavy feedback requires a read-only GitHub token"); + const token = process.env.GH_TOKEN; + if (command === "admit") { + const live = await admit(() => new GitHubProofAPI(request.repository, token), request, { ownRun: Number(process.env.GITHUB_RUN_ID) }); + if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `base_sha=${live.base}\n`); + console.log(`BRAIN_FEEDBACK_ADMISSION ${JSON.stringify({ pr: request.pr, head: live.head, base: live.base })}`); + } else if (command === "aggregate") { + const problems = feedbackProblems(JSON.parse(process.env.PROOF_NEEDS ?? "null")); + if (problems.length) throw new Error(problems.join("\n")); + console.log(`Draft heavy feedback passed for PR #${request.pr} at ${request.head}. This is feedback, not proof: request candidate confirmation after the final push.`); + } else throw new Error("Usage: bun scripts/heavy-feedback.ts admit|aggregate"); + } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); } +} diff --git a/scripts/request-heavy-feedback.ts b/scripts/request-heavy-feedback.ts new file mode 100644 index 0000000000..1d30c2831e --- /dev/null +++ b/scripts/request-heavy-feedback.ts @@ -0,0 +1,53 @@ +/** Request draft heavy feedback for a PR's live head (#3272). Feedback is never proof. + * + * bun scripts/request-heavy-feedback.ts [--json] + * + * Reads the live head, dispatches `.github/workflows/heavy-feedback.yml` from + * the default branch with that PR number and head SHA, and prints the run URL. + * `--json` prints the run identity. A newer request or push for the same PR + * cancels the earlier run. Policy: docs/decisions/ci-utility.md, "Hosted heavy + * feedback on draft heads". + */ +import { FEEDBACK_WORKFLOW, requireLiveDraftHead } from "./heavy-feedback"; +import type { API } from "./proof-reuse"; + +/** One `gh` invocation: argv plus optional stdin, resolving stdout. */ +export type GH = (args: string[], input?: string) => Promise; + +export interface FeedbackRun { pr: number; head: string; base: string; workflow: string; run: number; url: string; api: string; } + +export async function requestHeavyFeedback(gh: GH, repository: string, pr: number): Promise { + if (!Number.isSafeInteger(pr) || pr < 1) throw new Error("Usage: bun scripts/request-heavy-feedback.ts [--json]"); + const api: API = { async json(path) { return JSON.parse(await gh(["api", `repos/${repository}/${path}`])); }, + async log() { throw new Error("Draft heavy feedback requests read no logs"); } }; + const head = (await api.json(`pulls/${pr}`))?.head?.sha; + if (!/^[a-f0-9]{40}$/.test(head ?? "")) throw new Error(`PR #${pr} has no readable head`); + // Refuse locally what the workflow would refuse, before spending a dispatch. + const live = await requireLiveDraftHead(api, { repository, pr, head }); + const branch = JSON.parse(await gh(["api", `repos/${repository}`]))?.default_branch; + if (typeof branch !== "string" || !branch) throw new Error("Default branch unavailable"); + // The dispatch endpoint answers 200 with workflow_run_id, run_url and html_url. + const body = await gh(["api", "--method", "POST", `repos/${repository}/actions/workflows/${FEEDBACK_WORKFLOW}/dispatches`, "--input", "-"], + JSON.stringify({ ref: branch, inputs: { pr: String(pr), head_sha: live.head } })); + const response = body ? JSON.parse(body) : undefined; + if (!Number.isSafeInteger(response?.workflow_run_id) || typeof response.html_url !== "string" || typeof response.run_url !== "string") throw new Error("GitHub accepted the dispatch without returning its run identity"); + return { pr, head: live.head, base: live.base, workflow: FEEDBACK_WORKFLOW, run: response.workflow_run_id, url: response.html_url, api: response.run_url }; +} + +async function gh(args: string[], input?: string): Promise { + const child = Bun.spawn(["gh", ...args], { stdin: input === undefined ? "ignore" : new TextEncoder().encode(input), stdout: "pipe", stderr: "pipe" }); + 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(err.trim() || `gh exited ${code}`); + return out.trim(); +} + +if (import.meta.main) { + try { + const args = process.argv.slice(2), json = args.includes("--json"); + const rest = args.filter(arg => arg !== "--json"); + if (rest.length !== 1 || !/^[1-9]\d*$/.test(rest[0]!)) throw new Error("Usage: bun scripts/request-heavy-feedback.ts [--json]"); + const repository = process.env.BRAIN_KIT_REPOSITORY ?? "schlessera/brain-kit"; + const run = await requestHeavyFeedback(gh, repository, Number(rest[0])); + console.log(json ? JSON.stringify(run, null, 2) : run.url); + } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); } +} diff --git a/tests/candidate-proof.test.ts b/tests/candidate-proof.test.ts index e4d5648233..fd6fe7a202 100644 --- a/tests/candidate-proof.test.ts +++ b/tests/candidate-proof.test.ts @@ -87,3 +87,12 @@ test("the hosted entry point reads live readiness through its own API client", a } expect(reads).toEqual(Array(2).fill(`https://api.github.com/repos/${env.GITHUB_REPOSITORY}/pulls/7`)); }); + +test("the candidate gate refuses a draft heavy feedback dispatch as proof (#3272)", async () => { + const dispatch = { inputs: { pr: "7", head_sha: actual.parents[1] } }; + const feedbackEnv = { GITHUB_EVENT_NAME: "workflow_dispatch", GITHUB_SHA: actual.sha, GITHUB_REPOSITORY: env.GITHUB_REPOSITORY }; + expect(proofCadence(feedbackEnv, dispatch)).toBe("feedback-heavy"); + // ci.yml's bare dispatch declares no inputs and stays exhaustive. + expect(proofCadence(feedbackEnv, { inputs: {} })).toBe("exhaustive"); + await expect(validateCandidate("unused", dispatch, feedbackEnv, api(), actual), "FEEDBACK_IS_NEVER_PROOF").rejects.toThrow("Draft heavy feedback is never proof"); +}); diff --git a/tests/ci-plan.test.ts b/tests/ci-plan.test.ts index 224317fea5..c0db06949d 100644 --- a/tests/ci-plan.test.ts +++ b/tests/ci-plan.test.ts @@ -466,3 +466,19 @@ test("browser closure composition preserves exact consumer inventories and bound expect(unitShards(selectBrowserClosures(base, { browser: closed, layout: closed, endurance: closed, captures: closed }))).toEqual([1, 2, 3, 4]); expect(selected.local.runtime).toBe(plan.local.runtime); }); + +test("feedback-heavy cadence selects a changed ui-server file's heavy categories; draft selects none (#3272)", () => { + const f = fixture(); f.write("packages/ui-server/src/route.ts", "export const route = 1;\n"); + f.git("add", "."); f.git("commit", "-qm", "ui-server change"); + const env = { BASE_SHA: f.base, HEAD_SHA: "HEAD", FEEDBACK_PR: "7" }; + const dispatch = { inputs: { pr: "7", head_sha: "a".repeat(40) } }; + const plan = planFromEnvironment(f.dir, { ...env, GITHUB_EVENT_NAME: "workflow_dispatch" }); + expect(plan.global, "FEEDBACK_PLANS_THE_PR_NOT_EXHAUSTIVE").toBe(false); + expect(plan.changed).toEqual(["packages/ui-server/src/route.ts"]); + plan.cadence = proofCadence({ GITHUB_EVENT_NAME: "workflow_dispatch" }, dispatch); + expect(plan.cadence).toBe("feedback-heavy"); + const heavy = proofSelections(plan); + for (const category of ["unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"]) expect(heavy[category], `FEEDBACK_HEAVY_${category}`).toBe(true); + const draft = { ...plan, cadence: "draft" as const }; + expect(Object.values(proofSelections(draft)).some(Boolean), "DRAFT_STAYS_CHEAP").toBe(false); +}); diff --git a/tests/heavy-feedback.test.ts b/tests/heavy-feedback.test.ts new file mode 100644 index 0000000000..4ab823e660 --- /dev/null +++ b/tests/heavy-feedback.test.ts @@ -0,0 +1,150 @@ +/** Draft heavy feedback (#3272): exact live draft head, bounded yielding, never proof. */ +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { admit, FEEDBACK_AGGREGATE, feedbackProblems, feedbackRequest, requireLiveDraftHead, yieldReason } from "../scripts/heavy-feedback"; +import { FEEDBACK_GROUP, renderHeavyFeedbackWorkflow } from "../scripts/heavy-feedback-workflow"; +import { heavyFeedbackWorkflowProblems } from "../scripts/check-ci-workflows"; +import { requestHeavyFeedback, type GH } from "../scripts/request-heavy-feedback"; +import { verifyIntegrationProof } from "../scripts/integration-proof"; +import { MAX_MS } from "../scripts/integration-reservation"; +import type { API } from "../scripts/proof-reuse"; + +const ROOT = resolve(import.meta.dir, ".."); +const REPO = "odysseus/brain-kit"; +const HEAD = "a".repeat(40), BASE = "b".repeat(40); +const request = { repository: REPO, pr: 7, head: HEAD }; +const draft = { state: "open", draft: true, head: { sha: HEAD, repo: { full_name: REPO } }, base: { sha: BASE, repo: { full_name: REPO } } }; + +function fake(replies: Record, paths: string[] = []): API { + return { + async json(path) { + paths.push(path); + if (!(path in replies)) throw new Error(`Unexpected request ${path}`); + const reply = replies[path]; + if (reply instanceof Error) throw reply; + return typeof reply === "function" ? reply() : reply; + }, + async log() { throw new Error("UNEXPECTED_LOG_READ"); }, + }; +} +const RESERVATION = "contents/reservation.json?ref=brain-integration-reservation"; +const runs = (ids: number[]) => ({ workflow_runs: ids.map(id => ({ id })) }); +const idle = (pull: unknown = draft, others: number[] = []) => ({ + "pulls/7": pull, [RESERVATION]: new Error("Proof API refused 404"), + "actions/workflows/heavy-feedback.yml/runs?event=workflow_dispatch&status=in_progress&per_page=100": runs([41, ...others]), + "actions/workflows/heavy-feedback.yml/runs?event=workflow_dispatch&status=queued&per_page=100": runs([]), +}); + +test("the live-head check admits only an open same-repository draft at the requested head", async () => { + expect(await requireLiveDraftHead(fake({ "pulls/7": draft }), request)).toEqual({ base: BASE, head: HEAD }); + for (const [label, pull, message] of [ + ["MISMATCHED_SHA", { ...draft, head: { ...draft.head, sha: "c".repeat(40) } }, "differs from the requested"], + ["READY_PR", { ...draft, draft: false }, "is ready"], + ["CLOSED_PR", { ...draft, state: "closed" }, "is not open"], + ["FOREIGN_HEAD", { ...draft, head: { ...draft.head, repo: { full_name: "suitor/brain-kit" } } }, "is not a branch of"], + ] as const) { + await expect(requireLiveDraftHead(fake({ "pulls/7": pull }), request), label).rejects.toThrow(message); + } +}); + +test("workflow inputs must be a positive PR number and an exact SHA", () => { + const env = { FEEDBACK_PR: "7", FEEDBACK_HEAD_SHA: HEAD, GITHUB_REPOSITORY: REPO }; + expect(feedbackRequest(env)).toEqual(request); + expect(() => feedbackRequest({ ...env, FEEDBACK_PR: "7; true" })).toThrow("positive PR number"); + expect(() => feedbackRequest({ ...env, FEEDBACK_HEAD_SHA: "main" })).toThrow("exact 40-character head SHA"); +}); + +test("admission yields to a live ready-confirmation lease and to the repository-wide feedback slot", async () => { + const now = 1_000_000; + const lease = { id: "f".repeat(32), actor: 3, candidate: { repository: "https://github.com/odysseus/brain-kit", pr: 9, head: HEAD, base: BASE }, + acquired: now - 1000, expires: now + 60_000, cap: now - 1000 + MAX_MS }; + const state = { version: 1, updated: now - 1000, active: lease, last: { action: "acquire", actor: 3, at: now - 1000, previous: null } }; + const content = { encoding: "base64", content: Buffer.from(JSON.stringify(state)).toString("base64") }; + expect(await yieldReason(fake({ ...idle(), [RESERVATION]: content }), 41, now), "YIELDS_TO_CONFIRMATION").toContain("PR #9"); + expect(await yieldReason(fake({ ...idle(), [RESERVATION]: content }), 41, lease.expires), "EXPIRED_LEASE_ADMITS").toBeUndefined(); + expect(await yieldReason(fake(idle(draft, [52])), 41, now), "ONE_OTHER_RUN_FILLS_THE_SLOTS").toContain("52"); + expect(await yieldReason(fake(idle()), 41, now), "OWN_RUN_DOES_NOT_COUNT").toBeUndefined(); +}); + +test("a waiting admission rechecks the live head and stays bounded", async () => { + let clock = 0; const waits: string[] = []; + const options = { ownRun: 41, clock: () => clock, sleep: async (ms: number) => { clock += ms; }, log: (line: string) => waits.push(line), waitMs: 90_000, pollMs: 30_000 }; + await expect(admit(() => fake(idle(draft, [52])), request, options), "BOUNDED_WAIT").rejects.toThrow("yielded for the whole admission window"); + expect(waits).toHaveLength(3); + clock = 0; let polls = 0; + const pushedWhileWaiting = () => (++polls > 1 ? { ...draft, head: { ...draft.head, sha: "c".repeat(40) } } : draft); + await expect(admit(() => fake(idle(pushedWhileWaiting, [52])), request, options), "PUSH_REFUSES_WAITING_RUN").rejects.toThrow("differs from the requested"); + expect(await admit(() => fake(idle()), request, options)).toEqual({ base: BASE, head: HEAD }); +}); + +test("the request script reads the live head, dispatches it from the default branch and returns the run identity", async () => { + const calls: { args: string[]; input?: string }[] = []; + const gh = (pull: unknown): GH => async (args, input) => { + calls.push({ args, input }); + if (args.join(" ") === `api repos/${REPO}/pulls/7`) return JSON.stringify(pull); + if (args.join(" ") === `api repos/${REPO}`) return JSON.stringify({ default_branch: "main" }); + if (args.join(" ") === `api --method POST repos/${REPO}/actions/workflows/heavy-feedback.yml/dispatches --input -`) + return JSON.stringify({ workflow_run_id: 99, run_url: `https://api.github.com/repos/${REPO}/actions/runs/99`, html_url: `https://github.com/${REPO}/actions/runs/99` }); + throw new Error(`Unexpected gh ${args.join(" ")}`); + }; + expect(await requestHeavyFeedback(gh(draft), REPO, 7)).toEqual({ pr: 7, head: HEAD, base: BASE, workflow: "heavy-feedback.yml", + run: 99, url: `https://github.com/${REPO}/actions/runs/99`, api: `https://api.github.com/repos/${REPO}/actions/runs/99` }); + expect(JSON.parse(calls.at(-1)!.input!)).toEqual({ ref: "main", inputs: { pr: "7", head_sha: HEAD } }); + calls.length = 0; + await expect(requestHeavyFeedback(gh({ ...draft, draft: false }), REPO, 7), "READY_REQUEST_REFUSED").rejects.toThrow("is ready"); + expect(calls.some(call => call.args.includes("POST")), "NO_DISPATCH_AFTER_REFUSAL").toBe(false); +}); + +test("the feedback aggregate requires its own cadence and every selected category", () => { + const outputs = { cadence: "feedback-heavy", verify: "true", pack: "false", unit: "true", browser: "false", layout: "false", captures: "false", runtime: "false", runtime_host: "false", endurance: "false" }; + const needs: Record }> = { changeset: { result: "success", outputs }, + verify: { result: "success" }, unit: { result: "success" }, ...Object.fromEntries(["pack", "browser", "layout", "captures", "runtime", "runtime_host", "endurance"].map(name => [name, { result: "skipped" }])) }; + expect(feedbackProblems(needs)).toEqual([]); + expect(feedbackProblems({ ...needs, unit: { result: "failure" } })).toEqual(["unit: selected proof did not pass (failure)"]); + expect(feedbackProblems({ ...needs, changeset: { result: "success", outputs: { ...outputs, cadence: "confirmation" } } })).toEqual(["admission did not plan a feedback-heavy selection"]); +}); + +test("the workflow is ci.yml's category jobs with per-PR cancellation and an aggregate never named proof", () => { + const ci = readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"); + const text = readFileSync(join(ROOT, ".github/workflows/heavy-feedback.yml"), "utf8"); + expect(text, "GENERATED_FROM_CI").toBe(renderHeavyFeedbackWorkflow(ci)); + expect(heavyFeedbackWorkflowProblems(text, ci)).toEqual([]); + const workflow = Bun.YAML.parse(text) as any, source = Bun.YAML.parse(ci) as any; + expect(workflow.concurrency).toEqual({ group: "heavy-feedback-${{ github.event.pull_request.number || inputs.pr }}", "cancel-in-progress": true }); + expect(FEEDBACK_GROUP).toBe(workflow.concurrency.group); + 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"); + 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])); + expect(workflow.jobs[name].steps.map((step: any) => step.run ?? step.uses)).toEqual(source.jobs[name].steps.map((step: any) => step.run ?? step.uses)); + expect(workflow.jobs[name]["timeout-minutes"]).toBe(source.jobs[name]["timeout-minutes"]); + } + for (const [label, mutated, problem] of [ + ["NO_CANCELLATION", text.replace("cancel-in-progress: true", "cancel-in-progress: false"), "at most one draft heavy run per PR"], + ["GLOBAL_GROUP", text.replace(FEEDBACK_GROUP, "heavy-feedback"), "at most one draft heavy run per PR"], + ["NAMED_PROOF", text.replace(`name: ${FEEDBACK_AGGREGATE}`, "name: proof"), "never be named proof"], + ["STALE_COPY", text.replace("timeout-minutes: 45", "timeout-minutes: 44"), "stale copy"], + ] as const) expect(heavyFeedbackWorkflowProblems(mutated, ci).join("\n"), label).toContain(problem); +}); + +test("the merge gate refuses a PR whose only heavy evidence is a draft heavy feedback run", async () => { + const candidate = { repository: `https://github.com/${REPO}`, pr: 7, head: HEAD, base: BASE }; + const run = (id: number, extra: Record = {}) => ({ id, run_attempt: 1, event: "pull_request", head_sha: HEAD, status: "completed", conclusion: "success", + repository: { html_url: candidate.repository }, head_repository: { html_url: candidate.repository }, pull_requests: [{ number: 7 }], ...extra }); + const job = (name: string, conclusion = "success") => ({ id: name.length, name, status: "completed", conclusion, run_id: 17, head_sha: HEAD }); + const paths: string[] = []; + const api = fake({ + // The draft ci.yml run passed its cheap gates and skipped every heavy category. + [`actions/workflows/ci.yml/runs?event=pull_request&head_sha=${HEAD}&per_page=10`]: { workflow_runs: [run(17)] }, + [`actions/workflows/contract.yml/runs?event=pull_request&head_sha=${HEAD}&per_page=10`]: { workflow_runs: [run(18)] }, + "actions/runs/17/attempts/1/jobs?per_page=100": { total_count: 3, jobs: [job("changeset"), job("draft gates"), job("unit", "skipped")] }, + // The feedback run ran the heavy categories, but the gate never reads it. + [`actions/workflows/heavy-feedback.yml/runs?event=workflow_dispatch&head_sha=${HEAD}&per_page=10`]: { workflow_runs: [run(21, { event: "workflow_dispatch", pull_requests: [] })] }, + }, paths); + await expect(verifyIntegrationProof("unused", REPO, candidate, api, () => { throw new Error("UNEXPECTED_CHECKOUT_FETCH"); }), "FEEDBACK_IS_NOT_MERGE_EVIDENCE") + .rejects.toThrow("Missing complete candidate aggregate"); + expect(paths.some(path => path.includes("heavy-feedback"))).toBe(false); +}); From 76c53bcfac0713c553b192a59e2fba10f78ea359 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 09:36:07 +0000 Subject: [PATCH 2/3] docs(ci): record how draft heavy feedback runs and route heavy iteration to it Refs #3272 Co-Authored-By: Claude Opus 5.5 --- .agents/skills/work-issue/SKILL.md | 6 ++- .../work-issue/references/ci-and-merge.md | 8 ++++ docs/decisions/ci-utility.md | 41 ++++++++++++++++++- 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/.agents/skills/work-issue/SKILL.md b/.agents/skills/work-issue/SKILL.md index 77d60c37b4..f1be15a346 100644 --- a/.agents/skills/work-issue/SKILL.md +++ b/.agents/skills/work-issue/SKILL.md @@ -272,7 +272,11 @@ pinned browser/layout/offline/endurance/editorial and native runtime categories. Missing tools, skipped runtimes, failures/cancellations and unexpected job skips leave selected hosted proof incomplete. Never delete tests, weaken offline harnesses or rerun a real failure to obtain green. Keep drafts cheap and batch -pushes. A ready PR synchronize event runs fast feedback with a deliberately +pushes. For heavy iteration on a draft (native, runtime, browser, layout, +endurance or complete unit categories), request hosted feedback with +`bun scripts/request-heavy-feedback.ts ` instead of running long suites +locally. It needs no reservation, a newer push or request cancels it, and its +`draft heavy feedback` result is never `proof`. A ready PR synchronize event runs fast feedback with a deliberately nonpassing final gate. Before `confirm`, run `bun scripts/collisions.ts --json --pr ` and record its collisions (or none) with the PR head in the PR. For ordinary candidates, acquire the exact-candidate integration reservation with `bun scripts/integrate.ts confirm --issues owner/repo#N,...` before diff --git a/.agents/skills/work-issue/references/ci-and-merge.md b/.agents/skills/work-issue/references/ci-and-merge.md index 5cb6cd8e01..a779e39c98 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -38,6 +38,14 @@ runtimes, failures/cancellations and unexpected skips leave proof unfinished. Keep drafts cheap and batch pushes. Ready synchronize runs fast feedback and leaves `proof` nonpassing; convert to draft and mark ready after the final push to request candidate confirmation. Open/reopen ready events also request it. +For heavy iteration on a draft, run `bun scripts/request-heavy-feedback.ts +` (`--json` prints the run identity). It dispatches the PR's affected heavy +categories at its live head without the reservation, and refuses a ready, +closed, foreign or moved head. A newer request or push cancels the earlier run, +and admission waits while a ready confirmation holds the reservation. Its +aggregate, `draft heavy feedback`, is feedback only: the merge gate never reads +it, and exact-head ready confirmation remains the only `proof`. Use long local +suites only to debug a specific failure. Draft runs report `draft gates`, not `proof`. A ready PR without a passing `proof` from its confirmation run is unconfirmed, even if `draft gates` passed or failed because its live read found the PR ready; request confirmation again. diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 1d21b87ddb..4cfcd14633 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1451,7 +1451,46 @@ The dispatch workflow and request script are [#3272](https://github.com/schlessera/brain-kit/issues/3272). The `check:pr` and guidance changes are [#3273](https://github.com/schlessera/brain-kit/issues/3273). Runner-slot wait is [#2952](https://github.com/schlessera/brain-kit/issues/2952). -Until #3272 lands, drafts keep running cheap gates only. + +#### How the request runs + +`bun scripts/request-heavy-feedback.ts ` reads the live head and +dispatches `.github/workflows/heavy-feedback.yml` from the default branch with +the PR number and that SHA. It prints the run URL, or the run identity with +`--json`. A dispatch can only start a workflow file that exists on the default +branch, so the request always runs main's admission code. + +- **Same jobs and pins.** `scripts/heavy-feedback-workflow.ts` generates the + workflow from `ci.yml`. It copies the category jobs and replaces only their + checkout ref, which becomes the requested head, and their planner + environment. `bun run lint` refuses a stale copy, so a change to a + category job in `ci.yml` regenerates this file in the same PR. +- **Exact head.** The admission job refuses unless the live PR is open, a + draft, from this repository and at exactly the requested SHA. It checks this + again on every wait poll. It then plans the PR's affected selection against + the live PR base with the `feedback-heavy` cadence, which selects what + confirmation would. +- **Never proof.** The aggregate is named `draft heavy feedback` and prints no + candidate receipt. The candidate gate refuses the `feedback-heavy` cadence. + The merge gate reads only `ci.yml`'s `pull_request` runs and their `proof` + job, so a feedback run cannot satisfy it. +- **One run per PR.** The concurrency group is + `heavy-feedback-` with `cancel-in-progress`. The same workflow also runs + a one-step job on the PR's `synchronize`, `ready_for_review` and `closed` + events. That job joins the group and so cancels the in-flight feedback run. +- **Ready confirmations first.** GitHub Actions has no job priority. The + chosen approximation is admission-time yielding. The admission job waits + while the exact-candidate integration reservation holds a live lease, + because every ordinary confirmation runs under one. It also waits while + another feedback run is queued or in progress, which caps feedback at two + runs repository-wide. Waiting polls every 30 seconds and refuses after 30 + minutes. A confirmation requested after a feedback run was admitted still + competes with that run for runners. A ready transition cancels the PR's own + feedback run. The [#2952](https://github.com/schlessera/brain-kit/issues/2952) + runner-slot wait measures whether this is enough. +- **Red main.** The refusal while main is red is the red-main gate from + [#2942](https://github.com/schlessera/brain-kit/issues/2942). Whichever of + #2942 and #3272 lands second adds that gate to the admission job. ## Historical measurement and upstream guidance From 0ada7ba7c48ad052398b5bb691a484b78b200235 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 12:25:07 +0000 Subject: [PATCH 3/3] fix(ci): compare the generated feedback workflow by structure, not bytes Hosted CI pins Bun 1.4.2, whose YAML stringifier leaves a space after each mapping key, so the byte comparison reported a fresh file as stale. Refs #3272 Co-Authored-By: Claude Opus 5.5 --- scripts/check-ci-workflows.ts | 4 ++-- scripts/heavy-feedback-workflow.ts | 9 ++++++++- tests/heavy-feedback.test.ts | 6 ++++-- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/scripts/check-ci-workflows.ts b/scripts/check-ci-workflows.ts index cb71130b2e..53c1246203 100644 --- a/scripts/check-ci-workflows.ts +++ b/scripts/check-ci-workflows.ts @@ -3,7 +3,7 @@ import { existsSync, readFileSync, readdirSync } from "node:fs"; import { join, resolve } from "node:path"; import { PROOF_SHARDS, shardNumbers, type ShardedDomain } from "./proof-shards"; import { FEEDBACK_AGGREGATE } from "./heavy-feedback"; -import { CATEGORY_JOBS, FEEDBACK_GROUP, renderHeavyFeedbackWorkflow } from "./heavy-feedback-workflow"; +import { CATEGORY_JOBS, FEEDBACK_GROUP, renderHeavyFeedbackWorkflow, sameWorkflow } from "./heavy-feedback-workflow"; export const CI_WORKFLOWS = ["ci.yml", "contract.yml"] as const; const RUN_EXPRESSIONS = new Set(["matrix.shard", "github.event_name", "github.base_ref", "github.event.before"]); @@ -156,7 +156,7 @@ export function heavyFeedbackWorkflowProblems(text: string, ciText: string): str if (!workflow || typeof workflow !== "object") return ["heavy-feedback.yml: workflow must be a mapping"]; let rendered = ""; try { rendered = renderHeavyFeedbackWorkflow(ciText); } catch (error) { fail(`cannot derive from ci.yml: ${String(error)}`); } - if (rendered && text !== rendered) fail("stale copy of ci.yml's category jobs and pins; run bun scripts/heavy-feedback-workflow.ts"); + if (rendered && !sameWorkflow(text, rendered)) fail("stale copy of ci.yml's category jobs and pins; run bun scripts/heavy-feedback-workflow.ts"); if (/\bsecrets\.|\bpull_request_target\b|\bworkflow_run\b/.test(text)) fail("feedback must not expose secrets or privileged triggers"); if (JSON.stringify(workflow.permissions) !== JSON.stringify({ contents: "read", actions: "read", checks: "read" })) fail("token must stay read-only"); if (JSON.stringify(Object.keys(workflow.on ?? {}).sort()) !== JSON.stringify(["pull_request", "workflow_dispatch"])) fail("only a dispatch requests feedback; pull_request only cancels it"); diff --git a/scripts/heavy-feedback-workflow.ts b/scripts/heavy-feedback-workflow.ts index 8f3fe60e8e..cf70ec5d1a 100644 --- a/scripts/heavy-feedback-workflow.ts +++ b/scripts/heavy-feedback-workflow.ts @@ -102,6 +102,13 @@ export function renderHeavyFeedbackWorkflow(ciText: string): string { "# `bun scripts/request-heavy-feedback.ts `.\n" + Bun.YAML.stringify(workflow, null, 2); } +/** Freshness compares parsed structure: Bun's YAML stringifier whitespace differs + * between versions (1.4.2 leaves a space after each mapping key), and hosted CI + * pins an older Bun than a developer may run. Any job, pin or timeout change still differs. */ +export function sameWorkflow(text: string, rendered: string): boolean { + try { return Bun.deepEquals(Bun.YAML.parse(text), Bun.YAML.parse(rendered), true); } catch { return false; } +} + if (import.meta.main) { const root = resolve(import.meta.dir, ".."); const target = join(root, ".github/workflows/heavy-feedback.yml"); @@ -109,6 +116,6 @@ if (import.meta.main) { if (process.argv.includes("--check")) { let current = ""; try { current = readFileSync(target, "utf8"); } catch {} - if (current !== rendered) { console.error("heavy-feedback.yml is stale: run bun scripts/heavy-feedback-workflow.ts"); process.exit(1); } + if (!sameWorkflow(current, rendered)) { console.error("heavy-feedback.yml is stale: run bun scripts/heavy-feedback-workflow.ts"); process.exit(1); } } else writeFileSync(target, rendered); } diff --git a/tests/heavy-feedback.test.ts b/tests/heavy-feedback.test.ts index 4ab823e660..b6562aefa1 100644 --- a/tests/heavy-feedback.test.ts +++ b/tests/heavy-feedback.test.ts @@ -3,7 +3,7 @@ import { expect, test } from "bun:test"; import { readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { admit, FEEDBACK_AGGREGATE, feedbackProblems, feedbackRequest, requireLiveDraftHead, yieldReason } from "../scripts/heavy-feedback"; -import { FEEDBACK_GROUP, renderHeavyFeedbackWorkflow } from "../scripts/heavy-feedback-workflow"; +import { FEEDBACK_GROUP, renderHeavyFeedbackWorkflow, sameWorkflow } from "../scripts/heavy-feedback-workflow"; import { heavyFeedbackWorkflowProblems } from "../scripts/check-ci-workflows"; import { requestHeavyFeedback, type GH } from "../scripts/request-heavy-feedback"; import { verifyIntegrationProof } from "../scripts/integration-proof"; @@ -108,8 +108,10 @@ test("the feedback aggregate requires its own cadence and every selected categor test("the workflow is ci.yml's category jobs with per-PR cancellation and an aggregate never named proof", () => { const ci = readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"); const text = readFileSync(join(ROOT, ".github/workflows/heavy-feedback.yml"), "utf8"); - expect(text, "GENERATED_FROM_CI").toBe(renderHeavyFeedbackWorkflow(ci)); + expect(sameWorkflow(text, renderHeavyFeedbackWorkflow(ci)), "GENERATED_FROM_CI").toBe(true); expect(heavyFeedbackWorkflowProblems(text, ci)).toEqual([]); + // Hosted CI pins Bun 1.4.2, whose stringifier leaves a space after each mapping key. + expect(heavyFeedbackWorkflowProblems(text.replace(/^(\s*[A-Za-z_"-]+:)$/gm, "$1 "), ci), "STRINGIFIER_WHITESPACE_IS_NOT_DRIFT").toEqual([]); const workflow = Bun.YAML.parse(text) as any, source = Bun.YAML.parse(ci) as any; expect(workflow.concurrency).toEqual({ group: "heavy-feedback-${{ github.event.pull_request.number || inputs.pr }}", "cancel-in-progress": true }); expect(FEEDBACK_GROUP).toBe(workflow.concurrency.group);