diff --git a/.agents/skills/github/SKILL.md b/.agents/skills/github/SKILL.md index 047d32d5a0..a36d993d75 100644 --- a/.agents/skills/github/SKILL.md +++ b/.agents/skills/github/SKILL.md @@ -401,7 +401,7 @@ Complete repeatable proof is authoritative in affected hosted jobs under #1326; cancelled checks and unexpected skips cannot pass. Keep drafts cheap and batch pushes. Independent selected jobs run after metadata, with per-PR cancellation. Assess new base commits before refreshing: revalidate affected inputs, preserve -the actual tested head/base. Any base advance needs a new candidate-confirmation event; equivalent browser/layout domains may retain verified receipts. +the actual tested head/base. Any base advance needs a new candidate-confirmation event, and every selected category runs fresh on it. Inspect selected job checkouts and the proof aggregate before matching-head merge; verify the actual squash and automatic main push afterward. diff --git a/.agents/skills/work-issue/references/ci-and-merge.md b/.agents/skills/work-issue/references/ci-and-merge.md index c5b9d606eb..913228fb9e 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -54,20 +54,20 @@ 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. The candidate gate checks actual merge parents/tree against the live head/base. -A changed base requires a fresh confirmation event even without a rebase; -valid immutable browser/layout retention remains available. Read the actual +A changed base requires a fresh confirmation event even without a rebase. +Read the actual `refs/pull//merge` commit too: GitHub can retain its old base across a draft/ready transition. When that ref still has old parents, refresh the branch against live main before requesting confirmation; another same-head event alone does not establish a new combined tree. Endurance is fresh and separately mandatory whenever selected. Assess relevant base changes before redoing -heavy work; a new base requires confirmation, with valid browser/layout retention avoiding unnecessary execution. -Under #1333, a selected browser/layout domain may intentionally skip fresh -execution after complete input equivalence and original successful run/attempt/ -job/check/checkout receipts are validated. Inspect the current retention ledger -and independently validating aggregate. Preserve original identities; do not -describe retained jobs as executions on the new SHA. Native/Git-dependent and -unknown domains, main pushes and scheduled/manual coverage remain fresh. +heavy work; a new base requires confirmation. +Every selected category runs fresh, on ready confirmation, main pushes and +scheduled/manual coverage alike. Browser proof retention is retired (#4107): +a selected job that was skipped is missing proof, never a retained pass, and no +test pins a source file's hash, so a product edit never needs a re-audit. +Inspect the aggregate, and never describe an earlier run's jobs as executions +on the new SHA. A draft-to-ready transition can retain GitHub's previous PR base and synthetic merge ref even after live main advances. Before requesting expensive confirmation, @@ -129,7 +129,11 @@ Forks use ordinary `pull_request` with a read-only token (`contents: read`, plus `actions: read` / `checks: read` for bounded proof lookup), no secrets and nonpersisted checkout credentials; an approval-held run has not passed. Drafts run cheap gates only, and tests-only changes may intentionally skip -packaging while complete affected tests run. Read actual GitHub checks +packaging while complete affected tests run. One job is the exception: when a +PR adds or modifies a Bun test file, `determinism` repeats those files under +CPU load at every cadence, drafts included, and `draft gates` and `proof` +require it. A failing repetition is fixed in the test, never rerun +([the gate](../../../../docs/process/testing.md#changed-tests-repeat-under-load)). Read actual GitHub checks and logs for the current head, never an old Depot receipt or latest-main run. GitHub checks/statuses may include additional gates. No rows, queued/running checks or cancelled runs are not green. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2c50eb3f8b..b3fad4f056 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,7 +12,6 @@ on: permissions: contents: read actions: read - checks: read # Cancel obsolete PR heads. Preserve every integrated main commit's evidence. concurrency: @@ -21,6 +20,8 @@ concurrency: # Drafts run cheap gates; synchronize gives fast feedback. Open/ready/reopen # requests final affected confirmation. The proof gate refuses intermediate feedback. +# One job is selected at every pull-request cadence, drafts included: `determinism` +# repeats the Bun test files a change adds or modifies under CPU load (#4109). # Independent jobs start together; each PR owns its cancellation group (#1326). jobs: changeset: @@ -38,9 +39,7 @@ jobs: 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 }} - reuse: ${{ steps.reuse.outputs.reuse }} + determinism: ${{ steps.plan.outputs.determinism }} red_main_oid: ${{ steps.plan.outputs.red_main_oid }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 @@ -74,14 +73,8 @@ 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 + # Plan outputs are set before any metadata gate below can fail, so a main + # push still runs its complete selected proof (#2942). - name: Lint, leakage and contribution workflow guards run: bun run lint - name: Env documentation matches its descriptors @@ -98,14 +91,12 @@ jobs: elif [ "$GITHUB_EVENT_NAME" = push ]; then bun scripts/check-changeset.ts "$BEFORE_SHA" fi - - name: Retention ledger and diagnostics + - name: Product scenario inventory if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: - name: proof-reuse-ledger - path: | - tmp/proof-reuse.json - tmp/proof-inventory.json + name: proof-inventory + path: tmp/proof-inventory.json if-no-files-found: warn retention-days: 7 @@ -422,7 +413,7 @@ jobs: browser: needs: changeset - if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && 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' }} runs-on: ubuntu-24.04 timeout-minutes: 20 strategy: @@ -487,7 +478,7 @@ jobs: layout: needs: changeset - if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && 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' }} runs-on: ubuntu-24.04 timeout-minutes: 25 strategy: @@ -651,10 +642,66 @@ jobs: if-no-files-found: warn retention-days: 7 + determinism: + # A changed test that passes once can still fail on someone else's merge (#4109). + needs: changeset + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.determinism == 'true' }} + runs-on: ubuntu-24.04 + # 12 minutes setup + 40 minutes proof + 3 minutes for other steps. + timeout-minutes: 55 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + fetch-depth: 0 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: "1.4.2" + # Native source freezes require dependency inodes owned by this checkout. + - run: bun install --frozen-lockfile --backend=copyfile + - name: Recompute affected proof on the actual checkout + env: + 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 + # The unit job's prerequisites: a changed file may drive real Chrome or the offline namespaces. + - name: Real Chrome and offline Linux namespace prerequisites + id: runtime_setup + timeout-minutes: 12 + run: bash scripts/ci-runtime-setup.sh + - name: Repeat changed Bun test files under CPU load + id: runtime_proof + timeout-minutes: 40 + run: bun scripts/ci-proof.ts determinism + - 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 (40-minute limit): %s\n' \ + "$SETUP_OUTCOME" "$PROOF_OUTCOME" >> "$GITHUB_STEP_SUMMARY" + - name: Proof receipts and failure diagnostics + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: determinism-proof + path: | + tmp/determinism-report.json + tmp/determinism-junit.xml + tmp/proof-checkout.json + tmp/proof-resources.json + tmp/runner-disk.json + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 + proof: name: ${{ github.event_name != 'pull_request' && 'integrated or exhaustive proof' || github.event.pull_request.draft && 'draft gates' || 'proof' }} # Evaluate even after failures or skips; never interpret missing selected proof as green. - needs: [changeset, verify, pack, unit, runtime, runtime_host, browser, layout, captures, endurance] + needs: [changeset, verify, pack, unit, runtime, runtime_host, browser, layout, captures, endurance, determinism] if: ${{ always() && !cancelled() }} runs-on: ubuntu-24.04 timeout-minutes: 3 diff --git a/.github/workflows/heavy-feedback.yml b/.github/workflows/heavy-feedback.yml index ffebb5177c..9d43b82ffb 100644 --- a/.github/workflows/heavy-feedback.yml +++ b/.github/workflows/heavy-feedback.yml @@ -22,7 +22,6 @@ name: Draft heavy feedback permissions: contents: read actions: read - checks: read concurrency: group: "heavy-feedback-${{ github.event.pull_request.number || inputs.pr }}" cancel-in-progress: true @@ -51,8 +50,7 @@ jobs: 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 }}" + determinism: "${{ steps.plan.outputs.determinism }}" red_main_oid: "${{ steps.plan.outputs.red_main_oid }}" base_sha: "${{ steps.admit.outputs.base_sha }}" steps: @@ -88,9 +86,6 @@ jobs: 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: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.verify == 'true' }}" @@ -305,7 +300,7 @@ jobs: retention-days: 7 browser: needs: changeset - if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && 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' }}" runs-on: ubuntu-24.04 timeout-minutes: 20 strategy: @@ -344,7 +339,7 @@ jobs: retention-days: 7 layout: needs: changeset - if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && 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' }}" runs-on: ubuntu-24.04 timeout-minutes: 25 strategy: @@ -444,6 +439,50 @@ jobs: include-hidden-files: true if-no-files-found: warn retention-days: 7 + determinism: + needs: changeset + if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.determinism == 'true' }}" + runs-on: ubuntu-24.04 + timeout-minutes: 55 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + fetch-depth: 0 + ref: "${{ inputs.head_sha }}" + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # 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: Repeat changed Bun test files under CPU load + id: runtime_proof + timeout-minutes: 40 + run: bun scripts/ci-proof.ts determinism + - 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 (40-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@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: determinism-proof + path: "tmp/determinism-report.json\ntmp/determinism-junit.xml\ntmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/runner-disk.json\n" + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 aggregate: name: draft heavy feedback needs: @@ -457,6 +496,7 @@ jobs: - layout - captures - endurance + - determinism if: "${{ always() && !cancelled() && github.event_name == 'workflow_dispatch' }}" runs-on: ubuntu-24.04 timeout-minutes: 3 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a834207ca3..c7a539639b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -84,10 +84,12 @@ Before instrumenting installed dependencies, follow [dependency diagnostic preparation](docs/process/diagnostic-installs.md): worktrees alone do not isolate Bun cache hardlinks. -The native diagram producer has no frozen qualification pin -([#4105](https://github.com/schlessera/brain-kit/issues/4105)): adding, -removing or upgrading a dependency needs no requalification, and its proof -runs fresh in the producer's Docker boundary. A frozen lockfile still does not +No test pins the hash of a source file or of the installation +([#4105](https://github.com/schlessera/brain-kit/issues/4105), +[#4107](https://github.com/schlessera/brain-kit/issues/4107)): editing product +source, or adding, removing or upgrading a dependency, needs no re-audit or +requalification. Browser proof runs fresh whenever it is selected, and the +native diagram producer runs in its Docker boundary. A frozen lockfile still does not repair a modified shared package cache, and copying that cache copies the modifications ([#1980](https://github.com/schlessera/brain-kit/issues/1980)). When a check fails on installed bytes, recover only the owned checkout through @@ -219,7 +221,9 @@ real Chrome and required namespaces may not silently skip. The final `proof` check requires every selected category to pass. Scheduled/manual exhaustive runs supplement affected PR proof; they do not replace it. -Drafts stay on cheap gates. Opening/reopening a ready PR or marking it ready +Drafts stay on cheap gates, plus one job: a PR that adds or modifies a Bun +test file has those files repeated under CPU load +([why](docs/process/testing.md#changed-tests-repeat-under-load)). Opening/reopening a ready PR or marking it ready requests affected candidate confirmation of the fast categories (types, packaging, unit/integration); heavy runtime, browser, layout, capture and endurance proof runs on the squash's own main run @@ -237,7 +241,7 @@ Record actual head/base, job/attempt IDs, checkout logs and focused local receipts in the PR. Missing tools, failed/cancelled jobs and unexpected skips leave proof incomplete. The candidate gate requires the live head/base to match the tested merge checkout; a base advance requires a new confirmation request, without inherently -requiring a rebase. Admitted immutable browser-domain retention remains available. Preserve +requiring a rebase. Preserve the earlier tested tree rather than attributing it to a new base. Relevant input/dependency/harness changes require fresh proof; unknown changes expand conservatively. There is no generic cache of passing tests. Respect branch rules @@ -292,7 +296,7 @@ invalid tables fail visibly. Refresh explicitly from one successful CI run attempt in which every shard of the domain, as configured in `PROOF_SHARDS` (`scripts/proof-shards.ts`), ran fresh and succeeded: `bun scripts/refresh-browser-costs.ts [browser|layout]` -(browser by default). Cancelled, partial or retained-only proof supplies no +(browser by default). Cancelled or partial proof supplies no measurements. Review the source head/checkout/tree, job IDs and seconds/median metadata alongside the table. Unsharded discovery is unchanged and existing browser file concurrency is kept. diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 3eba406465..e4d1d390cb 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -26,6 +26,18 @@ escaping or unsupported inputs retain the previous broad selection. Exact source matching detects a changed call site; it does not prove an arbitrary runtime target is bounded. Do not declare an owner as its own target to conceal unknown inputs. +Identical indirect expressions can name exact lexical function scopes; stale, +ambiguous or shadowed bindings remain unresolved. A declaration can instead +name the one runner observation class, which admits only literal Linux boot +identity, self status and self PID-namespace queries through unshadowed +imported filesystem readers. Those values are runner observations, never Git +blobs or repository payloads. + +No script resolves an edge by pinning source bytes. The audited bindings that +did were [retired with proof retention](#retaining-complete-browser-domains) +(#4107): an edge the walk cannot follow leaves the category unresolved, and it +keeps the broad rule. + Runtime-selected configuration/modules and backend imports can prevent a closed category. That is a conservative result, not permission to discard an edge. The shared Vitest config imports the dispatch command; its real application fixture @@ -540,8 +552,8 @@ with `bun scripts/refresh-browser-costs.ts [browser|layout]` (the default remains browser). Each domain retains its own run/attempt/job, checkout/tree/parent and pinned-image provenance. Refresh requires fresh successful jobs from every shard of a successful CI run, matching actual checkouts, complete -reported project/file coverage and source/image attribution; cancelled, -partial or retained-only proof supplies no measurements. Refreshing one domain +reported project/file coverage and source/image attribution; cancelled or +partial proof supplies no measurements. Refreshing one domain preserves the other's costs and provenance. Reviewed CI reports are measurement inputs, never runtime dependencies. Layout refresh admits ordinary `ui-react-layout` measurements; `ui-react-endurance` remains a separate mandatory @@ -670,9 +682,7 @@ outcome never establishes a definite timeout cause. A successful proof step without affirmative completion evidence fails summary validation. A forced whole-job cancellation can prevent the summary itself; absence is unknown/nonpassing, never a promise of completion. These controls -preserve aggregate refusal and all offline and proof-reuse rules. Changing -the audited coordinator invalidates optional generated-build binding until a -separate post-merge re-audit under #2408; this repair does not repin it. +preserve aggregate refusal and all offline rules. Hosted unit partitions use a queue capped at two serial Bun test processes (`scripts/unit-workers.ts`), or one when only one file is selected. Native @@ -928,147 +938,96 @@ commit/tree/parents to the requested head/base and live PR readiness/head plus an independently queried base ref. A changed base requires a new confirmation request, even when a reviewer considers that base change unrelated. This is a conservative identity rule: no rebase is required solely to request a new -combined checkout, and admitted equivalent browser/layout domains can still be -retained. It supersedes the earlier permission to merge after only a manual -unrelated-base assessment. Endurance and Git-sensitive domains remain fresh. Reuse is justified only -when the complete suite inputs, dependency closure, fixtures and harness are -unchanged and recorded evidence establishes that fact; unknown/global changes -require fresh proof. There is no generic passing-result cache. The earlier run -still names its own tree, not a later combined checkout. Required branch rules +combined checkout. It supersedes the earlier permission to merge after only a manual +unrelated-base assessment. Every selected category runs fresh on the new +combined checkout: there is no passing-result cache, and +[browser proof retention is retired](#retaining-complete-browser-domains). +An earlier run still names its own tree, not a later combined checkout. Required branch rules and actual merge-result parent/tree validation remain binding. ### Retaining complete browser domains -Under #1333, ready-PR metadata can retain every shard of a complete browser or -layout domain from up to three recent successful automatic runs of that same -contribution. Unit, types, packaging, native runtime and editorial checks remain -fresh: their Git-sensitive or broader process inputs do not have an admitted -independent domain. Main pushes and scheduled/manual runs execute fresh proof. -There are no chains through previously retained/skipped jobs. - -Vitest's installed `list --filesOnly --json=` discovers actual project/file -ownership without collecting suites. Browser and layout each fingerprint their -complete applicable static-import and validated indirect-input closure from -#2125, including CSS scan roots and assets. Unknown runtime/computed inputs, -unavailable discovery and invalid declarations require fresh execution. -Directory ownership includes added descendants; missing and symbolic inputs -remain conservative failures until fully supported. - -Identical indirect expressions can name exact lexical function scopes; stale, -ambiguous or shadowed bindings remain unresolved. A narrow runner observation -class admits literal Linux boot identity, self status and self PID-namespace -queries through unshadowed imported filesystem readers. It rejects descriptor -paths, dynamic PID/path expressions, arbitrary files and non-reader constructs. -Those values are runner observations, never Git blobs or provider/repository -payloads. Other process/filesystem inputs still need supported ownership. - -Generated fixture roots additionally require the root-redirect environment -variables `BRAIN_ROOT`, `BRAIN_WORKER_DATA_ROOT` and `BRAIN_WORKER_CONFIG_ROOT` -to be absent, including empty overrides. The versioned runner condition is -checked when making fresh receipts and revalidating current/source evidence. -A verified literal producer in an owned temporary root alone does not bind a -consumer reached through CLI arguments, cwd or configuration redirection. - -A bounded command-activation audit covers seven dormant server, Mermaid and scene -callbacks. Registration in a selected project is allowed only when the complete -selected call inventory proves the callback is never invoked. It checks the -complete selected spec inventory, inherited setup/global hooks and their static -imports; actual invocation, callback escapes, dynamic loaders and aliased -command invocation retain fresh execution. Admission additionally requires exact -audited runner, configuration, callback and imported-helper source identities. -An edit requires a new audit rather than general TypeScript partial evaluation. -Only a proven inactive arrow body defers its runtime inputs. Its module and -static imports still execute and retain ordinary input checks, including any -top-level initializer or side effect. Dormant declared targets and their static -imports remain fingerprinted source bytes. This bounded support does not close -unrelated generated assets or provenance inputs. -The audited configuration, selected specs and inherited setup/global hooks are -also ordinary runtime closure roots; inspecting their command calls cannot -substitute for hashing their sources and resolving their executed input reads. - -Generated consumer stylesheet imports bind the exact `ui-kit`/`ui-react` -`dist/styles.css` output and byte-copied theme/token exports to their source stylesheets, recursive CSS inputs and -tracked producer. The audited build cleans package output, uses the frozen -Tailwind dependency and completes successfully before browser execution and its -fresh receipt. Three audited command readers additionally bind the runner's -`packages/ui-kit` cwd. Producer, command or execution-path drift makes that -binding unavailable. Current `dist` bytes never substitute for source inputs. -Other generated artifacts, external assets and temporary readers remain unknown -until their own bindings are validated. - -Generated CSS/theme and inclusion self-tests use raw Git blobs from the -independently pinned audited revision for their positive producer controls. -They test actual current producer bytes separately: legitimate audit drift -requires fresh proof and does not redefine the positive fixture. The locked -offline compiler and installed-asset byte/mode controls remain runtime proof. - -Browser document, inactive-command and worker-boundary self-tests follow the -same ownership rule. Their positive config, callers, producers and binary font -fixtures come from independently pinned raw Git blobs, including frozen directory -membership (`const owner`, `tests/frozen-browser-source.ts:8-22`). Actual candidate -bytes are checked separately against that owner -(`test.each([...reviewedBrowserDocuments])`, `tests/bound-browser-documents.test.ts:142-155`); -changed enforcement cannot qualify by recomputing its manifest. These fixtures -exercise the existing audit and never refresh production pins or authorize -retained proof for the candidate. - -Only a reviewed re-audit moves the audited revision -([#2408](https://github.com/schlessera/brain-kit/issues/2408), maintainer ruling 2026-10-18): - -- **Trigger.** A legitimate change to any file in the audited producer table - (`const auditedProducer`, `scripts/generated-build-inputs.ts`) lands on main. - That merge leaves the binding unavailable, so proof runs fresh. A separate - follow-up PR restores it. Drift is not batched indefinitely. -- **Owner.** The audited revision (`const owner`, `tests/frozen-generated-source.ts`) - must be a delivered main commit. CI reads its blobs offline from full history, - and a squash merge discards the changing PR's own commits, so that PR cannot - name itself as the owner. -- **Audit.** The re-audit reviews each changed producer and the combined set's - guarantees: cleaned package output, the frozen Tailwind dependency, the build - finishing before browser execution, checked exits and the fresh receipt. It - records the owner, the changed paths and digests, and the rationale. - Recomputing a digest is not an audit. -- **Update.** One PR moves the owner, refreshes every matching production digest - and updates the positive-fixture provenance together. It records two mutation - receipts, then completes local and hosted proof: - - a producer-digest bypass fails its negative control; - - corrupt positive ownership fails its positive control. -- **Drift during review.** A producer that changes again before the re-audit - merges needs renewed review, or stays unqualified and keeps fresh proof. - Automatic pin refreshes and per-file ownership are not part of this - procedure. -- **Audited readers.** The same rule covers the audited command readers - (`const readers`, `scripts/locked-browser-assets.ts:6-9`; - `const auditedReaders`, `scripts/generated-build-inputs.ts:37-41`) - ([#2408](https://github.com/schlessera/brain-kit/issues/2408), maintainer - ruling 2026-11-04). A legitimate change to a reader makes its asset binding - unknown, so proof runs fresh; it never fails a test, and the changing PR does - not refresh the reader's pin. The reader's self-test holds the repository's - actual reader to whichever side of its pin its bytes are on: matching bytes - must yield the installed receipt and drifted bytes must yield no receipt - (`test("the repo reader`, `tests/locked-browser-assets.test.ts:26-33`). Its - positive control reads the reader from the frozen owner. The post-merge - re-audit moves that owner and refreshes the reader's pins in both maps - together. - -The verify-budget producer re-audit requested by -[#3233](https://github.com/schlessera/brain-kit/issues/3233) was delivered with -the shared reader-owner re-audit in -[#4057](https://github.com/schlessera/brain-kit/pull/4057), merged as -`2182752399a584370f0b6bf10cbcf3f2f960341f`. That audit moved the frozen owner -from `736a3445e82aee509e10f3c8d00b95fc77749202` to delivered main -`a9bcdbd6734c1733390570e2a68c10afde3b00a9` (tree -`5221359a249376353f6fd4939f4076596517c87f`). It reviewed all twelve producers; -the five changed sources were `scripts/ci-proof.ts`, `scripts/check-pr.ts`, -`scripts/ci-runner.ts`, `.github/workflows/ci.yml` and `package.json`. -The PR records their old/new digests, the combined clean-output, locked-tool, -execution-order, checked-exit and fresh-receipt guarantees, including coordinator -diagnostics and command cleanup, and the restored producer-bypass and corrupt-owner -mutation receipts. Production pins and independently owned fixture provenance -moved together. This evidence qualifies the recorded owner only; subsequent -producer or reader drift still requires fresh proof under the procedure above. - -The native diagram SVG/PNG/PDF fixture runs inside a separate finite operation boundary. +**Retired (maintainer, 2026-11-16, +[#4107](https://github.com/schlessera/brain-kit/issues/4107)).** Every selected +`browser` and `layout` job runs fresh. This supersedes #1333 (retention), #2126 +(its hosted demonstration) and the #2408 re-audit rulings of 2026-10-18 and +2026-11-04, and follows #4105, which retired the native diagram pin for the +same reason. The last re-audit under that procedure was +[#4057](https://github.com/schlessera/brain-kit/pull/4057), for +[#3233](https://github.com/schlessera/brain-kit/issues/3233); its record left +this document with the procedure and remains on that pull request. + +**What it was.** Under #1333, a ready PR could skip every shard of a complete +browser or layout domain when an earlier successful run of the same +contribution had run it on equivalent inputs. Equivalence was a fingerprint +over the domain's complete input closure. To call a closure complete, each +runtime edge the static walk could not follow was resolved by an *audited +binding*: a script that named the exact call site and pinned the SHA-256 of +every source file involved. The aggregate revalidated a ledger of retained +categories before accepting their skip. + +**Why it is retired.** + +- **No event reaches it.** Retention applied only to a ready PR that selected + `browser` or `layout`. Under the [hybrid ruling](#hybrid-post-merge-heavy-proof), + ready confirmation no longer selects either, and ready feedback never did. + Main and exhaustive runs were always fresh. +- **It rarely worked before that.** #2126 recorded no retained category in 57 + PR runs. Its one controlled hit saved runner seconds and was slower end to + end (1,253 s against 1,220 s). +- **Its pins failed product PRs.** A pin is a hash of first-party source, and + its self-test read the live file. A product change to a pinned file, such as + `packages/ui-react/src/ws-client/inbound.ts`, turned `unit` red until the + changing PR recomputed the hash. Twenty PRs edited that one file. + +**What was removed.** + +- The retained-proof lookup, its ledger, the aggregate's revalidation and the + fresh-execution receipt each shard printed for it. The metadata job has no + retention step and sets no `run_browser`, `run_layout` or `reuse` output. + `checks: read`, which only that lookup used, is gone from the token. +- The inclusion fingerprint and its immutable-tree snapshot. +- Every audited binding, with its frozen positive fixtures and self-tests: + command activation, document and replay producers, runtime readers, dispatch + registries, literal payloads, locked installed assets, generated CSS and the + dictation theme, screenshot baselines, and the Worker capability audit + manifest. + +**What stays.** + +- **Selection** ([browser proof input ownership](#browser-proof-input-ownership)). + The static walk and the declared inputs still build each category's closure. + An edge a binding used to resolve is now unresolved, so the category keeps + the planner's broad rule for it. Removing a binding can only widen + selection. The qualification replay found no narrowing: over the archived + 100-PR set (#1741–#2071) and over the 100 most recent merges at the time + (#3837–#4101), the rule after the removal selected every category the rule + before it selected, in all four browser categories. The ten build and CI + scripts that left the closures each make a plan global on their own, which + selects everything. +- **The aggregate.** A selected job that is missing, skipped, cancelled or + failed cannot pass, and nothing excuses a skip. `integrate.ts merge` refuses + a selected-proof receipt that names a retained category. The receipt keeps an + always-empty `retained` list so that a checkout predating the retirement and + the timing collector still parse it. +- **The zero-Worker boundary.** The selected browser projects install it before + product imports (`installWorkerBoundary`, `scripts/browser-worker-boundary.ts:2-21`). + It records and refuses every Worker construction, checks after test hooks and + again in the outer `aroundAll` after returned and file-fixture cleanup, then + restores the original descriptor. Catching the construction error in the + product cannot make the proof pass. Layout, endurance and the real PDF-worker + runtime categories run unrestricted. +- **Every runtime assertion in the browser suites**, including the + zero-request replay guards and the native producer's checks below. + +**The guard against a return.** `tests/first-party-source-pins.test.ts` refuses +a script or test that holds the SHA-256 of a first-party source file. It also +changes the bytes of two formerly pinned product files in a copy of the tree, +and requires planning and the root tests the planner selects for them to pass. +If retention is wanted again, its qualification is designed afresh, without +source pins that a product change can break. + +The native diagram SVG/PNG/PDF fixture runs behind a container boundary. The host launches each engine's native producer in a separate network-disabled, read-only-root Docker container, using the existing pinned Playwright image's actual immutable manifest reference. The only host mounts are the private six-workspace @@ -1076,12 +1035,10 @@ source view (read-only), a private external-package installation (read-only), th captured installed Bun bytes (read-only), and an initially empty owned output directory. Its HOME/temp and shared-memory filesystems are fresh container state; neither the original checkout nor host temporary directories or browser font -cache are mounted. Image and Bun identities join the browser input fingerprint. +cache are mounted. Execution bootstrap provisions the exact manifest digest and verifies its RepoDigest before either producer or browser consumption. Acquisition stays -outside the offline producer and proof lookup. -Metadata lookup projects the explicit manifest reference without requiring a Docker image -on the metadata runner; actual execution requires that exact manifest reference with no pull. +outside the offline producer; execution requires that exact manifest reference with no pull. The kernel mount boundary applies to imported initialization and shared library helpers as well as the fixed entry; their inactivity is not assumed. @@ -1130,175 +1087,14 @@ The container boundary above, the producer's own run-time checks and the browser's validation of the handoff session, checkout and artifact hashes are unchanged. The comparisons against an expected source, installation or runtime identity (`diagram-export-command.ts`, `prepare-diagram-export-source.mjs`, -`ci-proof.ts`) take that identity from the retired binding, so they no longer -run. If browser retention -returns to ready confirmation, its qualification is designed afresh then. -Local proof is not a hosted baseline, retention hit or permission to use a -failed workflow. - -Two audited fixture readers consume the literal installed `axe-core/axe.min.js` -asset. Its explicit resource identity records package name/version, relative -asset name, SHA-256 and mode in addition to the matching manifest/lockfile and -frozen-install conditions. Missing, symbolic, escaped or changed reader inputs -remain fresh; a changed reader stays fresh until its post-merge re-audit. This is exact-file validation, not a scan of `node_modules` or a -claim that arbitrary installed files belong to a domain. - -Two exact source-owned literal payloads—the rectangle SVG fixture and the -black/white pixel probe—have no resource loads or executable content. Their -complete owner and call identities validate the actual Playwright sink and -lexical binding. Interpolated HTML and other payloads remain unresolved; this -support cannot certify arbitrary generated documents. - -The complete activation-audited import inventory also seals two bounded reader -flows. The exact browser sequencer calls the cost reader without an override, -so its default is the module-relative cost JSON. The exact font command fixes -the repository and lock-hash cache roots, verifies every length/checksum before -use and replaces the pinned stylesheet URLs with those verified bytes. Reader, -caller and font JSON/CSS/head identities must match their audit; additional -imports, reexports or loaders into either reader require fresh execution. These -bindings name only the exact consumed repository bytes. They do not bless -arbitrary file parameters, changed font data or unverified cached content. - -Two finite private dispatch registries admit their exact indexed calls while -every handler and imported helper retains normal runtime input traversal. The -source audit verifies literal function entries, copied handler maps and private -non-escaping registries. The complete importer inventory rejects additional -map consumers; two exact consumers of a different chat helper are separately -audited. Changed source, escaping maps or new consumers require fresh execution. - -The dictation theme command has a separate temporary-output producer binding. -Its exact source owns a new temporary directory, invokes the locked Tailwind -CLI with constant input/output arguments, awaits successful completion, reads -only that output and removes the directory. The binding includes the compiler -asset identity, checked build producer and recursively resolved CSS entry, -theme, tokens and explicit source scan. Its precise `promisify` and -`createRequire` uses do not permit other aliases. The runner registration and -complete importer inventory seal the command's caller; source or input drift -requires a new audit. This support does not admit arbitrary subprocess outputs. - -One interpolated HTML fixture is separately bound to its exact producer and -complete selected command-call inventory. The destination-press spec supplies -only the source-owned paragraph document plus an explicit reporting/scroll -script; its other call removes the route. Exact configuration, command owner -and caller bytes seal the argument origins. Additional direct, renamed or -await-import command callers, escaping command aliases or direct owner imports -require fresh execution. This is a producer binding, not an assertion that -HTML containing a script is inert. - -The argument-free ghost replay has a distinct self-contained-document binding. -Its sole exact caller first renders the literal Performance story, then copies -that scene's DOM and the loaded CSS rules. The preview, inherited font setup, -checksum-verifying font producer, lock/CSS/head inputs and replay guard are -source-audited; all imported component and CSS dependencies retain their normal -closure traversal. Verified font bytes are inline data URLs. The replay page -aborts and records every HTTP/websocket attempt, also records request events -that could bypass routing, and asserts no attempts after document/font loading -and before/after tracing. Loopback resources receive no exemption. A resource -attempt fails the actual proof; source, caller, guard or producer drift requires -a new audit. The scene, visual assertions and trace remain unchanged. - -Diagram capture binds all six exact renderer, axis, positional, node-link, -callout and scene-bounds callers and their complete call-site inventories, -closed SVG primitive producers, -literal adopted fixture, generated consumer CSS and locked inline-font inputs. -Its additional replay page contains that source-owned document, aborts and records -HTTP/websocket requests, and checks the zero-request invariant after document and -font loading and after capture. Unknown DOM or resource origins remain unresolved; -source or producer drift requires fresh execution and a new audit. The -scene-bounds caller owns one literal origin-group fixture and two literal -annotation variants. Its client/static/flattened renderers share the closed -primitive producer; the fixture, flattening dependency and changed geometry, -annotation and painter sources are pinned explicitly. This audit does not -qualify native retention or replace complete fresh runtime proof. - -The selected browser capability additionally requires a complete audited -input-domain identity and an enforced zero-Worker boundary. The native, -forwarding diagnostic established no intended Worker execution in that -selection; its observation ended at `afterAll`, so it does not claim returned -cleanup coverage. Enforcement installs before product imports, records and -refuses every construction attempt, checks after test hooks and checks again -in the earliest outer `aroundAll` finally after returned/file-fixture cleanup. -Catching a construction error in the product cannot make its proof pass. The -original descriptor is restored completely after checking. Real PDF-worker -runtime categories and the layout/endurance projects retain fresh unrestricted -execution; no product constructor or configuration default changes. - -Admission validates exact known enforcement/configuration sources independently -of the audit manifest, then joins every selected source/data path, blob/mode, -directory membership, resource identity and inventory entry to that bounded -audit. Any relevant source, caller, realm, hook, guard or data edit executes -fresh until re-audited. A constructor hidden by a new alias cannot bypass this -mandatory browser capability check merely by disappearing from syntax -discovery. Unknown external resources still prevent admission. The manifest's -own bytes are ordinary shared fingerprint inputs; it is never self-hashed. -Version 2 separates current source-audit admission from historical diagnostic -observations. Historical case counts and their cleanup gap remain attributed to -the old selection; adding projects does not fabricate a whole-domain observation. -Old or missing admission metadata stays fresh. Its metadata cannot replace -complete successful guarded fresh jobs or the -independent retained-proof validator. This bounds the existing PDF constructor -to no consumed Worker resource; it does not authorize an arbitrary worker URL. - -Vitest screenshot references are inputs too. The pinned installed resolver's -verified defaults locate them under each selected spec's own -`__screenshots__/` directory. Eligible immutable tracked paths, -bytes and modes join the closure and capability identity, including added, -deleted and renamed baselines. A tracked file/symlink at a baseline directory -cannot hide an external reference. Custom screenshot directories/resolvers, -matcher aliases and unresolved option objects stay fresh; only closed literal -comparison settings are supported. The framework asset identity joins the -locked installed resources. No current output or untracked image enters this -snapshot, and baseline changes cannot inherit old passing comparisons. - -The inclusion fingerprint binds relevant immutable Git paths, blob identities -and modes, selected discovery ownership/order, the domain's measured partitions (`PROOF_SHARDS`) and -runner identity. It also includes every proof/tooling script and workflow, -root/package manifests and lockfiles, compiler configuration and expanded build -source inventories. These conservative shared harness inputs can invalidate -retention even when only one domain executes them. Unrelated prose is not an -input merely because it is tracked; imported or declared prose remains included. - -Source/current closure discovery uses separate raw-Git-blob snapshots. Workspace -package links resolve inside their own snapshot, while external dependency -resolution uses the frozen install only after source/current algorithm, -configuration, manifests and lockfiles match. Current generated/dist artifacts, -working-tree bytes and Git archive substitutions cannot stand in for immutable -source content. A helper or dependency identity mismatch executes fresh. - -The implemented fingerprint is only a necessary condition for retention. A -bounded browser admission still needs the complete guarded fresh baseline and -real retained-proof validation; unsupported layout/runtime inputs continue -fresh execution. Neither a synthetic closed fixture nor a graph -structure hash establishes a real hosted retention hit. #2126 remains open until -its controlled same-PR hosted demonstration and independent aggregate evidence -are complete. - -Each source shard must have an actual successful fresh execution step, a -matching GitHub Actions check, one post-success receipt, and a checkout log -for the same PR. Run/attempt/job/check IDs and immutable commit/tree/parents -are verified against the [read-only GitHub job/check APIs](https://docs.github.com/en/rest/actions/workflow-jobs). -Both source and current Git -trees are recomputed; artifact or PR metadata claims alone cannot authorize -retention. The source workflow must be identical. The current-head aggregate -independently repeats receipt validation before accepting a selected domain's -intentional skip, retaining the original evidence's identity in the ledger. -Missing, failed, cancelled, held, malformed or mismatched evidence cannot pass. - -CI adds only `actions: read` and `checks: read` for those APIs; ordinary fork execution retains -its read-only token, no secrets and nonpersisted checkout credentials. Lookup -is limited to three runs, 32 API requests with a 45-second API budget, bounded response sizes and -finite logs; unavailable evidence falls back to fresh execution. The aggregate -fails closed if previously admitted retention is no longer verifiable. -The escaped ledger output stays below 90 KB, leaving room for the aggregate's -other outputs under the native per-environment-string limit; larger receipts -execute fresh. -Record actual retained runner time and lookup/aggregate costs on a controlled -base advancement. This preserves runner consumption without claiming that -unchanged browser proof removes a remaining long native critical path. +`ci-proof.ts`) took that identity from the retired binding, so they no longer +run. Local proof is not a hosted baseline or permission to use a failed +workflow. + + Discovery has a fixed 30-second wall-clock maximum for the native child to exit -and both output pipes to drain (`browserInventory`, `scripts/proof-inputs.ts:81-139`), -in local preflight and hosted metadata, -fingerprinting, reuse lookup and aggregate validation. The maintainer selected +and both output pipes to drain (`browserInventory`, `scripts/proof-inputs.ts:55-113`), +in local preflight and hosted metadata. The maintainer selected option A under [#2380](https://github.com/schlessera/brain-kit/issues/2380) on 2026-10-22: #2326's cold discovery sample took 14,811 ms in the pinned offline image with two CPUs, so 30 seconds allows approximately twice that observed @@ -1307,9 +1103,8 @@ margin does not guarantee completion under arbitrary CPU starvation; a stuck child can take up to 15 seconds longer to fail than under the previous maximum. Process controls inject a short deadline and assert the default separately; the integration test allows additional time for ownership scanning and cleanup. -Discovery failure still rejects unsuccessful inventories and retains the -caller's existing fresh-execution or fail-closed behavior. -A missing immutable Git object has an eight-second bounded fetch. +Discovery failure still rejects unsuccessful inventories: selection then keeps +the broad rule for every browser category, and the scenario inventory fails closed. Runner image context comes from the image's [recorded environment](https://github.com/actions/runner-images/blob/main/images/ubuntu/scripts/build/configure-environment.sh). @@ -1690,7 +1485,8 @@ a run killed from outside still leaves an honest receipt. `integrate.ts merge` maps each skipped, timed-out or preempted check to its hosted categories and refuses the candidate when none of them ran successfully in the exact-head selected proof, naming every such check and the categories it -needs. A category retained by validated proof reuse counts as run. The metadata +needs. Only a category that ran counts: nothing is retained from an earlier +run. The metadata gate always runs, so lint, leakage and changeset checks are always covered; an unknown check maps to no category and can never be covered. @@ -1819,7 +1615,7 @@ branch, so the request always runs main's admission code. - **Red main.** The refusal while main is red is the red-main gate from [#2942](https://github.com/schlessera/brain-kit/issues/2942). The admission job runs it on the requested head after admission - (`redMain.name`, `scripts/heavy-feedback-workflow.ts:85`), so feedback is + (`redMain.name`, `scripts/heavy-feedback-workflow.ts:84`), so feedback is refused only when that head contains the bad commit and the PR is not a declared fix ([#3321](https://github.com/schlessera/brain-kit/issues/3321)). @@ -1859,7 +1655,7 @@ stay pre-merge; heavy categories move to the squash's own main run. `unit` (complete affected unit/integration discovery, unchanged). It no longer runs `runtime`, `runtime_host`, `browser`, `layout`, `captures` or `endurance`. The exclusion lives in one place: - `proofSelections` (`scripts/ci-plan.ts:424-433`) applies + `proofSelections` (`scripts/ci-plan.ts:434-446`) applies `POST_MERGE_CATEGORIES` (`scripts/red-main.ts:20-25`). Candidate admission, the aggregate and the merge path validate that same selection, so none of them can require a post-merge category. @@ -2078,6 +1874,79 @@ Git and its configuration. A merge that another Git or another rename setting would have written differently reads as altered and costs one more review; it never passes unread. +## Changed tests repeat under load before merge + +The maintainer ruled on 2026-11-16 +([#4109](https://github.com/schlessera/brain-kit/issues/4109)) that a Bun test +file a pull request adds or modifies must pass repeated runs under CPU load +before it merges. + +**Why.** Main went red 25 times between 2026-11-02 and 2026-11-16. About 18 of +those incidents were cleared by changing only a test: a wait, a pinned clock, +a readiness signal, a deadline a loaded shard could meet. About six were +product defects. The first-main failure rate was about the same for PRs under +100 lines (19%) as for PRs over 2,000 lines (22%). These are tests that pass +once and fail later on someone else's merge, and nothing ran a new or changed +test more than once before it merged. + +- **What runs.** `bun scripts/test-determinism.ts --base ` selects the + Bun test files under `packages/` and `tests/` that the change adds or + modifies against its merge base (`determinismTests`, + `scripts/ci-plan.ts:323-328`). It runs them in one invocation of the offline + wrapper with Bun's `--rerun-each= --bail=1` (`repetitionArgv`, + `scripts/test-determinism.ts:84-87`), so the offline preload applies and + preparation builds once. One busy loop per CPU runs for the duration. Each + is killed by PID on every exit path, and exits by itself if its parent dies + (`startBurners`, `scripts/test-determinism.ts:136-151`). The first failing + repetition fails the command, which names the file, the repetition and the + case. A passing run must also show every repetition in Bun's test report. +- **Bounded.** Five repetitions by default, within a budget of 600 seconds of + the reviewed weights in `scripts/test-shard-costs.json`. When five do not + fit, every file gets the same reduced count, down to a floor of two + (`planRepetitions`, `scripts/test-determinism.ts:62-81`). A selection too + heavy for the floor still runs every file twice and is reported over budget. + No selected file is skipped; the report lists each one with the repetitions + it got. Over 150 merges before the gate, 142 selections fit five + repetitions. A selection too heavy for the job's step limit is + [#4117](https://github.com/schlessera/brain-kit/issues/4117). +- **Where it is required.** The hosted `determinism` job is selected whenever + the plan lists such a file, at every pull-request cadence: draft, ready + `synchronize` feedback and ready confirmation. Draft heavy feedback runs it + too (`proofSelections`, `scripts/ci-plan.ts:441-453`). This amends "drafts + run cheap gates only" for this one job, so the + [fast lane](#fast-lane-outside-the-core-packages)'s newest run includes it. + `draft gates`, `proof` and the merge path require it when selected and + require its intentional skip otherwise. It is a fast category under the + [hybrid split](#hybrid-post-merge-heavy-proof): it is not in + `POST_MERGE_CATEGORIES`. The job has the `unit` job's runtime prerequisites, + because a changed file may drive real Chrome. +- **Not on main.** A main push never selects it. The squash's files were + repeated before they merged, and the main run already runs each of them once + in `unit`. +- **Not local.** `check:pr` never runs it, because it occupies every CPU of a + shared host. `check:pr --plan` names the command when the change selects it. + A deliberate local run takes a + [host admission](../process/testing.md#host-admission-for-heavy-local-commands) slot. + +**What does not change.** No test deadline changes. No failure is retried +into a pass: a failing repetition is a failed job, and the remedy is fixing +the test or what it exposes. Unchanged tests are not repeated. + +**First hosted run.** The job's first run, on the PR that added it, repeated +seven changed files five times and then failed in the gate's own test: under +GitHub Actions Bun prints each run's header as a `::group::` annotation, which +the failure parser did not read, so the failure was reported without its file +and repetition. The parser reads both forms now. That run took 552 seconds +for about 174 weighted seconds, a ratio of about 3.2 under four burners on +four CPUs, so a selection at the 600-second budget needs about 32 minutes of +the 40-minute step limit. + +**Known limits.** Repetitions of one file share a process. Bun 1.4.2 evaluates +the module again for each run, but `globalThis` and process state persist, so a +file that leaks state into its next run fails too. Vitest browser, layout, +endurance and story specs run in the pinned container and are not covered +([#4116](https://github.com/schlessera/brain-kit/issues/4116)). + ## Historical measurement and upstream guidance The following guidance records the paid-provider investigation which motivated @@ -2178,7 +2047,7 @@ this narrowly scoped collector while retaining the existing CI/provider gates. The [collection guide](../process/ci-timings.md) defines interval/attempt accounting, missing evidence, cancellation costs, PR attribution and the historical exhaustive-run proxy. Estimates remain distinct from same-source -paired measurements. Timing metadata never authorizes proof retention or merge. +paired measurements. Timing metadata never authorizes a skipped category or a merge. The expanded [issue #2476](https://github.com/schlessera/brain-kit/issues/2476) objective is reliable parallel agent throughput. Collection diff --git a/docs/decisions/github-actions-ci.md b/docs/decisions/github-actions-ci.md index ddcd9c499b..1f056819b0 100644 --- a/docs/decisions/github-actions-ci.md +++ b/docs/decisions/github-actions-ci.md @@ -40,9 +40,10 @@ remain required; missing runtimes and unrelated failures cannot be called green. > cleared locally as in CI. Bun and Node still each load every package in one > process, now followed by one process per package. This decision still binds. -Forks use `pull_request` with `contents: read` and CI's `actions: read` / `checks: read` for -bounded immutable proof lookup under #1333, no secrets, no job-level -permission escalation and no persisted token. Titles and labels reach the +Forks use `pull_request` with `contents: read` and CI's `actions: read` for its +bounded read-only run and job lookups, no secrets, no job-level +permission escalation and no persisted token. `checks: read` went with proof +retention (#4107), its only reader. Titles and labels reach the contract script as environment data. A first-time contributor's approval-held run has not passed. Project sync keeps its separate trusted token and event workflow; ordinary CI does not acquire that token. diff --git a/docs/decisions/test-health.md b/docs/decisions/test-health.md index 0b6d19bb7d..7a71d4e58a 100644 --- a/docs/decisions/test-health.md +++ b/docs/decisions/test-health.md @@ -39,7 +39,7 @@ follows is in [ci-utility.md](ci-utility.md) and enumerated fields. - **A batch stays inside one group and lands as one pull request.** Hosted proof for a test edit is priced by the workspaces it touches, not by the - number of files (`const packageCode`, `scripts/ci-plan.ts:356-357`): any path + number of files (`const packageCode`, `scripts/ci-plan.ts:366-367`): any path under a package's `tests/` selects that package and its reverse dependants. One changed test in a package costs the same confirmation as thirty, so small pull requests are the most expensive way to land this work. A large diff --git a/docs/process/ci-timings.md b/docs/process/ci-timings.md index e400222833..d59ff65a28 100644 --- a/docs/process/ci-timings.md +++ b/docs/process/ci-timings.md @@ -27,8 +27,9 @@ The time interval selects runs by their original creation time. Every available attempt of a selected run is collected separately. `--resources` additionally reads executed proof-job logs for their structured resource markers and the aggregate's selection/retention marker. It does not persist full logs. Without -that option, job and step timestamps are still available, but retained browser -proof cannot always be distinguished from other skipped jobs. An unavailable +that option, job and step timestamps are still available. In runs archived +before browser proof retention was retired (#4107), a retained browser job +cannot always be distinguished from other skipped jobs. An unavailable marker remains unknown, rather than a zero-duration command. Filtered searches recursively split time ranges at GitHub's 1,000-result cap. diff --git a/docs/process/proof-domains.md b/docs/process/proof-domains.md index 3bbf2aacef..505527738b 100644 --- a/docs/process/proof-domains.md +++ b/docs/process/proof-domains.md @@ -2,7 +2,7 @@ Default execution ownership is discovered, not copied into a static test allowlist. `bun run test:inventory` writes `tmp/proof-inventory.json`; CI publishes -it with the metadata artifact. Each row has a runner/project/file identity, +it as the metadata job's `proof-inventory` artifact. Each row has a runner/project/file identity, its domain, source test declarations and assertion line locations. An assertion inside a parameterized test runs for every collected case: the inventory does not pretend source declarations are runtime test counts. Actual suite reports @@ -127,12 +127,22 @@ and complete `git diff --no-renames SHA^ SHA` paths: bun scripts/replay-browser-selection.ts snapshot.json report.json ``` +A change to the selection rule attaches a comparison. Write the report on the +tree before the change, then pass it as the baseline on the tree after it: + +```sh +bun scripts/replay-browser-selection.ts snapshot.json after.json before.json +``` + +`omittedSinceBaseline` lists every PR and category the earlier rule selected +and the later one omits. It must be empty unless the change is ruled to narrow +selection. + The tool verifies every diff and emits per-PR before/after selection, the list of omitted browser plans, complete category closures and unresolved-edge diagnostics. It compares current selection rules over historical changes, not historical source execution or elapsed performance. Closure graph hashes describe paths and diagnostics, -not source bytes or passing-proof fingerprints. Keep the actual source identity -with its report; proof retention requires its separate immutable input validation. +not source bytes. Keep the actual source identity with its report. Schedule/manual proof is exhaustive; push proof remains complete affected proof. ## Recording assertion mapping diff --git a/docs/process/test-authoring.md b/docs/process/test-authoring.md index d114bbd174..20715031e9 100644 --- a/docs/process/test-authoring.md +++ b/docs/process/test-authoring.md @@ -151,6 +151,15 @@ test("the date field shows the parsed date and refuses an unparseable one", asyn discovers. Prevents `skipped`, `conditional-skip`, `retry`, `only` and `undiscovered`. +A Bun test file that a pull request adds or modifies is checked against these +rules before it merges: the hosted `determinism` job runs it five times in a +row under CPU load and fails on the first failing repetition +([the gate](testing.md#changed-tests-repeat-under-load)). A test that waits for +a while, reads the wall clock or keeps state from its previous run fails +there, not on someone else's merge. Reproduce a failure with +`bun scripts/test-determinism.ts --base origin/main`, and fix the test under +the rule it broke. A longer deadline or a retry is not a fix. + ## Cost - **C1. Know the budget of the tier.** Most unit files finish in under a diff --git a/docs/process/testing.md b/docs/process/testing.md index f2e85c9c21..125d9a8636 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -233,7 +233,7 @@ remainingButtonCases(() => "fine"); ``` Remove that temporary leaf after the diagnostic, including on failure. It is -not part of ordinary layout discovery or the retained proof inventory. +not part of ordinary layout discovery or the proof inventory. 1. Save `packages/ui-kit/vitest.config.ts` outside the tree. Temporarily replace only the `ui-react-layout` project's discovery array with @@ -297,6 +297,41 @@ Await it and assert on the result, or use `expectRejection` (`packages/ui-server/tests/helpers/expect-rejection.ts`) ([why](../decisions/sqlite-write-worker.md#testing-note)). +## Changed tests repeat under load + +A Bun test file that a pull request adds or modifies runs several times under +CPU load before it merges +([the 2026-11-16 ruling](../decisions/ci-utility.md#changed-tests-repeat-under-load-before-merge)). +Most red-main incidents in the two weeks before it were cleared by changing +only a test that had passed once. + +```sh +bun scripts/test-determinism.ts --base origin/main # what the hosted job runs +bun scripts/test-determinism.ts --base origin/main --json # the report on stdout +``` + +- **Selection.** Files that `bun test` discovers under `packages/` and + `tests/`, added or modified against the merge base. Deleted files, the + experiment tier and Vitest specs are not selected. +- **The run.** One invocation of `bun run test` with `--rerun-each` and + `--bail=1`, so the offline preload is active and a non-loopback connection + fails as it does in any test. One busy loop per CPU runs until the command + exits; each is stopped by PID and exits by itself if the command is killed. +- **The bound.** Five repetitions, reduced uniformly to no fewer than two when + the reviewed weights in `scripts/test-shard-costs.json` exceed 600 seconds. + The report lists every selected file with the repetitions it got, and says + when the selection is over budget at the floor. +- **A failure** names the file, the repetition and the case. Repetitions of a + file share one process, so state left on `globalThis`, in the environment or + on disk reaches the next run. Fix the test; do not raise its deadline. +- **Where it runs.** The hosted `determinism` job, at every pull-request + cadence including draft, and in draft heavy feedback. `draft gates` and + `proof` require it when the change selects it. `check:pr` never runs it: it + occupies every CPU, and the host is shared. `check:pr --plan` prints the + command when it applies. A local run waits for + [host admission](#host-admission-for-heavy-local-commands); + `--burners ` lowers the load for a diagnosis. + ## Tests that cannot fail A green test is evidence only if it could have been red. Each of these shapes @@ -647,7 +682,10 @@ in the [CI and merge reference](../../.agents/skills/work-issue/references/ci-an release preparation runs instead of PR proof. Scheduled exhaustive CI is additional coverage, not a replacement for selected pre-merge proof. -- Drafts run cheap gates. Ready `opened`, `reopened` and `ready_for_review` +- Drafts run cheap gates, plus the `determinism` job when the change adds or + modifies a Bun test file + ([changed tests repeat under load](#changed-tests-repeat-under-load)). + Ready `opened`, `reopened` and `ready_for_review` events request full affected confirmation. Ready `synchronize` runs affected fast invariants and types only; `proof` remains nonpassing until the author converts to draft and marks ready after the final push. A push invalidates @@ -666,17 +704,14 @@ in the [CI and merge reference](../../.agents/skills/work-issue/references/ci-an and live PR readiness/head plus the independent live base ref. Any base advance requires a new confirmation request (a rebase is not inherently required). Relevant input/dependency/harness changes require fresh checks; never call an old - receipt a new combined-tree pass. Under #1333, complete browser/layout - domains may retain validated equivalent successful automatic receipts. - Inclusion fingerprints recompute each immutable tree's complete supported - import/declaration closure and tracked path/blob/mode, build/discovery/partition - and runner identities. Unknown generated/runtime inputs execute fresh; a - graph-structure hash or unchanged imported files alone cannot authorize reuse. + receipt a new combined-tree pass. Every selected category runs fresh on that + checkout: browser proof retention and the source pins that qualified it are + [retired](../decisions/ci-utility.md#retaining-complete-browser-domains) + (#4107), so no job is skipped on the strength of an earlier run and no test + fails because a product file's hash moved. Before naming a source run as passing proof, verify its workflow name/path, event, head, conclusion and complete job inventory. Repository synchronization - jobs do not provide CI proof. Read the current retention ledger and aggregate; - original run/job/checkout - identity remains distinct. Other categories stay fresh. Verify actual squash + jobs do not provide CI proof. Read the aggregate. Verify actual squash parent/tree and automatic main-push proof. Respect branch rules. A writer can bypass checks when protection is absent; agents still require passing candidate proof and must re-read head/base before matching-head merge. This change does not alter repository protection. @@ -724,7 +759,9 @@ action/runtime versions, pinned offline browser image and diagnostic artifacts. Independent selected categories run after metadata; the final proof aggregate rejects failures, cancellations, missing outputs and unexpected skips. Tests-only changes may intentionally skip packaging while complete -affected tests run. Drafts run cheap gates only. Forks use ordinary +affected tests run. Drafts run cheap gates only, with one exception: the +`determinism` job repeats a change's added or modified Bun test files under +CPU load at every pull-request cadence. Forks use ordinary `pull_request`, a read-only token (`contents: read`, plus `actions: read` / `checks: read` for bounded proof lookup), no secrets and nonpersisted checkout credentials. A fork run awaiting maintainer approval has not passed. @@ -753,7 +790,7 @@ Workflows reference each action by commit, with its release tag as a comment: tag and commit. Environment setup via `scripts/ci-runtime-setup.sh` has its own 12-minute -step limit in `unit`, `runtime` and `runtime_host`. Proof retains a separate +step limit in `unit`, `runtime`, `runtime_host` and `determinism`. Proof retains a separate 30-minute unit allowance or 15-minute runtime allowance. The job caps are 45 and 30 minutes respectively, including three minutes for the remaining steps. The [timeout basis](../decisions/ci-utility.md#separate-environment-setup-and-proof-budgets) @@ -860,7 +897,7 @@ name any still-missing automatic failure screenshots. Passing cases, local files and upload patterns alone do not establish hosted retention. Reading CI for a PR — the actual current head, the live base, checkout SHAs, -run/job/attempt IDs, retained #1333 receipts, refused-start jobs, and the +run/job/attempt IDs, refused-start jobs, and the merge and post-merge checks — is the `work-issue` skill's [CI and merge reference](../../.agents/skills/work-issue/references/ci-and-merge.md). @@ -874,18 +911,9 @@ Tailwind stylesheet is backed by the dependency manifests and lockfile, with `source(none)` disabling implicit scanning, and the kit token export names its source. An edited or duplicate statement invalidates its declaration. Missing inputs, symlinks, escaped paths, globs, remote URLs, dynamic sources and unknown -build directives remain unresolved and require fresh proof. This discovery -support does not itself establish a complete retainable browser domain. - - -Retention's bounded browser-command audit must preserve imported top-level -execution. Its tests import a real config in a Bun child and observe a transitive -module input even while the registered callback remains dormant. Activating a -command through a selected spec, inherited setup or configuration must force -fresh execution; registration alone is not invocation. Registered dormant -callbacks require the same complete call/escape audit, and a mutation of that -activation guard must fail the named assertion. -The exact audited configuration/source guard makes unsupported edits fresh. +build directives remain unresolved, and the category then keeps the planner's +broad selection rule. Discovery only selects categories: it never lets a +selected job be skipped. ## Cross-PR timing collection diff --git a/scripts/bound-browser-documents.ts b/scripts/bound-browser-documents.ts deleted file mode 100644 index 6d5f1d4068..0000000000 --- a/scripts/bound-browser-documents.ts +++ /dev/null @@ -1,250 +0,0 @@ -/** Exact fixture producers and every selected BrowserCommands invocation. */ -import {createHash} from "node:crypto"; -import {existsSync,readFileSync,realpathSync} from "node:fs"; -import {resolve} from "node:path"; -import ts from "typescript"; -import type {BrowserImporters} from "./bound-browser-runtime-inputs"; -const config="packages/ui-kit/vitest.config.ts"; -interface DocumentDeclaration { command:string;owner:string;ownerHash:string;caller:string;callerHash:string;calls:number;additionalCallers?:Record;sink:string;producers:Record; } -const declarations:DocumentDeclaration[]=[{ - command:"htmlPreviewFixture",owner:"packages/ui-kit/tests/visual/form-browser.ts",ownerHash:"3ccf67a71fa64af195bbf8cf6d173064dc9d2d4fc6abc699fa0a638c352ca62e", - caller:"packages/ui-react/tests/browser/destination-press.pointer.tsx",callerHash:"85e9a20f9a15dd38a6479e3dd668e45f6f8324c2e6a97a252172392c1bfb857e",calls:2, - sink:'route.fulfill(requested === path\n ? { status: 200, contentType: "text/html", body: html }\n : { status: 404, contentType: "text/plain", body: "Unknown fixture file" })', - producers:{} as Record -},{ - // #1599 re-audit: design-font-checks.ts only adds a synchronous layout read of its probe host; no sink, call, argument or producer changes. - command:"ghostTrace",owner:"packages/ui-kit/tests/visual/ghost-browser.ts",ownerHash:"004c45bd7261997efccc74623ee2f67db4fc832b99039bc2f49cea81e75fb799", - caller:"packages/ui-kit/tests/visual/ghost-sweep.visual.tsx",callerHash:"77ecc3626f82ae9687f17fdc9846353ed9bd3057a802ac3e8acd89b72d17039e",calls:1, - sink:'page.setContent(`${fixture.html}`)', - producers:{ - "packages/ui-kit/stories/states/GhostSweep.stories.tsx":"25da76fdba02282bb4ff656da68f27dd1b134d1ed938ceff353ae4c88e0f30b7", - "packages/ui-kit/.storybook/preview.ts":"bff3b384ba6fd35c4ac6381e2fc125cbeefeda32a58ec3eeef288a19238de0a1", - "packages/ui-kit/.storybook/preview.css":"d98834fb114fc7aa26cf2b79bcbaf363943fdd99b1535748f14f1dd861a0d4ec", - "packages/ui-kit/tests/visual/zero-request-replay.ts":"694080b66abfd6235d1873e63c908f4284b8804e5f3ff2ac98ca89169c59290e", - "packages/ui-kit/tests/visual/design-font-setup.ts":"ef812cb97c62da898dc0050cdfc09762163dfdb2cac1e3b813d586fd0fa95fb2", - "packages/ui-kit/tests/visual/design-font-checks.ts":"502748af10e70e34583dc82f0f9de21d59d1b86829aa80d29ce04e071da464cd", - "packages/ui-kit/tests/visual/rank-footer-browser.ts":"7c4a2b0e4b5d3f40f2cc84af86f852c36068791fcb1dc6f8989f2863d51733a0", - "scripts/captures/fonts.ts":"a0d96b46f110e929e34cdc592927c4a23dedde9f672e059bfae7bba10e8349cd", - "scripts/captures/font-lock.json":"3ec58a552059527131bda0277703425243a63aa311d58b67201a7b2c9fe136ad", - "scripts/captures/fonts.css":"1a6035cc96ef6b928378a04b1f81c13b52362f18fa00e087f4a5f15155482a4d", - "packages/ui-kit/.storybook/preview-head.html":"66da7597557f1418096239edcd74f7a8decfc70dfc8f1d820de0cf365df41ed7" - } -},{ - // Reviewed against #2295, #2346 and #2228: the origin-group caller renders - // only its literal fixture and literal annotations through closed primitives. - // All six callers retain the exact HTML/CSS sink and zero-request replay. - // #2386 re-audit: narrow geometry/capture case split preserves all eight - // callout capture sites, arguments and unchanged HTML/CSS/font producers. - // #2241 re-audit: renderer/axis edits only strengthen viewer selection and - // font assertions; capture arguments, call counts and producer closure stay fixed. - // #1599 re-audit: design-font-checks.ts only adds a synchronous layout read of its probe host; no sink, call, argument or producer changes. - "command": "diagramCapture", - "owner": "packages/ui-react/tests/browser/diagram-proof-command.ts", - "ownerHash": "d7280cf23ba24bd636f7737d8552801e37f8c03c1e773aee660c9e07ded524a9", - "caller": "packages/ui-react/tests/browser/diagrams-renderer.layout.tsx", - "callerHash": "9d5e6b574bc22fb19f47c6d7d813f13bd444920539bf341732700e9d3413de4a", - "calls": 2, - "additionalCallers": { - "packages/ui-react/tests/browser/diagrams-scene-bounds.layout.tsx": { - "hash": "923869d4212954ce0df2104e4cc47e40eb4e0ab95d32e5bfa19039196e262f65", - "calls": 1 - }, - "packages/ui-react/tests/browser/diagrams-callouts.layout.tsx": { - "hash": "83e34b70e1de6368073d1aa3414f5f42ffd071da6246ce47109397df72206091", - "calls": 8 - }, - "packages/ui-react/tests/browser/diagrams-axis.layout.tsx": { - "hash": "bd7c728af1ae5c250ddbef4e3423372590aabc65430661fe6afed97e3eb6e933", - "calls": 3 - }, - "packages/ui-react/tests/browser/diagrams-positional.layout.tsx": { - "hash": "2d3e72c1b72aff553518bff7f03f99123bd772159f9844f3b68eef025556fbde", - "calls": 1 - }, - "packages/ui-react/tests/browser/diagrams-node-link.layout.tsx": { - "hash": "ee5282269f48ed482fc9f3b3316c88b538c7b29772e78f5f87ff27915fa4090f", - "calls": 2 - } - }, - "sink": "page.setContent(`${drawing.html}`)", - "producers": { - "packages/module-diagrams/tests/fixtures/origin-group.ts": "90d66bdeb55421e7896152c2f5069cefacbbb4b6271c70859a17644dad344dd4", - "packages/module-diagrams/src/flatten.ts": "0afc5a8fa2caa2adedf83fb3d3d323698a06d7a61243350a699e39457dfb70ab", - "packages/ui-kit/tests/visual/zero-request-replay.ts": "694080b66abfd6235d1873e63c908f4284b8804e5f3ff2ac98ca89169c59290e", - "packages/ui-kit/tests/visual/form-browser.ts": "3ccf67a71fa64af195bbf8cf6d173064dc9d2d4fc6abc699fa0a638c352ca62e", - "packages/ui-kit/tests/visual/design-font-setup.ts": "ef812cb97c62da898dc0050cdfc09762163dfdb2cac1e3b813d586fd0fa95fb2", - "packages/ui-kit/tests/visual/design-font-checks.ts": "502748af10e70e34583dc82f0f9de21d59d1b86829aa80d29ce04e071da464cd", - "packages/ui-kit/tests/visual/rank-footer-browser.ts": "7c4a2b0e4b5d3f40f2cc84af86f852c36068791fcb1dc6f8989f2863d51733a0", - "scripts/captures/fonts.ts": "a0d96b46f110e929e34cdc592927c4a23dedde9f672e059bfae7bba10e8349cd", - "scripts/captures/font-lock.json": "3ec58a552059527131bda0277703425243a63aa311d58b67201a7b2c9fe136ad", - "scripts/captures/fonts.css": "1a6035cc96ef6b928378a04b1f81c13b52362f18fa00e087f4a5f15155482a4d", - "packages/ui-kit/.storybook/preview-head.html": "66da7597557f1418096239edcd74f7a8decfc70dfc8f1d820de0cf365df41ed7", - "packages/module-diagrams/tests/fixtures/callouts.ts": "efbef5b4db026fe2e1d2fe93261a883aab95c6b533ae1d2c68d92cb1b649fd7e", - "packages/module-diagrams/tests/fixtures/renderer-fixture.ts": "dc0db9aba9cd425c0cb12bd0241c6d9b4d8edd4a1ed6270e391f9d0cae7018be", - "packages/module-diagrams/tests/fixtures/adopted-homecoming-relay.diagram.yaml": "bc5d906627a8392da7921f8d74ff72eb7de4fb9cf03879fc6c83b1aaec0ee3a4", - "packages/module-diagrams/src/callout-path.ts": "94354204bac1f9d2e8fffef49123fc787c47f07bdcce5b7593161a63468cb3fa", - "packages/module-diagrams/src/callouts.ts": "6da78e9cc418771268298034896fd39976ab823d843c5874ef8ca15fe5f96e2c", - "packages/module-diagrams/src/legend.ts": "d5a9e9803a8b81100737cac0cc8b3fc8fdcb97c11a7d0ba10ced598a71744568", - "packages/module-diagrams/src/axis-check.ts": "ba2133b3c42bcd72abcdb7200ba4fd4a05656aee0028b7894db7a22bcafbdbe9", - "packages/module-diagrams/src/axis-layout.ts": "75e78e607a91d3b5684eaf3b071f56e41c317a1b336a9c06b80608121a41c34d", - "packages/module-diagrams/src/axis-spec.ts": "55bce9fad9e94af099a55fb1f7d282247c4b5f0dbdd9b33679e2903acfc28b93", - "packages/module-diagrams/src/shape-svg.ts": "b629406bfec41e3ed9973a395a6271d69f1ce45d823591ab15b5581a0116a29b", - "packages/module-diagrams/src/shape.ts": "9d3cd34d9153410ecc7b20e5edbf01c9a68e934dbe9ce662b4cf1af988d19f40", - "packages/module-diagrams/tests/fixtures/axis-examples.ts": "3925e82b8bc2ced444d8d6019fa13a93396315438e6e1c426fd338cc42685d2e", - "packages/module-diagrams/src/skin.generated.ts": "3c78137114fdb7ac4d376bec30c871c57ebba64fe3872427807a8b4e77200996", - "packages/module-diagrams/src/check.ts": "67e6497e3e66c91ae0a5c86cd99800f684141f2a56e4b9ccefc79a1c8277f7a9", - "packages/module-diagrams/src/svg-model.ts": "a72bc6967654882691527cb394c46325cb12f4b98c23855aeff68b9c36108b2e", - "packages/module-diagrams/src/geometry.ts": "f8620fe7c216e92e325e775e0f7448a104bba6da0c149d7d01fce80a4b173191", - "packages/module-diagrams/src/drawing-style.ts": "cf1205bce1ab55197b70801bda46f915419ff174d5a1374a1c87df1f796bb36b", - "packages/module-diagrams/src/ui.tsx": "e1931a9c6e069d4f90b5d9ca9db25417db73c5c18d2d7d02114b6cf71183640e", - "packages/module-diagrams/src/layout.ts": "a07ec439599855bbfea587e68eeafbb151fcc52b0b8999ef3f9145e4b2d70622", - "packages/module-diagrams/src/skin.ts": "b49834b6119b5bfa7b51d538b4896d2422d469216ffd517bf1ca401fc351f05a", - "packages/module-diagrams/src/render.ts": "e1567e2fe9158049b92b0706a4af54ba06beee4d2022cf4538705ef27251c581", - "packages/module-diagrams/src/spec.ts": "32cfea76ec701e80a2bb06b0c892d95f888d92921f75dcf873c6a071962e7fd8", - "packages/module-diagrams/src/positional-check.ts": "50736c5283fdefbe9c0b501fb385445e3092867ad93cf6e3aa744f4aedae1e4e", - "packages/module-diagrams/src/positional-layout.ts": "47759c55dbd58bbec1cf25868f0f07270c1cec4d1a70c8f67ed29498ce8ad6ff", - "packages/module-diagrams/src/positional-spec.ts": "2ab49b3b1f68610a4fea8ac90cde0a34ac96e099d21f7d3383fa72b44ce64a87", - "packages/module-diagrams/src/containment.ts": "bb8ce8a46399e86e779d95c79c26e72db2d0005a9f517bcb86d0d4f0d79f4a24", - "packages/module-diagrams/src/node-link-check.ts": "8d79f23079a7c9e0592315ae37515fcf92af9c70a1992cbf52ba9d6032fff3eb", - "packages/module-diagrams/src/node-link-svg.ts": "58865c81cea002b7373d54d68ef350bf5d436efd7c3b185336a6492bec784b9d", - "packages/module-diagrams/skills/diagram/references/examples/positional/flywheel.diagram.yaml": "7f0a2e0a6a568bbebb9e93f8df920a7bb1a4592b0863df7169af007188f75519", - "packages/module-diagrams/skills/diagram/references/examples/positional/funnel.diagram.yaml": "f07c66e0884e43480e2433a38f46b1c30920f63b160c11d731e4dbe360c0bb3a", - "packages/module-diagrams/skills/diagram/references/examples/positional/layer-stack.diagram.yaml": "7de880f4a717ab37174fbb07554d23d6cc97c28cce2a6b7841ec2a2e02ee8ec5", - "packages/module-diagrams/skills/diagram/references/examples/positional/loop.diagram.yaml": "f646cc67dc0f1e74638fe508e43b777853247a2befd0acdb0c763c88cedaf725", - "packages/module-diagrams/skills/diagram/references/examples/positional/pyramid.diagram.yaml": "b400671e033ab21d8d076b11a0011f4c2ae402d394d95b4a441ff974eede07f1", - "packages/module-diagrams/skills/diagram/references/examples/positional/quadrant.diagram.yaml": "a34c654a0c4894cae18dc5a19d656bd69c08cf5422cef120f2c0b539ed7d7175", - "packages/module-diagrams/skills/diagram/references/examples/positional/venn.diagram.yaml": "a762f39dfa71cfc559ecf15b659bca094c5c9f7797e9147cc668bcdbccc987a3", - "packages/module-diagrams/skills/diagram/references/examples/architecture.diagram.yaml": "0c6d9a736fb3337f58b2430afc35b7bb597e42fd97d252b80ff721bb9bddaa8a", - "packages/module-diagrams/skills/diagram/references/examples/flowchart.diagram.yaml": "46ab66859d500bb36e327adc73375b9f48461ea2137ce24c87226b9aaaa41a97", - "packages/module-diagrams/skills/diagram/references/examples/state-machine.diagram.yaml": "2411a0e1bff9509f4fe3dad2fdfd92b55a9886e59520dbead6302b43ca00a964", - "packages/module-diagrams/skills/diagram/references/examples/tree.diagram.yaml": "005933705b5836ef083761d47c8ff52eec644618ee07ef726fc807a8f418c29e", - "packages/module-diagrams/skills/diagram/references/examples/er.diagram.yaml": "c28b51b3aa3f177c90e4df088edca9da918034a16721d1afde6373495771bd4a", - "packages/module-diagrams/skills/diagram/references/examples/dependency.diagram.yaml": "d5474b1abf5b11ad5826c099f4fbf2d33ca0e44b2b10eca287056da73f0102ad", - "packages/module-diagrams/skills/diagram/references/examples/architecture-containment.diagram.yaml": "8efc225957ba0fa6a51802448098895de838fa75087f3b4202df8196d0c622fc" - } -}, -{ - // #1599 re-audit: design-font-checks.ts only adds a synchronous layout read of its probe host; no sink, call, argument or producer changes. - "command": "diagramRasterComparison", - "owner": "packages/ui-react/tests/browser/diagram-export-command.ts", - "ownerHash": "f7c3d14ccf96438bf4e28ecc1929b1208fb99520d21a9947086bb43bca933328", - "caller": "packages/ui-react/tests/browser/diagrams-export.layout.tsx", - "callerHash": "2730c38d2b808280c8798cc33adceee54f3c3b7e0a6beff2d2066552d8fceb9f", - "calls": 3, - "sink": "page.setContent(`${html}`)", - "producers": { - "packages/ui-kit/tests/visual/zero-request-replay.ts": "694080b66abfd6235d1873e63c908f4284b8804e5f3ff2ac98ca89169c59290e", - "packages/ui-kit/tests/visual/form-browser.ts": "3ccf67a71fa64af195bbf8cf6d173064dc9d2d4fc6abc699fa0a638c352ca62e", - "packages/ui-kit/tests/visual/design-font-setup.ts": "ef812cb97c62da898dc0050cdfc09762163dfdb2cac1e3b813d586fd0fa95fb2", - "packages/ui-kit/tests/visual/design-font-checks.ts": "502748af10e70e34583dc82f0f9de21d59d1b86829aa80d29ce04e071da464cd", - "packages/ui-kit/tests/visual/rank-footer-browser.ts": "7c4a2b0e4b5d3f40f2cc84af86f852c36068791fcb1dc6f8989f2863d51733a0", - "scripts/captures/fonts.ts": "a0d96b46f110e929e34cdc592927c4a23dedde9f672e059bfae7bba10e8349cd", - "scripts/captures/font-lock.json": "3ec58a552059527131bda0277703425243a63aa311d58b67201a7b2c9fe136ad", - "scripts/captures/fonts.css": "1a6035cc96ef6b928378a04b1f81c13b52362f18fa00e087f4a5f15155482a4d", - "packages/ui-kit/.storybook/preview-head.html": "66da7597557f1418096239edcd74f7a8decfc70dfc8f1d820de0cf365df41ed7", - "packages/module-diagrams/tests/fixtures/renderer-fixture.ts": "dc0db9aba9cd425c0cb12bd0241c6d9b4d8edd4a1ed6270e391f9d0cae7018be", - "packages/module-diagrams/tests/fixtures/adopted-homecoming-relay.diagram.yaml": "bc5d906627a8392da7921f8d74ff72eb7de4fb9cf03879fc6c83b1aaec0ee3a4", - "packages/module-diagrams/src/callout-path.ts": "94354204bac1f9d2e8fffef49123fc787c47f07bdcce5b7593161a63468cb3fa", - "packages/module-diagrams/src/callouts.ts": "6da78e9cc418771268298034896fd39976ab823d843c5874ef8ca15fe5f96e2c", - "packages/module-diagrams/src/legend.ts": "d5a9e9803a8b81100737cac0cc8b3fc8fdcb97c11a7d0ba10ced598a71744568", - "packages/module-diagrams/src/axis-check.ts": "ba2133b3c42bcd72abcdb7200ba4fd4a05656aee0028b7894db7a22bcafbdbe9", - "packages/module-diagrams/src/axis-layout.ts": "75e78e607a91d3b5684eaf3b071f56e41c317a1b336a9c06b80608121a41c34d", - "packages/module-diagrams/src/axis-spec.ts": "55bce9fad9e94af099a55fb1f7d282247c4b5f0dbdd9b33679e2903acfc28b93", - "packages/module-diagrams/src/shape-svg.ts": "b629406bfec41e3ed9973a395a6271d69f1ce45d823591ab15b5581a0116a29b", - "packages/module-diagrams/src/shape.ts": "9d3cd34d9153410ecc7b20e5edbf01c9a68e934dbe9ce662b4cf1af988d19f40", - "packages/module-diagrams/tests/fixtures/axis-examples.ts": "3925e82b8bc2ced444d8d6019fa13a93396315438e6e1c426fd338cc42685d2e", - "packages/module-diagrams/src/skin.generated.ts": "3c78137114fdb7ac4d376bec30c871c57ebba64fe3872427807a8b4e77200996", - "packages/module-diagrams/src/check.ts": "67e6497e3e66c91ae0a5c86cd99800f684141f2a56e4b9ccefc79a1c8277f7a9", - "packages/module-diagrams/src/svg-model.ts": "a72bc6967654882691527cb394c46325cb12f4b98c23855aeff68b9c36108b2e", - "packages/module-diagrams/src/geometry.ts": "f8620fe7c216e92e325e775e0f7448a104bba6da0c149d7d01fce80a4b173191", - "packages/module-diagrams/src/drawing-style.ts": "cf1205bce1ab55197b70801bda46f915419ff174d5a1374a1c87df1f796bb36b", - "packages/module-diagrams/src/ui.tsx": "e1931a9c6e069d4f90b5d9ca9db25417db73c5c18d2d7d02114b6cf71183640e", - "packages/module-diagrams/src/layout.ts": "a07ec439599855bbfea587e68eeafbb151fcc52b0b8999ef3f9145e4b2d70622", - "packages/module-diagrams/src/skin.ts": "b49834b6119b5bfa7b51d538b4896d2422d469216ffd517bf1ca401fc351f05a", - "packages/module-diagrams/src/render.ts": "e1567e2fe9158049b92b0706a4af54ba06beee4d2022cf4538705ef27251c581", - "packages/module-diagrams/src/spec.ts": "32cfea76ec701e80a2bb06b0c892d95f888d92921f75dcf873c6a071962e7fd8", - "packages/module-diagrams/src/positional-check.ts": "50736c5283fdefbe9c0b501fb385445e3092867ad93cf6e3aa744f4aedae1e4e", - "packages/module-diagrams/src/positional-layout.ts": "47759c55dbd58bbec1cf25868f0f07270c1cec4d1a70c8f67ed29498ce8ad6ff", - "packages/module-diagrams/src/positional-spec.ts": "2ab49b3b1f68610a4fea8ac90cde0a34ac96e099d21f7d3383fa72b44ce64a87", - "packages/module-diagrams/src/containment.ts": "bb8ce8a46399e86e779d95c79c26e72db2d0005a9f517bcb86d0d4f0d79f4a24", - "packages/module-diagrams/src/node-link-check.ts": "8d79f23079a7c9e0592315ae37515fcf92af9c70a1992cbf52ba9d6032fff3eb", - "packages/module-diagrams/src/node-link-svg.ts": "58865c81cea002b7373d54d68ef350bf5d436efd7c3b185336a6492bec784b9d", - "packages/module-diagrams/skills/diagram/references/examples/positional/flywheel.diagram.yaml": "7f0a2e0a6a568bbebb9e93f8df920a7bb1a4592b0863df7169af007188f75519", - "packages/module-diagrams/skills/diagram/references/examples/positional/funnel.diagram.yaml": "f07c66e0884e43480e2433a38f46b1c30920f63b160c11d731e4dbe360c0bb3a", - "packages/module-diagrams/skills/diagram/references/examples/positional/layer-stack.diagram.yaml": "7de880f4a717ab37174fbb07554d23d6cc97c28cce2a6b7841ec2a2e02ee8ec5", - "packages/module-diagrams/skills/diagram/references/examples/positional/loop.diagram.yaml": "f646cc67dc0f1e74638fe508e43b777853247a2befd0acdb0c763c88cedaf725", - "packages/module-diagrams/skills/diagram/references/examples/positional/pyramid.diagram.yaml": "b400671e033ab21d8d076b11a0011f4c2ae402d394d95b4a441ff974eede07f1", - "packages/module-diagrams/skills/diagram/references/examples/positional/quadrant.diagram.yaml": "a34c654a0c4894cae18dc5a19d656bd69c08cf5422cef120f2c0b539ed7d7175", - "packages/module-diagrams/skills/diagram/references/examples/positional/venn.diagram.yaml": "a762f39dfa71cfc559ecf15b659bca094c5c9f7797e9147cc668bcdbccc987a3", - "packages/module-diagrams/skills/diagram/references/examples/architecture.diagram.yaml": "0c6d9a736fb3337f58b2430afc35b7bb597e42fd97d252b80ff721bb9bddaa8a", - "packages/module-diagrams/skills/diagram/references/examples/flowchart.diagram.yaml": "46ab66859d500bb36e327adc73375b9f48461ea2137ce24c87226b9aaaa41a97", - "packages/module-diagrams/skills/diagram/references/examples/state-machine.diagram.yaml": "2411a0e1bff9509f4fe3dad2fdfd92b55a9886e59520dbead6302b43ca00a964", - "packages/module-diagrams/skills/diagram/references/examples/tree.diagram.yaml": "005933705b5836ef083761d47c8ff52eec644618ee07ef726fc807a8f418c29e", - "packages/module-diagrams/skills/diagram/references/examples/er.diagram.yaml": "c28b51b3aa3f177c90e4df088edca9da918034a16721d1afde6373495771bd4a", - "packages/module-diagrams/skills/diagram/references/examples/dependency.diagram.yaml": "d5474b1abf5b11ad5826c099f4fbf2d33ca0e44b2b10eca287056da73f0102ad", - "packages/module-diagrams/skills/diagram/references/examples/architecture-containment.diagram.yaml": "8efc225957ba0fa6a51802448098895de838fa75087f3b4202df8196d0c622fc", - "packages/module-diagrams/src/flatten.ts": "0afc5a8fa2caa2adedf83fb3d3d323698a06d7a61243350a699e39457dfb70ab", - "packages/module-diagrams/src/fonts.ts": "e575dbabbaa452f22389e61770b02200e78b965018f61662573f985024801419", - "packages/module-diagrams/assets/fonts/2.ttf": "44ce4a84f20d60f24539bd0cef11f79c29e38609e0f8adf18551c9794a5d9dc3", - "packages/module-diagrams/assets/fonts/4.ttf": "df54dbfafba61d4911eb3dab9bba2d20531fb009f01d64dd42fa96ab862584d8", - "packages/module-diagrams/assets/fonts/6.ttf": "b4fc14ec283d54236fd302cdb92546f98ae0ff061ca5ee23453a02bdf4628791", - "packages/module-diagrams/assets/fonts/7.ttf": "50357df108c5d297ec4ece76aeddf49561f3794f67af077cfc2c711b7a75b439" - } -}]; -export interface BrowserDocumentInputs {runtime:string[];bytes:string[];} -/** The reviewed declarations, read-only, for the producer-closure guard in tests (#2348). */ -export const reviewedBrowserDocuments:readonly Readonly[]=declarations; -/** Requires a successful complete activation audit; aliases/loaders are checked - * there. All producers/dependencies retain normal input traversal here. - */ -export function boundBrowserDocuments(root:string,files:readonly string[],importers:BrowserImporters):Map>{ - return evaluateBrowserDocuments(root,files,importers).bound; -} -/** Why each declared document owner did not bind, naming the first offending file (#2348). */ -export function browserDocumentRefusals(root:string,files:readonly string[],importers:BrowserImporters):Map{ - return evaluateBrowserDocuments(root,files,importers).refusals; -} -function evaluateBrowserDocuments(root:string,files:readonly string[],importers:BrowserImporters){ - const result=new Map>(),refusals=new Map(); - const matches=(file:string,hash:string)=>{const path=resolve(root,file);return existsSync(path)&&realpathSync(path)===path&&createHash("sha256").update(readFileSync(path)).digest("hex")===hash;}; - if(!matches(config,"89ea7a414a191a5624fce2dff8e0434aac5474c4c5b74d13499848cd17e2b257")){for(const declaration of declarations)refusals.set(declaration.owner,`unreviewed configuration ${config}`);return {bound:result,refusals};} - for(const declaration of declarations){ - const callers=new Map([[declaration.caller,{hash:declaration.callerHash,calls:declaration.calls}],...Object.entries(declaration.additionalCallers??{})]); - const absent=[config,declaration.owner,...callers.keys()].find(file=>!files.includes(file)); - const drifted=!matches(declaration.owner,declaration.ownerHash)?declaration.owner: - [...callers].find(([file,entry])=>!matches(file,entry.hash))?.[0]??Object.entries(declaration.producers).find(([file,hash])=>!matches(file,hash))?.[0]; - const importer=[...(importers.get(declaration.owner)??[])].find(file=>file!==config); - const refusal=absent?`not selected: ${absent}`:drifted?`stale reviewed pin: ${drifted}`:importer?`direct command-owner importer: ${importer}`:undefined; - if(refusal){refusals.set(declaration.owner,refusal);continue;} - const counts=new Map([...callers.keys()].map(file=>[file,0]));let unsafe=false; - for(const file of files){ - if(!/\.[cm]?[jt]sx?$/.test(file))continue; - const source=ts.createSourceFile(file,readFileSync(resolve(root,file),"utf8"),ts.ScriptTarget.Latest,true),names=new Set(); - for(const statement of source.statements)if(ts.isImportDeclaration(statement)&&ts.isStringLiteral(statement.moduleSpecifier)&&statement.moduleSpecifier.text==="vitest/browser"){ - const bindings=statement.importClause?.namedBindings; - if(bindings&&ts.isNamedImports(bindings))for(const binding of bindings.elements)if((binding.propertyName?.text??binding.name.text)==="commands")names.add(binding.name.text); - } - const bindings=(node:ts.Node)=>{ - if(ts.isVariableDeclaration(node)&&ts.isObjectBindingPattern(node.name)&&node.initializer&&ts.isAwaitExpression(node.initializer)&&ts.isCallExpression(node.initializer.expression)&&node.initializer.expression.expression.kind===ts.SyntaxKind.ImportKeyword){ - const literal=node.initializer.expression.arguments[0]; - if(literal&&ts.isStringLiteral(literal)&&literal.text==="vitest/browser")for(const binding of node.name.elements)if(ts.isIdentifier(binding.name)&&(binding.propertyName?.getText(source)??binding.name.text)==="commands")names.add(binding.name.text); - } - ts.forEachChild(node,bindings); - };bindings(source); - const walk=(node:ts.Node)=>{ - if(ts.isPropertyAccessExpression(node)&&ts.isIdentifier(node.expression)&&names.has(node.expression.text)&&node.name.text===declaration.command){ - if(!callers.has(file)||!ts.isCallExpression(node.parent)||node.parent.expression!==node){unsafe=true;refusals.set(declaration.owner,`${callers.has(file)?"unchecked command use":"unreviewed caller"}: ${file}`);}else counts.set(file,counts.get(file)!+1); - } - ts.forEachChild(node,walk); - };walk(source); - } - // Form: cleanup(null), literal paragraphs and a reporting/scroll script. - // Ghost: argument-free call immediately after the exact Performance story; - // all replay network attempts abort and fail before/after fonts and trace. - const producers=Object.keys(declaration.producers); - const miscounted=[...callers].find(([file,entry])=>counts.get(file)!==entry.calls)?.[0]; - if(!unsafe&&miscounted)refusals.set(declaration.owner,`reviewed call count changed: ${miscounted}`); - if(!unsafe&&!miscounted)result.set(declaration.owner,new Map([[declaration.sink,{runtime:[...callers.keys(),...producers.filter(file=>/\.[cm]?[jt]sx?$/.test(file))],bytes:producers.filter(file=>!/\.[cm]?[jt]sx?$/.test(file))}]])); - } - return {bound:result,refusals}; -} diff --git a/scripts/bound-browser-runtime-inputs.ts b/scripts/bound-browser-runtime-inputs.ts deleted file mode 100644 index 04dc53555c..0000000000 --- a/scripts/bound-browser-runtime-inputs.ts +++ /dev/null @@ -1,105 +0,0 @@ -/** Exact reader/default/verified-data bindings under a complete runner inventory. */ -import {resolveRuntimeModule} from "./runtime-module-resolution"; -import { createHash } from "node:crypto"; -import { existsSync, readFileSync, realpathSync } from "node:fs"; -import { join, relative, resolve } from "node:path"; -import ts from "typescript"; -const declarations = [ - { - "owner": "scripts/browser-shards.ts", - "caller": "scripts/browser-sequencer.ts", - "ownerHash": "958aeecec0f2552037163345a560116718b928fd334ddf9c61c398bc8f691071", - "callerHash": "fd6a75b71fba29a169f0c84f488a1d1d9927e87c0612dc939122750368cbb77c", - "sites": { - "readFileSync(path, \"utf8\")": [ - "scripts/browser-shard-costs.json" - ] - } - }, - { - "owner": "scripts/captures/fonts.ts", - "data": { - "scripts/captures/font-lock.json": "3ec58a552059527131bda0277703425243a63aa311d58b67201a7b2c9fe136ad", - "scripts/captures/fonts.css": "1a6035cc96ef6b928378a04b1f81c13b52362f18fa00e087f4a5f15155482a4d", - "packages/ui-kit/.storybook/preview-head.html": "66da7597557f1418096239edcd74f7a8decfc70dfc8f1d820de0cf365df41ed7" - }, - "caller": "packages/ui-kit/tests/visual/rank-footer-browser.ts", - "ownerHash": "a0d96b46f110e929e34cdc592927c4a23dedde9f672e059bfae7bba10e8349cd", - "callerHash": "7c4a2b0e4b5d3f40f2cc84af86f852c36068791fcb1dc6f8989f2863d51733a0", - "sites": { - "readFile(resolve(root, \"scripts/captures/font-lock.json\"))": [ - "scripts/captures/font-lock.json" - ], - "readFile(resolve(root, lock.stylesheet.file))": [ - "scripts/captures/fonts.css" - ], - "readFile(resolve(root, \"packages/ui-kit/.storybook/preview-head.html\"), \"utf8\")": [ - "packages/ui-kit/.storybook/preview-head.html" - ], - "readFile(resolve(cache, entry.file))": [ - "scripts/captures/font-lock.json" - ] - } - }, -{ - // #2469 re-audit: the caller adds raster-parity diagnostics and a repaint command; its sole owner edge (`diagramFontCss`) and argument-free `diagramFontStyles` call are unchanged. - "owner": "packages/module-diagrams/src/fonts.ts", - "caller": "packages/ui-react/tests/browser/diagram-export-command.ts", - "ownerHash": "e575dbabbaa452f22389e61770b02200e78b965018f61662573f985024801419", - "callerHash": "64674a93954a3d92ea99c9707fd2a6b693ca43fc7c4680243eff8cd2cef2fee6", - "data": { - "packages/module-diagrams/assets/fonts/2.ttf": "44ce4a84f20d60f24539bd0cef11f79c29e38609e0f8adf18551c9794a5d9dc3", - "packages/module-diagrams/assets/fonts/4.ttf": "df54dbfafba61d4911eb3dab9bba2d20531fb009f01d64dd42fa96ab862584d8", - "packages/module-diagrams/assets/fonts/6.ttf": "b4fc14ec283d54236fd302cdb92546f98ae0ff061ca5ee23453a02bdf4628791", - "packages/module-diagrams/assets/fonts/7.ttf": "50357df108c5d297ec4ece76aeddf49561f3794f67af077cfc2c711b7a75b439" - }, - "sites": { - "readFileSync(new URL(`../assets/fonts/${face.file}.ttf`,import.meta.url))": [ - "packages/module-diagrams/assets/fonts/2.ttf", - "packages/module-diagrams/assets/fonts/4.ttf", - "packages/module-diagrams/assets/fonts/6.ttf", - "packages/module-diagrams/assets/fonts/7.ttf" - ] - } -} -]; -const options:ts.CompilerOptions={moduleResolution:ts.ModuleResolutionKind.Bundler,module:ts.ModuleKind.ESNext,customConditions:["bun"],allowImportingTsExtensions:true}; -export type BrowserRuntimeBindings=Map>; -/** Only complete activation-audited source inventories may call this helper. - * Exact caller bodies establish the cost-file default and lock-verified font - * root/cache flow. Any new import/loader edge to either reader invalidates it. - * Targets are bytes consumed by those readers, not executed source or CSS. - */ -export type BrowserImporters=Map>; -export function browserImporters(root:string,files:readonly string[]):BrowserImporters { - const result:BrowserImporters=new Map(); - for(const file of files){ - if(!/\.[cm]?[jt]sx?$/.test(file))continue; - const source=ts.createSourceFile(file,readFileSync(join(root,file),"utf8"),ts.ScriptTarget.Latest,true); - const edge=(specifier:string)=>{ - const target=resolveRuntimeModule(specifier,join(root,file),options)?.resolvedFileName; - if(!target)return;const normalized=relative(root,target).replaceAll("\\","/"); - const sources=result.get(normalized)??new Set();sources.add(file);result.set(normalized,sources); - }; - const walk=(node:ts.Node)=>{ - if((ts.isImportDeclaration(node)||ts.isExportDeclaration(node))&&node.moduleSpecifier&&ts.isStringLiteral(node.moduleSpecifier)&& - !(ts.isImportDeclaration(node)?node.importClause?.isTypeOnly:node.isTypeOnly))edge(node.moduleSpecifier.text); - if(ts.isCallExpression(node)&&node.arguments.length===1&&ts.isStringLiteralLike(node.arguments[0]!)&& - (node.expression.kind===ts.SyntaxKind.ImportKeyword||node.expression.getText(source)==="require"))edge(node.arguments[0]!.text); - ts.forEachChild(node,walk); - };walk(source); - } - return result; -} -export function boundBrowserRuntimeInputs(root:string,files:readonly string[],importers=browserImporters(root,files)):BrowserRuntimeBindings { - const result:BrowserRuntimeBindings=new Map(); - for(const declaration of declarations){ - if(!files.includes(declaration.owner)||!files.includes(declaration.caller))continue; - const matches=(file:string,expected:string)=>{const path=resolve(root,file);return existsSync(path)&&realpathSync(path)===path&&createHash("sha256").update(readFileSync(path)).digest("hex")===expected;}; - if(!matches(declaration.owner,declaration.ownerHash)||!matches(declaration.caller,declaration.callerHash))continue; - if(declaration.data && Object.entries(declaration.data).some(([file,digest])=>!matches(file,digest)))continue; - const sealed=[...(importers.get(declaration.owner)??[])].every(file=>file===declaration.caller); - if(sealed)result.set(declaration.owner,new Map(Object.entries(declaration.sites))); - } - return result; -} diff --git a/scripts/browser-command-activation.ts b/scripts/browser-command-activation.ts deleted file mode 100644 index 7741800549..0000000000 --- a/scripts/browser-command-activation.ts +++ /dev/null @@ -1,237 +0,0 @@ -/** Conservative registration audit. This prototype never removes execution inputs. */ -import {resolveRuntimeModule} from "./runtime-module-resolution"; -import { createHash } from "node:crypto"; -import { existsSync, readFileSync, realpathSync } from "node:fs"; -import { dirname, isAbsolute, join, relative, resolve } from "node:path"; -import { builtinModules } from "node:module"; -import ts from "typescript"; -import type { Spec } from "./proof-inputs"; - -export interface CommandCandidate { owner: string; name: string; } -export interface CommandActivationAudit { - candidates: (CommandCandidate & { projects: string[] })[]; - files: string[]; - roots: string[]; - unresolved: string[]; - /** Registration is necessary but does not prove module initialization safe. */ - executionExcluded: false; -} -const builtins = new Set(builtinModules.flatMap(name => [name, `node:${name}`])); -const options: ts.CompilerOptions = { moduleResolution: ts.ModuleResolutionKind.Bundler, module: ts.ModuleKind.ESNext, - customConditions: ["bun"], resolveJsonModule: true, allowImportingTsExtensions: true, jsx: ts.JsxEmit.ReactJSX }; -const propertyName = (node: ts.PropertyName) => ts.isIdentifier(node) || ts.isStringLiteral(node) ? node.text : undefined; - -/** Audit the actual config, every selected spec, and all literal setup/global hooks. - * Unknown registrations, invocation aliases, loaders and workspace imports stay fresh. - * Imported top-level effects are deliberately still interpreted by input closure. - */ -export function auditCommandActivation(root: string, config: string, selected: readonly Spec[], candidates: readonly CommandCandidate[]): CommandActivationAudit { - root = realpathSync(root); - const files = new Set(), unresolved = new Set(), visited = new Set(); - const inactive: CommandActivationAudit["candidates"] = []; - const projects = new Set(selected.map(spec => spec.project)); - if (!selected.length || projects.size === 0 || new Set(candidates.map(candidate => candidate.name)).size !== candidates.length) - unresolved.add("Missing or ambiguous command activation inventory"); - const sourceFile = (file: string) => { - const absolute = resolve(root, file), normalized = relative(root, absolute).replaceAll("\\", "/"); - if (!normalized || normalized.startsWith("../") || isAbsolute(normalized) || !existsSync(absolute) || realpathSync(absolute) !== absolute) - throw new Error(`Unsupported activation source: ${file}`); - files.add(normalized); - const source = ts.createSourceFile(normalized, readFileSync(absolute, "utf8"), ts.ScriptTarget.Latest, true); - if (/\.[cm]?[jt]sx?$/.test(normalized) && (source as ts.SourceFile & { parseDiagnostics: readonly ts.Diagnostic[] }).parseDiagnostics.length) - throw new Error(`Invalid activation source: ${file}`); - return source; - }; - const configAst = sourceFile(config); - for (const candidate of candidates) { - const owner = sourceFile(candidate.owner); - const typeImports = owner.statements.filter(ts.isImportDeclaration).filter(statement => - ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text === "vitest/node") - .flatMap(statement => statement.importClause?.namedBindings && ts.isNamedImports(statement.importClause.namedBindings) - ? statement.importClause.namedBindings.elements.filter(element => (element.propertyName?.text ?? element.name.text) === "BrowserCommand").map(element => element.name.text) : []); - const definitions = owner.statements.filter(ts.isVariableStatement).filter(statement => statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) - .flatMap(statement => [...statement.declarationList.declarations]).filter(declaration => ts.isIdentifier(declaration.name) && declaration.name.text === candidate.name && - declaration.initializer && ts.isArrowFunction(declaration.initializer) && declaration.type && ts.isTypeReferenceNode(declaration.type) && - ts.isIdentifier(declaration.type.typeName) && typeImports.includes(declaration.type.typeName.text)); - if (definitions.length !== 1) { unresolved.add(`Unsupported BrowserCommand definition: ${candidate.owner}`); continue; } - let imported = 0, unsafe = false; - const callback = definitions[0]!; - const ownerReferences = (node: ts.Node) => { - if (node === callback.initializer) return; - if (ts.isIdentifier(node) && node.text === candidate.name && node !== callback.name && - !((ts.isPropertySignature(node.parent) || ts.isMethodSignature(node.parent)) && node.parent.name === node)) unsafe = true; - ts.forEachChild(node, ownerReferences); - }; - ownerReferences(owner); - const registrations = new Set(); - const walk = (node: ts.Node) => { - if (ts.isIdentifier(node) && node.text === candidate.name) { - const parent = node.parent; - if (ts.isImportSpecifier(parent) && parent.name === node && !parent.propertyName) { - const declaration = parent.parent.parent.parent; - if (!ts.isImportDeclaration(declaration) || !ts.isStringLiteral(declaration.moduleSpecifier) || - relative(root, resolve(dirname(join(root, config)), declaration.moduleSpecifier.text)).replaceAll("\\", "/") !== candidate.owner) unsafe = true; - else imported++; - } else if (ts.isShorthandPropertyAssignment(parent) && parent.name === node && ts.isObjectLiteralExpression(parent.parent)) { - const commands = parent.parent.parent; - if (!ts.isPropertyAssignment(commands) || propertyName(commands.name) !== "commands" || - parent.parent.properties.some(property => !ts.isShorthandPropertyAssignment(property) && !ts.isPropertyAssignment(property))) unsafe = true; - let project: string | undefined; - for (let ancestor: ts.Node | undefined = commands.parent; ancestor && ancestor !== configAst; ancestor = ancestor.parent) { - if (!ts.isObjectLiteralExpression(ancestor)) continue; - const name = ancestor.properties.find(property => ts.isPropertyAssignment(property) && propertyName(property.name) === "name"); - if (name && ts.isPropertyAssignment(name)) { - if (ts.isStringLiteral(name.initializer)) project = name.initializer.text; - break; - } - } - if (!project) unsafe = true; else registrations.add(project); - } else unsafe = true; - } - ts.forEachChild(node, walk); - }; - walk(configAst); - if (unsafe || imported !== 1 || !registrations.size) - unresolved.add(`Active or ambiguous command registration: ${candidate.name}`); - else inactive.push({ ...candidate, projects: [...registrations].sort() }); - } - // Inspect every selected test and all hooks, including inherited hooks. Do - // not infer nonactivation from grep or only the browser category's filenames. - const roots = new Set([config, ...selected.map(spec => spec.file)]); - const hooks = (node: ts.Node) => { - if (ts.isPropertyAssignment(node) && ["setupFiles", "globalSetup", "setupFile", "globalTeardown"].includes(propertyName(node.name) ?? "")) { - const values = ts.isArrayLiteralExpression(node.initializer) ? [...node.initializer.elements] : [node.initializer]; - for (const value of values) { - if (!ts.isStringLiteral(value)) unresolved.add(`Computed activation hook: ${node.getText(configAst)}`); - else roots.add(relative(root, resolve(dirname(join(root, config)), value.text)).replaceAll("\\", "/")); - } - } - ts.forEachChild(node, hooks); - }; - hooks(configAst); - const configUnknowns = (node: ts.Node) => { - if (ts.isSpreadAssignment(node) || ts.isComputedPropertyName(node)) unresolved.add("Unsupported computed/spread activation configuration"); - ts.forEachChild(node, configUnknowns); - }; - configUnknowns(configAst); - const visit = (file: string) => { - if (visited.has(file)) return; - visited.add(file); - let source: ts.SourceFile; - try { source = sourceFile(file); } catch (error) { unresolved.add(String(error)); return; } - if (!/\.[cm]?[jt]sx?$/.test(file)) return; - const commands = new Set(); - const moduleRequire = source.statements.filter(ts.isImportDeclaration).some(statement => ts.isStringLiteral(statement.moduleSpecifier) && - ["node:module", "module"].includes(statement.moduleSpecifier.text) && statement.importClause?.namedBindings && ts.isNamedImports(statement.importClause.namedBindings) && - statement.importClause.namedBindings.elements.some(binding => !binding.propertyName && binding.name.text === "createRequire")); - const boundedRequireUse = (node: ts.Identifier) => { - if (node.text !== "require" || !moduleRequire) return false; - const parent = node.parent; - if (ts.isVariableDeclaration(parent) && parent.name === node && parent.initializer?.getText(source) === "createRequire(import.meta.url)") return true; - if (!ts.isPropertyAccessExpression(parent) || parent.expression !== node || parent.name.text !== "resolve" || !ts.isCallExpression(parent.parent) || parent.parent.expression !== parent) return false; - return parent.parent.arguments.length === 1 && ts.isStringLiteral(parent.parent.arguments[0]!) && parent.parent.arguments[0]!.text !== "vitest/browser"; - }; - const edge = (specifier: string, typeOnly: boolean) => { - if (typeOnly || builtins.has(specifier) || specifier.startsWith("bun:")) return; - // Styles/assets are bytes, not JavaScript command entrypoints. Their - // producer ownership remains mandatory in the separate input closure. - if (/\.(?:css|svg|png|jpe?g|woff2?|wasm)(?:\?.*)?$/.test(specifier)) return; - if (file !== config && candidates.some(candidate => specifier.startsWith(".") && resolve(dirname(join(root, file)), specifier) === resolve(root, candidate.owner))) - unresolved.add(`Selected execution imports command owner: ${file}`); - const result = resolveRuntimeModule(specifier, join(root, file), options); - if (result?.isExternalLibraryImport && !specifier.startsWith("@schlessera/")) return; - const asset = specifier.startsWith(".") ? resolve(dirname(join(root, file)), specifier.split("?")[0]!) : ""; - const target = result?.resolvedFileName ?? (asset && existsSync(asset) ? asset : undefined); - if (!target) { unresolved.add(`Unresolved activation import ${file}: ${specifier}`); return; } - const normalized = relative(root, target).replaceAll("\\", "/"); - if (normalized.startsWith("node_modules/")) return; - if (file !== config && candidates.some(candidate => resolve(root, candidate.owner) === target)) unresolved.add(`Selected execution imports command owner: ${file}`); - visit(normalized); - }; - for (const statement of source.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text === "vitest/browser") { - const bindings = statement.importClause?.namedBindings; - if (statement.importClause?.name || bindings && ts.isNamespaceImport(bindings)) unresolved.add(`Aliased browser command namespace: ${file}`); - if (bindings && ts.isNamedImports(bindings)) for (const binding of bindings.elements) - if ((binding.propertyName?.text ?? binding.name.text) === "commands") commands.add(binding.name.text); - } - const bindings = (node: ts.Node) => { - if (ts.isVariableDeclaration(node) && node.initializer && ts.isAwaitExpression(node.initializer) && - ts.isCallExpression(node.initializer.expression) && node.initializer.expression.expression.kind === ts.SyntaxKind.ImportKeyword && - node.initializer.expression.arguments.length === 1 && ts.isStringLiteral(node.initializer.expression.arguments[0]!) && - node.initializer.expression.arguments[0]!.text === "vitest/browser") { - if (!ts.isObjectBindingPattern(node.name)) unresolved.add(`Aliased dynamic browser namespace: ${file}`); - else for (const binding of node.name.elements) { - if (binding.dotDotDotToken || binding.propertyName && !ts.isIdentifier(binding.propertyName) || !ts.isIdentifier(binding.name)) unresolved.add(`Ambiguous dynamic browser binding: ${file}`); - else if ((binding.propertyName && ts.isIdentifier(binding.propertyName) ? binding.propertyName.text : binding.name.text) === "commands") commands.add(binding.name.text); - } - } - ts.forEachChild(node, bindings); - }; - bindings(source); - const walk = (node: ts.Node) => { - if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier) && node.moduleSpecifier.text === "vitest/browser" && !node.isTypeOnly) - unresolved.add(`Re-exported browser command namespace: ${file}`); - if (ts.isCallExpression(node) && node.arguments.length === 1 && ts.isStringLiteral(node.arguments[0]!) && node.arguments[0]!.text === "vitest/browser" && - (node.expression.kind === ts.SyntaxKind.ImportKeyword || node.expression.getText(source) === "require")) { - const parent = node.parent; - if (node.expression.kind !== ts.SyntaxKind.ImportKeyword || !ts.isAwaitExpression(parent) || !ts.isVariableDeclaration(parent.parent) || !ts.isObjectBindingPattern(parent.parent.name)) - unresolved.add(`Unsupported dynamic browser namespace: ${file}`); - } - if (ts.isIdentifier(node) && ["eval", "Function", "require"].includes(node.text) && !boundedRequireUse(node) && - !(ts.isCallExpression(node.parent) && node.parent.expression === node) && - !(ts.isNewExpression(node.parent) && node.parent.expression === node)) unresolved.add(`Aliased activation evaluator/loader: ${file}`); - if (ts.isCallExpression(node) && /^(?:eval|Function)$/.test(node.expression.getText(source)) || - ts.isNewExpression(node) && node.expression.getText(source) === "Function") unresolved.add(`Dynamic activation evaluation: ${file}`); - if (ts.isIdentifier(node) && commands.has(node.text)) { - const parent = node.parent; - if (!ts.isImportSpecifier(parent) && !ts.isBindingElement(parent)) { - if (!ts.isPropertyAccessExpression(parent) || parent.expression !== node || !ts.isCallExpression(parent.parent) || parent.parent.expression !== parent) - unresolved.add(`Dynamic or aliased command invocation: ${file}`); - else if (candidates.some(candidate => candidate.name === parent.name.text)) unresolved.add(`Selected command invocation ${file}: ${parent.name.text}`); - } - } - if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) - edge(node.moduleSpecifier.text, ts.isImportDeclaration(node) ? node.importClause?.isTypeOnly === true : node.isTypeOnly); - if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword || ts.isIdentifier(node.expression) && node.expression.text === "require")) { - if (node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0]!)) edge(node.arguments[0]!.text, false); - else unresolved.add(`Computed activation loader: ${file}`); - } - if (ts.isCallExpression(node) && node.expression.getText(source).startsWith("import.meta.glob")) unresolved.add(`Computed activation glob: ${file}`); - ts.forEachChild(node, walk); - }; - walk(source); - }; - for (const file of roots) visit(file); - return { candidates: inactive, files: [...files].sort(), roots: [...roots].sort(), unresolved: [...unresolved].sort(), executionExcluded: false }; -} - -// This is a bounded audit of one actual runner/configuration and its seven -// dormant callbacks, not a JavaScript partial evaluator. A source edit requires -// an explicit new audit; imports still run through normal runtime closure. -const auditedSources: Record = { - "packages/ui-react/tests/browser/mermaid-proof-command.ts": "df7cc849b743c55c897236cd021793ad489548d780db2d053248116563832d3c", - "packages/ui-react/tests/browser/offline/scene-commands.ts": "ad76a69e553d1d0208a5a92c8270876403930788964bd75f3887d06a426c17d2", - "packages/ui-kit/vitest.config.ts": "89ea7a414a191a5624fce2dff8e0434aac5474c4c5b74d13499848cd17e2b257", - "packages/ui-kit/vite.config.ts": "ffdb82cbcf2fd0106799690580ca7af612a0bcceeacf198ef0e8a77313b4cb91", - "scripts/visual.mjs": "364a3719574894b6f47113d62b50aee60a5b9d09e5f1eba3200efc608ca4f6a6", - "packages/ui-react/tests/browser/hygiene-loop-command.ts": "fd9c5e18f1e374be3657fefd6c7aac76f16794f1ca59f0f038761c75130da35a", - "packages/ui-react/tests/browser/hygiene-server-command.ts": "13706860dac40cab354554cadbd809143a0f32ee0314d8fcec8f1d6d1d70b1bb", - "packages/ui-react/tests/browser/policy-server-command.ts": "9cd4bfe73ea42e200f795c42a4ce1d2eb014daf9e117275d171b95314db1f148", - "packages/ui-react/tests/browser/dispatch-actions-command.ts": "1e832b08a6560980f224bfc38713517091f381446da8e6eabeb28062f7ac151e", - "packages/ui-react/tests/browser/hygiene-completion-frame.ts": "30d48865921cb18bfcae7942fedf53e8933c04444c85fdad291d2aca2b30d2f1" -}; -export function auditedInactiveCommands(root: string, selected: readonly Spec[]) { - for (const [file, expected] of Object.entries(auditedSources)) { - const absolute = resolve(root,file); - if (!existsSync(absolute) || realpathSync(absolute) !== absolute || createHash("sha256").update(readFileSync(absolute)).digest("hex") !== expected) return undefined; - } - return {config:"packages/ui-kit/vitest.config.ts",selected,candidates:[ - {name:"mermaidOutput",owner:"packages/ui-react/tests/browser/mermaid-proof-command.ts"}, - {name:"mermaidScreenComparison",owner:"packages/ui-react/tests/browser/mermaid-proof-command.ts"}, - {name:"offlineScene",owner:"packages/ui-react/tests/browser/offline/scene-commands.ts"}, - {name:"hygieneLoop",owner:"packages/ui-react/tests/browser/hygiene-loop-command.ts"}, - {name:"hygieneServer",owner:"packages/ui-react/tests/browser/hygiene-server-command.ts"}, - {name:"policyServer",owner:"packages/ui-react/tests/browser/policy-server-command.ts"}, - {name:"dispatchActions",owner:"packages/ui-react/tests/browser/dispatch-actions-command.ts"}, - ]}; -} diff --git a/scripts/browser-input-closure.ts b/scripts/browser-input-closure.ts index 1248e9a817..d608c05503 100644 --- a/scripts/browser-input-closure.ts +++ b/scripts/browser-input-closure.ts @@ -1,17 +1,13 @@ -/** Source-owned browser proof inputs. Unknown edges retain complete broad proof. */ +/** Source-owned browser inputs for category selection. A changed file inside a + * category's closure selects it; an edge this walk cannot resolve leaves the + * closure unresolved, and `closureSelects` then keeps the planner's broad rule. + * Nothing here pins source bytes: the audited bindings that resolved such + * edges for proof retention were retired with it (#4107). */ import {resolveRuntimeModule} from "./runtime-module-resolution"; import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs"; import { builtinModules } from "node:module"; import { dirname, isAbsolute, join, relative, resolve } from "node:path"; import ts from "typescript"; -import { auditCommandActivation, type CommandCandidate } from "./browser-command-activation"; -import { generatedThemeInputs } from "./generated-theme-inputs"; -import { sourceBrowserDispatch } from "./source-browser-dispatch"; -import { boundBrowserDocuments, type BrowserDocumentInputs } from "./bound-browser-documents"; -import { browserImporters, boundBrowserRuntimeInputs, type BrowserRuntimeBindings } from "./bound-browser-runtime-inputs"; -import { sourceBrowserPayload } from "./source-browser-payloads"; -import { lockedBrowserAsset, type LockedBrowserAsset } from "./locked-browser-assets"; -import { generatedCssInputs, generatedCssReadInputs } from "./generated-build-inputs"; import { cssInputs } from "./css-inputs"; import { normalizeInventory, type Spec } from "./proof-inputs"; @@ -26,7 +22,7 @@ export interface IndirectInput { observation?: "linux-proc-self-identity"; } export interface InputDeclaration { owner: string; inputs: IndirectInput[]; } -export interface InputClosure { files: string[]; directories?: string[]; external?: LockedBrowserAsset[]; unresolved: string[]; } +export interface InputClosure { files: string[]; directories?: string[]; unresolved: string[]; } const builtins = new Set(builtinModules.flatMap(name => [name, `node:${name}`])); const sourceExtension = /\.[cm]?[jt]sx?$/; const readOperations = new Set(["readFile", "readFileSync", "readdir", "readdirSync", "readlink", "readlinkSync", "createReadStream", "open", "openSync", "opendir", "opendirSync", "access", "accessSync", "existsSync", "stat", "statSync", "lstat", "lstatSync", "watch", "watchFile", "spawn", "spawnSync", "exec", "execSync", "execFile", "execFileSync", "fork"]); @@ -36,33 +32,10 @@ function inside(root: string, file: string): string | undefined { return !path.startsWith("../") && !isAbsolute(path) ? path : undefined; } /** No declaration can suppress an unresolved call: every declaration names real inputs. */ -export function discoverInputClosure(root: string, entrypoints: readonly string[], declarations: readonly InputDeclaration[] = [], activation?: { config: string; selected: readonly Spec[]; candidates: readonly CommandCandidate[] }): InputClosure { +export function discoverInputClosure(root: string, entrypoints: readonly string[], declarations: readonly InputDeclaration[] = []): InputClosure { root = realpathSync(root); const unresolved = new Set(), files = new Set(), directories = new Set(); - const external = new Map(); const declared = new Map>(); - const inactive = new Map>(); - const executionRoots = new Set(); - let runtimeBindings: BrowserRuntimeBindings = new Map(); - let dispatchBindings = new Map>(); - let documentBindings = new Map>(); - let themeBinding: ReturnType; - if (activation) { - const audit = auditCommandActivation(root, activation.config, activation.selected, activation.candidates); - for (const failure of audit.unresolved) unresolved.add(failure); - if (!audit.unresolved.length) { - for(const file of audit.roots)executionRoots.add(file); - const importers = browserImporters(root, audit.files); - runtimeBindings = boundBrowserRuntimeInputs(root, audit.files, importers); - dispatchBindings = sourceBrowserDispatch(root, audit.files, importers); - documentBindings = boundBrowserDocuments(root, audit.files, importers); - themeBinding = generatedThemeInputs(root, audit.files, importers); - } - if (!audit.unresolved.length) for (const candidate of audit.candidates) { - const names = inactive.get(candidate.owner) ?? new Set(); - names.add(candidate.name); inactive.set(candidate.owner, names); - } - } const inputKey = (input: IndirectInput) => input.scope ? `${input.scope}\0${input.expression}` : input.expression; for (const declaration of declarations) { if (!declaration || typeof declaration.owner !== "string" || !/\.(?:[cm]?[jt]sx?|css)$/.test(declaration.owner) || !Array.isArray(declaration.inputs) || declared.has(declaration.owner) || !inside(root, resolve(root, declaration.owner)) || !existsSync(join(root, declaration.owner))) { @@ -78,10 +51,10 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ const options: ts.CompilerOptions = { moduleResolution: ts.ModuleResolutionKind.Bundler, module: ts.ModuleKind.ESNext, customConditions: ["bun"], resolveJsonModule: true, allowImportingTsExtensions: true, jsx: ts.JsxEmit.ReactJSX }; const visited = new Set(); - const visit = (file: string, scanOnly = false, sourceOnly = false) => { + const visit = (file: string, scanOnly = false) => { const absolute = resolve(root, file), normalized = inside(root, absolute); if (normalized === undefined || normalized.startsWith("node_modules/") || normalized === "node_modules") { unresolved.add(`Input escapes repository: ${file}`); return; } - const key = `${scanOnly}:${sourceOnly}:${normalized}`; + const key = `${scanOnly}:${normalized}`; if (visited.has(key)) return; visited.add(key); if (!existsSync(absolute)) { unresolved.add(`Missing input: ${normalized}`); return; } @@ -91,7 +64,7 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ const stat = ts.sys.directoryExists(absolute); if (stat) { directories.add(normalized || "."); - for (const entry of readdirSync(absolute).sort()) visit(normalized ? `${normalized}/${entry}` : entry, scanOnly, sourceOnly); + for (const entry of readdirSync(absolute).sort()) visit(normalized ? `${normalized}/${entry}` : entry, scanOnly); return; } if (scanOnly) return; // Byte inventories: Tailwind text or exact mount-bound inputs. @@ -119,12 +92,9 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ const source = readFileSync(absolute, "utf8"), ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true); if ((ast as ts.SourceFile & { parseDiagnostics: readonly ts.Diagnostic[] }).parseDiagnostics.length) unresolved.add(`Invalid source: ${normalized}`); const uses = new Set(), sites = new Set(); - const pathResolveAliases = new Set(); const aliases = new Map(), namespaces = new Set(), filesystemAliases = new Set(), shadowedBindings = new Set(); for (const statement of ast.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) { const specifier = statement.moduleSpecifier.text.replace(/^node:/, ""); - if (specifier === "path" && statement.importClause?.namedBindings && ts.isNamedImports(statement.importClause.namedBindings)) - for (const binding of statement.importClause.namedBindings.elements) if ((binding.propertyName?.text ?? binding.name.text) === "resolve") pathResolveAliases.add(binding.name.text); if (["fs", "fs/promises", "child_process"].includes(specifier)) { if (statement.importClause?.name) namespaces.add(statement.importClause.name.text); const bindings = statement.importClause?.namedBindings; @@ -137,23 +107,17 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ } const edge = (specifier: string, typeOnly = false) => { if (builtins.has(specifier) || specifier.startsWith("bun:")) return; - const generated = specifier.startsWith(".") ? generatedCssInputs(root, resolve(dirname(absolute), specifier.split("?")[0]!)) : undefined; - if (generated) { - visit(generated.entry); - for (const producer of generated.producer) visit(producer, true); - return; - } const result = typeOnly ? ts.resolveModuleName(specifier, absolute, options, ts.sys).resolvedModule : resolveRuntimeModule(specifier, absolute, options); if (!result) { // Bundler-owned assets are still repository inputs, even when TypeScript has no declaration. const asset = specifier.startsWith(".") ? resolve(dirname(absolute), specifier.split("?")[0]!) : ""; - if (asset && existsSync(asset)) { visit(relative(root, asset), typeOnly, sourceOnly); return; } + if (asset && existsSync(asset)) { visit(relative(root, asset), typeOnly); return; } unresolved.add(`Unresolved import ${normalized}: ${specifier}`); return; } const target = inside(root, result.resolvedFileName); if (target?.startsWith("node_modules/") || result.isExternalLibraryImport && !specifier.startsWith("@schlessera/")) return; if (!target) { unresolved.add(`External workspace input ${normalized}: ${specifier}`); return; } - visit(target, typeOnly, sourceOnly); + visit(target, typeOnly); }; const lexicalScope = (node: ts.Node): string => { const names: string[] = []; @@ -200,20 +164,14 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ } return matches; }; - const boundAlias = (node: ts.Identifier): boolean => { - if(themeBinding?.owner!==normalized)return false; - const contexts=themeBinding.aliases.get(node.text);if(!contexts)return false; - return [node.parent,node.parent?.parent].some(parent=>parent&&contexts.has(parent.getText(ast))); - }; - const walk = (node: ts.Node, dormant = sourceOnly) => { - if (!dormant && ts.isPropertyAccessExpression(node) && /^(?:process|Bun)\.env$/.test(node.getText(ast)) && + const walk = (node: ts.Node) => { + if (ts.isPropertyAccessExpression(node) && /^(?:process|Bun)\.env$/.test(node.getText(ast)) && !((ts.isPropertyAccessExpression(node.parent) || ts.isElementAccessExpression(node.parent)) && node.parent.expression === node)) unresolved.add(`Git-dependent execution input: ${normalized}`); - if (!dormant && (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && /^(?:process|Bun)\.env$/.test(node.expression.getText(ast))) { + if ((ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && /^(?:process|Bun)\.env$/.test(node.expression.getText(ast))) { const name = ts.isPropertyAccessExpression(node) ? node.name.text : node.argumentExpression && ts.isStringLiteral(node.argumentExpression) ? node.argumentExpression.text : undefined; if (!name || name.startsWith("GITHUB_")) unresolved.add(`Git-dependent execution input: ${normalized}`); } - if (ts.isArrowFunction(node) && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) && inactive.get(normalized)?.has(node.parent.name.text)) dormant = true; if (ts.isCallExpression(node) || ts.isNewExpression(node)) { const expression = node.getText(ast); const matching = declarationAt(node); @@ -223,33 +181,18 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ sites.add(key); } } - if (!dormant && ts.isIdentifier(node) && aliases.has(node.text) && readOperations.has(aliases.get(node.text)!)) { + if (ts.isIdentifier(node) && aliases.has(node.text) && readOperations.has(aliases.get(node.text)!)) { const parent = node.parent; - if (!ts.isImportSpecifier(parent) && !(ts.isCallExpression(parent) && parent.expression === node) && !boundAlias(node)) unresolved.add(`Unsupported input alias ${normalized}: ${node.text}`); + if (!ts.isImportSpecifier(parent) && !(ts.isCallExpression(parent) && parent.expression === node)) unresolved.add(`Unsupported input alias ${normalized}: ${node.text}`); } - if (!dormant && ts.isIdentifier(node) && namespaces.has(node.text)) { + if (ts.isIdentifier(node) && namespaces.has(node.text)) { const parent = node.parent; if (!ts.isImportClause(parent) && !ts.isNamespaceImport(parent) && !(ts.isPropertyAccessExpression(parent) && parent.expression === node) && !(ts.isElementAccessExpression(parent) && parent.expression === node)) unresolved.add(`Unsupported input namespace alias ${normalized}: ${node.text}`); } - if (!dormant && ts.isIdentifier(node) && node.text === "require" && !(ts.isCallExpression(node.parent) && node.parent.expression === node) && !boundAlias(node)) unresolved.add(`Unsupported require alias ${normalized}`); + if (ts.isIdentifier(node) && node.text === "require" && !(ts.isCallExpression(node.parent) && node.parent.expression === node)) unresolved.add(`Unsupported require alias ${normalized}`); if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) edge(node.moduleSpecifier.text, ts.isImportDeclaration(node) ? node.importClause?.isTypeOnly === true : node.isTypeOnly); - if (dormant && (ts.isCallExpression(node) || ts.isNewExpression(node))) { - for (const declaration of inputDeclarations(node)) { - uses.add(inputKey(declaration)); - for (const target of declaration.targets) visit(target, false, true); - } - if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && - node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0]!)) { - // Imported modules execute only when the inactive callback executes. - const specifier = node.arguments[0]!.text; - const result = resolveRuntimeModule(specifier, absolute, options); - if (builtins.has(specifier) || specifier.startsWith("bun:")) { /* Runtime-provided builtin; already in runner identity. */ } - else if (result && !result.isExternalLibraryImport) visit(relative(root, result.resolvedFileName), false, true); - else if (!result) unresolved.add(`Unresolved dormant import ${normalized}: ${specifier}`); - } - } - if (!dormant && ts.isCallExpression(node)) { + if (ts.isCallExpression(node)) { const originalCallee = node.expression.getText(ast), callee = aliases.get(originalCallee) ?? originalCallee, expression = node.getText(ast); if (node.expression.kind === ts.SyntaxKind.ImportKeyword) { if (node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0]!)) edge(node.arguments[0]!.text); @@ -262,49 +205,26 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ } else if (aliases.has(originalCallee) && readOperations.has(callee) || [...namespaces].some(name => originalCallee.startsWith(name + ".") && readOperations.has(originalCallee.split(".").at(-1)!)) || /^(?:require|Bun\.(?:file|spawn|spawnSync|build|resolveSync)|import\.meta\.glob)$/.test(originalCallee) || ts.isElementAccessExpression(node.expression) || /\.(?:fulfill|setContent)$/.test(originalCallee)) { - const path = node.arguments[0]; - const literalRead = filesystemAliases.has(originalCallee) && !shadowedBindings.has(originalCallee) && callee === "readFile" && - node.arguments.length === 2 && ts.isStringLiteral(node.arguments[1]!) && node.arguments[1]!.text === "utf8" && - path && ts.isCallExpression(path) && ts.isIdentifier(path.expression) && pathResolveAliases.has(path.expression.text) && - path.arguments.length === 1 && ts.isStringLiteral(path.arguments[0]!) ? path.arguments[0]!.text : undefined; - const generated = literalRead ? generatedCssReadInputs(root, normalized, literalRead) : undefined; - const locked = literalRead ? lockedBrowserAsset(root, normalized, literalRead) : undefined; - const literalPayload = /\.(?:fulfill|setContent)$/.test(originalCallee) && sourceBrowserPayload(root, normalized, expression); - const boundRuntime = runtimeBindings.get(normalized)?.get(expression); - const boundDispatch = dispatchBindings.get(normalized)?.has(expression) === true; - const boundDocument = documentBindings.get(normalized)?.get(expression); - if(boundDocument){for(const target of boundDocument.runtime)visit(target);for(const target of boundDocument.bytes)visit(target,true);} - const generatedTheme = themeBinding?.owner===normalized && themeBinding.read===expression ? themeBinding : undefined; - if(generatedTheme){for(const target of generatedTheme.css)visit(target);for(const target of generatedTheme.bytes)visit(target,true);external.set(`${generatedTheme.compiler.package}/${generatedTheme.compiler.asset}`,generatedTheme.compiler);} - if (boundRuntime) for (const target of boundRuntime) visit(target, true); - if (locked) { - external.set(`${locked.package}/${locked.asset}`, locked); - visit("package.json", true); visit("bun.lock", true); - } - if (generated) { - visit(generated.entry); - for (const producer of generated.producer) visit(producer, true); - } const matching = inputDeclarations(node); if (matching.some(declaration => declaration.observation && !kernelObservation(node, declaration))) unresolved.add(`Invalid runner observation ${normalized}: ${expression}`); - if (!matching.length && !generated && !locked && !literalPayload && !boundRuntime && !boundDispatch && !generatedTheme && !boundDocument) unresolved.add(`Undeclared input ${normalized}: ${expression}`); + if (!matching.length) unresolved.add(`Undeclared input ${normalized}: ${expression}`); else for (const declaration of matching) { uses.add(inputKey(declaration)); for (const target of declaration.targets) visit(target); } } } - if (!dormant && ts.isNewExpression(node) && /^(?:Worker|SharedWorker|Bun\.Glob)$/.test(node.expression.getText(ast))) { + if (ts.isNewExpression(node) && /^(?:Worker|SharedWorker|Bun\.Glob)$/.test(node.expression.getText(ast))) { const expression = node.getText(ast), declaration = declared.get(normalized)?.get(expression); if (declaration?.observation) unresolved.add(`Invalid runner observation ${normalized}: ${expression}`); if (!declaration) unresolved.add(`Undeclared constructed input ${normalized}: ${expression}`); else { uses.add(expression); for (const target of declaration.targets) visit(target); } } - ts.forEachChild(node, child => walk(child, dormant)); + ts.forEachChild(node, walk); }; walk(ast); for (const [key, declaration] of declared.get(normalized) ?? []) if (!uses.has(key)) unresolved.add(`Stale declaration ${normalized}: ${declaration.expression}`); }; - for (const file of [...entrypoints,...executionRoots]) visit(file); + for (const file of entrypoints) visit(file); for (const owner of declared.keys()) if (!files.has(owner)) unresolved.add(`Unused declaration owner: ${owner}`); - return { files: [...files].sort(), directories: [...directories].sort(), ...(external.size ? { external: [...external.values()].sort((a,b) => `${a.package}/${a.asset}`.localeCompare(`${b.package}/${b.asset}`)) } : {}), unresolved: [...unresolved].sort() }; + return { files: [...files].sort(), directories: [...directories].sort(), unresolved: [...unresolved].sort() }; } export function closureSelects(changed: readonly string[], closure: InputClosure, broad: boolean): boolean { const inputs = new Set(closure.files); diff --git a/scripts/browser-screenshot-inputs.ts b/scripts/browser-screenshot-inputs.ts deleted file mode 100644 index 215ae8506b..0000000000 --- a/scripts/browser-screenshot-inputs.ts +++ /dev/null @@ -1,74 +0,0 @@ -/** Vitest's pinned default reference-image ownership over immutable tracked inputs. */ -import ts from "typescript"; -import { readFileSync } from "node:fs"; -import { basename, dirname, join } from "node:path"; -import { lockedPackageAsset } from "./locked-browser-assets"; -import type { InputClosure } from "./browser-input-closure"; -import type { Spec } from "./proof-inputs"; - -// Installed @vitest/browser 4.1.11, resolveOptions/defaultOptions: the default -// resolver joins the test directory, __screenshots__, test basename and a -// sanitized image basename. Custom resolvers/directories are unsupported. -const frameworkHash = "0453902c16246ee96fd57727fe438c9a8383d49f7b908f242501aa8faf193455"; -const pathOptions = new Set(["resolveScreenshotPath", "screenshotDirectory"]); -const ordinaryOptions = new Set(["comparatorName", "comparatorOptions", "screenshotOptions", "timeout", "strict"]); -const key = (node: ts.PropertyName) => ts.isIdentifier(node) || ts.isStringLiteral(node) ? node.text : undefined; - -/** This is called on a Git materialization, never current dist or untracked files. */ -export function includeBrowserScreenshots(root: string, closure: InputClosure, selected: readonly Spec[], tracked: ReadonlySet): InputClosure { - let calls = 0; - for (const file of closure.files.filter(file => /\.[cm]?[jt]sx?$/.test(file))) { - const source = ts.createSourceFile(file, readFileSync(join(root, file), "utf8"), ts.ScriptTarget.Latest, true); - const constants = new Map(); - for (const statement of source.statements) if (ts.isVariableStatement(statement) && statement.declarationList.flags & ts.NodeFlags.Const) - for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name)) constants.set(declaration.name.text, declaration); - const literal = (node: ts.Expression, top: boolean, seen = new Set()): boolean => { - if (ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isParenthesizedExpression(node)) return literal(node.expression, top, seen); - if (ts.isIdentifier(node)) { - const declaration = constants.get(node.text); - if (!declaration?.initializer || seen.has(node.text)) return false; - let escaped = false; - const references = (value: ts.Node) => { - if (ts.isIdentifier(value) && value.text === node.text && value !== declaration.name && - !(ts.isCallExpression(value.parent) && value.parent.arguments[1] === value && ts.isPropertyAccessExpression(value.parent.expression) && value.parent.expression.name.text === "toMatchScreenshot")) escaped = true; - ts.forEachChild(value, references); - }; - references(source); - return !escaped && literal(declaration.initializer, top, new Set([...seen, node.text])); - } - if (ts.isObjectLiteralExpression(node)) return node.properties.every(property => ts.isPropertyAssignment(property) && - key(property.name) !== undefined && !pathOptions.has(key(property.name)!) && (!top || ordinaryOptions.has(key(property.name)!)) && literal(property.initializer, false, seen)); - if (top) return false; - if (ts.isArrayLiteralExpression(node)) return node.elements.every(value => !ts.isSpreadElement(value) && literal(value, false, seen)); - return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node) || [ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword, ts.SyntaxKind.NullKeyword].includes(node.kind); - }; - const visit = (node: ts.Node) => { - if (ts.isTypeNode(node)) return; - if (ts.isPropertyAssignment(node) && pathOptions.has(key(node.name) ?? "") || - ts.isElementAccessExpression(node) && node.argumentExpression && ts.isStringLiteral(node.argumentExpression) && pathOptions.has(node.argumentExpression.text)) - throw new Error(`Unsupported screenshot path override: ${file}`); - if (ts.isPropertyAccessExpression(node) && node.name.text === "toMatchScreenshot") { - const call = node.parent; - if (!ts.isCallExpression(call) || call.expression !== node || call.arguments.length > 2 || call.arguments[1] && !literal(call.arguments[1], true)) - throw new Error(`Unsupported screenshot matcher options or alias: ${file}`); - calls++; - } - ts.forEachChild(node, visit); - }; - visit(source); - } - if (!calls) return closure; - const framework = lockedPackageAsset(root, "@vitest/browser", "dist/index.js"); - if (!framework || framework.version !== "4.1.11" || framework.sha256 !== frameworkHash) throw new Error("Unsupported installed screenshot resolver"); - const directories = new Set(closure.directories), files = new Set(closure.files); - for (const spec of selected) { - const directory = `${dirname(spec.file)}/__screenshots__/${basename(spec.file)}`; - if (tracked.has(directory) || tracked.has(`${dirname(spec.file)}/__screenshots__`)) throw new Error("Screenshot directory is a tracked non-directory input"); - for (const path of tracked) if (path.startsWith(directory + "/")) { - files.add(path); directories.add(directory); - } - } - // Git path/mode/blob validation remains mandatory in the inclusion caller; - // symlinks and missing eligible files can never become passing ownership. - return { ...closure, files: [...files].sort(), directories: [...directories].sort(), external: [...(closure.external ?? []), framework] }; -} diff --git a/scripts/browser-worker-audit.json b/scripts/browser-worker-audit.json deleted file mode 100644 index a255bf32ad..0000000000 --- a/scripts/browser-worker-audit.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "version": 2, - "category": "browser", - "identity": "795abd5839096c4c451db7ff42ea5264b3ad7652439f8c927858505708a597b5", - "enforcement": "Earliest selected-project setup; afterEach plus outer aroundAll finally covers returned and file-fixture cleanup. Fresh registered job success remains mandatory.", - "sourceAudit": { - "version": 1, - "base": "b03e6550688723f644b5efc4b97d243c832963a0", - "selected": 309, - "files": 2295, - "scope": "Complete 309-pair selected source/import/configuration/command inventory, including the separate network-disabled read-only-root native Docker producer. All six source families and preparation inputs, copied external installation membership/bytes/modes/internal aliases, actual immutable manifest reference and captured private Bun bytes join current identity. The producer mounts only private source/install/Bun and initially empty owned output; HOME/tmp/shared-memory are fresh container filesystems. Host checkout/state mount counterfactuals fail the named absent-data assertions. Imported initialization and shared helpers remain active inside this finite filesystem boundary. Fresh per-launch output session, captured validated artifact bytes, artifact hashes, exact native entry/configuration/core-dispatch guards and original generated SVG/reference consumers remain enforced. Source or installation drift makes the binding unavailable; runtime drift changes its fingerprint. All resource/Worker guards, complete fresh same-PR two-shard proof and whole-workflow success remain mandatory. Metadata is not passing proof; historical observations retain their scope and source. Reviewed exact source deltas include bounded compilation, restricted IPC, private-parent masking, observational build receipts and repeat-identity observation, and the delivered conversation modules. The complete selected closure has 2,295 files. The two added callout project/file pairs use the exact reviewed diagramCapture caller and producers. Directory and external identities remain unchanged. The complete 859-input diagram source identity is qualified by actual offline SVG/PNG/PDF execution on the same private hosted-mode installation and runtime. The original enforced PDF Worker exception remains the sole unresolved input. The hosted installation mode identity is qualified by actual offline SVG/PNG/PDF execution on an independent normalized copy, not by accepting drift. This metadata update still requires fresh complete selected browser execution and whole-workflow success before any retention. The latest reviewed selected-source changes are per-case callout ownership/drain and separated proof scenarios, plus the ordinary safe builder that refuses unqualified persistent output reuse. The observational receipt and repeat observer remain inputs; these two source changes leave directory, external and native identities unchanged. No new native execution or whole-workflow result is inferred from this projection. Retired 2026-11-16 (#4105): the native identity is no longer recorded or bound, and the browser domain always runs fresh; the qualification statements above are historical." - }, - "historicalDiagnostic": { - "base": "b0b4340cd", - "observed": 297, - "workerAttempts": 0, - "passed": 8808, - "skipped": 10, - "scope": "setup through afterAll; returned cleanup gap retained", - "logSha256": "da33e71a8dc26e89f5b5a81762261a62828a660d3bb67968f853d6a8c49de88e", - "observerSha256": "5d1760000e759cca123066c3b38b8d23320316e6878896aec4031cd2b2e46303" - }, - "guardedFreshProofRequired": true, - "historicalTargetedDiagnostic": { - "projects": [ - "diagrams-chromium", - "diagrams-webkit" - ], - "observed": 2, - "passed": 18, - "workerAttempts": 0, - "logSha256": "282640cec719b3e5940018963f64b383a3eee13c4bc03a69d711fe66965b7fcd", - "scope": "Both added project pairs passed all 18 original cases with zero Worker attempts on the audited source at that checkpoint, after the intended resource mutation failed in Chromium and WebKit and originals were restored. This remains two project pairs, not a whole-299-domain observation.", - "source": "a0f007ae0f8cbe224c101179a1955044c3d241c3" - }, - "targetedDiagnostic": { - "projects": [ - "diagrams-chromium", - "diagrams-webkit" - ], - "observed": 8, - "passed": 102, - "workerAttempts": 0, - "logSha256": "f23e7fd21eb7a995371825f948b6edb13007eb4949c1ca96da0a62b53f5e4baf", - "source": "aab3d5556ad6332eeaae7dceb84dae68806ae48f", - "scope": "All four diagram specs in both engines passed 102 unchanged cases under the permanent returned-cleanup Worker boundary and zero-request replay guards, with registry-verified pristine Vitest packages. Source includes the exact viewport restoration from #2253. The intended new-family resource mutation failed in both engines; originals restored. This is eight selected file/project pairs, not a complete 305-pair observation or hosted passing proof." - } -} diff --git a/scripts/browser-worker-audit.ts b/scripts/browser-worker-audit.ts deleted file mode 100644 index 855c5bd2f8..0000000000 --- a/scripts/browser-worker-audit.ts +++ /dev/null @@ -1,74 +0,0 @@ -/** Capability audit for one measured selected domain; never a proof receipt. */ -import {createHash} from "node:crypto"; -import {lstatSync,readFileSync,realpathSync} from "node:fs"; -import {isAbsolute,resolve,relative} from "node:path"; -import type {InputClosure} from "./browser-input-closure"; -import type {Spec} from "./proof-inputs"; -export const workerAuditFile="scripts/browser-worker-audit.json"; -export const pdfWorkerInput='Undeclared constructed input packages/ui-react/src/lib/pdf.ts: new Worker(url, { type: "module" })'; -const guards=["packages/ui-kit/tests/visual/worker-boundary-setup.ts","scripts/browser-worker-boundary.ts"]; -const enforcement:Record={ - "packages/ui-kit/vitest.config.ts":"89ea7a414a191a5624fce2dff8e0434aac5474c4c5b74d13499848cd17e2b257", - "scripts/browser-worker-boundary.ts":"fe7b63742370e3a6f2d8f99a77d23ce538d905744ad34d34e99ce342ff62d31b", - "packages/ui-kit/tests/visual/worker-boundary-setup.ts":"80ba88b24fc1f0269d0f8a6b58520d715375b8af21ca636112f3294ffd7ad60f" -}; -function workerAuditMaterial(root:string,closure:InputClosure,selected:readonly Spec[],diagnosticOnly=false){ - try{ - if(!selected.length||selected.some(spec=>["ui-react-layout","ui-react-endurance"].includes(spec.project))||(!diagnosticOnly&&closure.unresolved.some(input=>input!==pdfWorkerInput))||!guards.every(file=>closure.files.includes(file))||closure.files.includes(workerAuditFile))return; - const files=closure.files.map(file=>{ - const absolute=resolve(root,file),path=relative(root,absolute).replaceAll("\\","/"); - if(path!==file||isAbsolute(path)||path.startsWith("../")||realpathSync(absolute)!==absolute)throw new Error("Unowned worker audit input"); - const stat=lstatSync(absolute); - if(stat.isDirectory()&&closure.directories?.includes(file))return [file,"directory"]; - if(!stat.isFile()||stat.isSymbolicLink())throw new Error("Nonregular worker audit input"); - return [file,stat.mode&0o777,createHash("sha256").update(readFileSync(absolute)).digest("hex")]; - }).sort((a,b)=>String(a[0]).localeCompare(String(b[0]))); - const inventory=selected.map(({file,project})=>({file,project})).sort((a,b)=>a.project.localeCompare(b.project)||a.file.localeCompare(b.file)); - return {version:1,files,directories:[...(closure.directories??[])].sort(),external:closure.external??[],inventory}; - }catch{return;} -} -export function workerAuditIdentity(root:string,closure:InputClosure,selected:readonly Spec[]):string|undefined{ - const material=workerAuditMaterial(root,closure,selected); - return material?createHash("sha256").update(JSON.stringify(material)).digest("hex"):undefined; -} -/** Diagnostics contain only the same bounded repository-relative identities used - * by admission. They never authorize execution or disclose source contents. */ -export function inspectWorkerAudit(root:string,closure:InputClosure,selected:readonly Spec[]){ - const material=workerAuditMaterial(root,closure,selected); - const actualIdentity=material?createHash("sha256").update(JSON.stringify(material)).digest("hex"):undefined; - const diagnosticMaterial=material??workerAuditMaterial(root,closure,selected,true); - let audit:any; - try{ - const path=resolve(root,workerAuditFile); - if(realpathSync(path)===path&&lstatSync(path).isFile())audit=JSON.parse(readFileSync(path,"utf8")); - }catch{ /* Missing or malformed evidence cannot qualify the domain. */ } - const expectedIdentity=typeof audit?.identity==="string"&&/^[a-f0-9]{64}$/.test(audit.identity)?audit.identity:undefined; - const enforcementValid=diagnosticMaterial&&Object.entries(enforcement).every(([path,hash])=>diagnosticMaterial.files.some(file=>file[0]===path&&file[2]===hash)); - const qualified=Boolean(actualIdentity&&enforcementValid&&audit?.version===2&&audit.category==="browser"&&expectedIdentity===actualIdentity&&audit.guardedFreshProofRequired===true&& - audit.sourceAudit?.version===1&&audit.sourceAudit?.selected===selected.length&&audit.sourceAudit?.files===closure.files.length&& - Number.isSafeInteger(audit.historicalDiagnostic?.observed)&&audit.historicalDiagnostic.observed>0&&audit.historicalDiagnostic.workerAttempts===0); - // Unknowns never gain admission material. A separate bounded inspection may - // still report public path/mode/blob identities without granting ownership. - const labels=closure.unresolved.slice(0,64).map(input=>{ - const prefixes:[[string,string],...Array<[string,string]>]=[["Undeclared constructed input ","undeclared-constructed-input"],["Undeclared input ","undeclared-input"],["Unresolved import ","unresolved-import"],["Unsupported input alias ","unsupported-input-alias"]]; - const prefix=prefixes.find(([text])=>input.startsWith(text)); - const owner=prefix?input.slice(prefix[0].length).split(":")[0]:undefined; - return{code:prefix?.[1]??"unsupported-input",...(owner&&owner.length<256&&/^[A-Za-z0-9_./@-]+$/.test(owner)&&closure.files.includes(owner)?{owner}:{})}; - }); - const diagnostic={version:1,expectedIdentity,actualIdentity,enforcementValid:Boolean(enforcementValid),admissionSupported:Boolean(material),selected:selected.length,files:closure.files.length,unresolvedCount:closure.unresolved.length,unresolved:labels,material:diagnosticMaterial}; - if(JSON.stringify(diagnostic).length>768*1024)return{qualified:false,diagnostic:{version:1,expectedIdentity,actualIdentity,reason:"bounded manifest exceeded"}}; - return{qualified,diagnostic}; -} -export class WorkerAuditError extends Error{ - constructor(readonly diagnostic:ReturnType["diagnostic"]){super("Unresolved immutable browser inputs require fresh proof: unvalidated selected Worker capability audit");} -} -export function logWorkerAuditDiagnostic(error:unknown){ - if(!(error instanceof WorkerAuditError))return; - const {material,...header}=error.diagnostic as {material?:unknown;[key:string]:unknown}; - console.log("BRAIN_WORKER_AUDIT_DIAGNOSTIC "+JSON.stringify(header)); - const text=JSON.stringify(material??null); - for(let offset=0;offset problems.push(`${file}: ${message}`); if (/\bsecrets\.|\bpull_request_target\b|\bworkflow_run\b/.test(text)) fail("CI must not expose secrets or privileged triggers"); - const permissions = file === "ci.yml" ? { contents: "read", actions: "read", checks: "read" } : { contents: "read" }; + const permissions = file === "ci.yml" ? { contents: "read", actions: "read" } : { contents: "read" }; if (JSON.stringify(workflow.permissions) !== JSON.stringify(permissions)) fail("workflow permissions must be the specified read-only contents/actions scope"); const expectedTriggers = file === "ci.yml" ? ["pull_request", "push", "schedule", "workflow_dispatch"] : ["pull_request"]; if (JSON.stringify(Object.keys(workflow.on ?? {}).sort()) !== JSON.stringify(expectedTriggers)) fail("unexpected contribution triggers"); - const expectedJobs = file === "ci.yml" ? ["browser", "captures", "changeset", "endurance", "layout", "pack", "proof", "runtime", "runtime_host", "unit", "verify"] : ["contract"]; + const expectedJobs = file === "ci.yml" ? ["browser", "captures", "changeset", "determinism", "endurance", "layout", "pack", "proof", "runtime", "runtime_host", "unit", "verify"] : ["contract"]; if (JSON.stringify(Object.keys(workflow.jobs ?? {}).sort()) !== JSON.stringify(expectedJobs)) fail("missing or unexpected CI jobs"); for (const [name, job] of Object.entries(workflow.jobs ?? {})) { if (job["runs-on"] !== "ubuntu-24.04") fail(`${name}: unmapped GitHub-hosted runner`); @@ -53,14 +53,15 @@ export function workflowProblems(text: string, file: string): string[] { } } if (file === "ci.yml") { - const names = ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"]; + const names = ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism"]; for (const name of names) { 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'` : ""); + // The planner's selection alone decides: no second output may skip a selected category (#4107). + const selection = `needs.changeset.outputs.${name} == 'true'`; // 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`); + if (job?.if !== `\${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && ${selection} }}`) fail(`${name}: proof must run on its explicit planner selection alone`); } const verify = workflow.jobs?.verify; const verifySteps = verify?.steps ?? []; @@ -79,9 +80,10 @@ export function workflowProblems(text: string, file: string): string[] { verifySteps.indexOf(summary) <= verifySteps.findIndex(s => s.id === "verify_proof")) fail("verify: always summary must separate raw install, planning and proof outcomes and receipts"); // Network prerequisites cannot spend proof capacity; measured basis: docs/decisions/ci-utility.md (#2658). - for (const [name, proofMinutes] of [["unit", 30], ["runtime", 15], ["runtime_host", 15]] as const) { + // Repeated changed tests need the unit job's prerequisites: they may drive real Chrome (#4109). + for (const [name, proofMinutes] of [["unit", 30], ["runtime", 15], ["runtime_host", 15], ["determinism", 40]] as const) { const job = workflow.jobs?.[name]; - const setup = job?.steps?.find(step => step.run === `bash scripts/ci-runtime-setup.sh${name === "unit" ? "" : " --native"}`); + const setup = job?.steps?.find(step => step.run === `bash scripts/ci-runtime-setup.sh${name === "unit" || name === "determinism" ? "" : " --native"}`); const command = `bun scripts/ci-proof.ts ${name}`; const proof = job?.steps?.find(step => step.run === command || step.run?.startsWith(`${command} `)); if (setup?.["timeout-minutes"] !== 12) fail(`${name}: environment setup must have its separate 12-minute limit`); @@ -89,7 +91,7 @@ export function workflowProblems(text: string, file: string): string[] { const limit = job?.["timeout-minutes"]; if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 12 + proofMinutes + 3) fail(`${name}: job limit must cover setup, proof and 3 minutes of other steps`); } - // Matrices, retention and refresh share one shard table; a drifted matrix would strand a partition. + // Matrices, the merge path and the cost refresh share one shard table; a drifted matrix would strand a partition. for (const domain of Object.keys(PROOF_SHARDS) as ShardedDomain[]) { const job = workflow.jobs?.[domain] as any; if (JSON.stringify(job?.strategy?.matrix?.shard) !== JSON.stringify(shardNumbers(domain)) || @@ -108,11 +110,10 @@ export function workflowProblems(text: string, file: string): string[] { if (proof?.name !== "${{ github.event_name != 'pull_request' && 'integrated or exhaustive proof' || github.event.pull_request.draft && 'draft gates' || 'proof' }}") fail("proof: draft, manual or main runs must not impersonate candidate confirmation"); if (JSON.stringify(proof?.needs) !== JSON.stringify(["changeset", ...names])) fail("proof: aggregate must observe every selected category"); if (proof?.if !== "${{ always() && !cancelled() }}") fail("proof: aggregate must observe failures/skips and reject cancellation"); - for (const category of ["unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"]) { + for (const category of ["unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism"]) { if (!workflow.jobs?.[category]?.steps?.some(step => step.run === `bun scripts/ci-proof.ts ${category}` || step.run?.startsWith(`bun scripts/ci-proof.ts ${category} `))) fail(`${category}: complete proof command is missing`); } if (!proof?.steps?.some(step => step.run === "bun scripts/ci-proof.ts aggregate")) fail("proof: executable aggregate is missing"); - if (!workflow.jobs?.changeset?.steps?.some(step => step.run === "bun scripts/proof-reuse.ts")) fail("metadata: immutable retention validation is missing"); const metadata = workflow.jobs?.changeset?.steps ?? []; const admission = metadata.findIndex(step => step.run === "bun scripts/candidate-proof.ts"); const planning = metadata.findIndex(step => step.run === "bun scripts/ci-plan.ts"); @@ -205,7 +206,7 @@ export function heavyFeedbackWorkflowProblems(text: string, ciText: string): str try { rendered = renderHeavyFeedbackWorkflow(ciText); } catch (error) { fail(`cannot derive from ci.yml: ${String(error)}`); } 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(workflow.permissions) !== JSON.stringify({ contents: "read", actions: "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"); diff --git a/scripts/check-pr.ts b/scripts/check-pr.ts index 12685959ba..3d98b97d69 100644 --- a/scripts/check-pr.ts +++ b/scripts/check-pr.ts @@ -68,6 +68,15 @@ export function localChecks(plan: CheckPlan, full = false, mergeBase?: string, i return checks; } +/** + * The repeated-run command for a plan that changes Bun test files (#4109). + * `check:pr` names it and never runs it: it occupies every CPU of a shared + * host, so the hosted `determinism` job is where it runs. + */ +export function determinismCommand(plan: CheckPlan, base: string): string | undefined { + return plan.determinism?.length ? `bun scripts/test-determinism.ts --base ${base}` : undefined; +} + class SandboxSetupTimeout extends Error {} /** The fastest of three sandbox setup probes must take less than this. */ @@ -266,7 +275,9 @@ if (import.meta.main) { const importGraphFeedback = full ? "skipped: --full/--all retain their existing suites" : importGraph ? "enabled with --import-graph" : "skipped by default; enable with --import-graph"; console.log(JSON.stringify({ ...plan, commands: plannedCommands.map(command => command.name), commandDetails: plannedCommands, - importGraphFeedback, packedConsumerChecks: full && plan.pack, hostedProofRequired: plan.local }, null, 2)); + importGraphFeedback, packedConsumerChecks: full && plan.pack, hostedProofRequired: plan.local, + ...(determinismCommand(plan, base) ? { determinismCommand: determinismCommand(plan, base), + determinismNote: "not run locally: it occupies every CPU; the hosted determinism job repeats these files under load" } : {}) }, null, 2)); if (print) process.exit(0); const chromeStep: Command = { name: "first real Chrome launch and render", argv: [] }; const steps: PreflightStep[] = [...commands.slice(0, 3).map(command => [command]), [contributionChangeset], diff --git a/scripts/check-receipt.ts b/scripts/check-receipt.ts index 461419c614..c2a4cb4af0 100644 --- a/scripts/check-receipt.ts +++ b/scripts/check-receipt.ts @@ -98,12 +98,12 @@ export function receiptFromBody(body: string | null | undefined): CheckReceipt | return parseReceipt(parsed); } -/** Hosted categories the exact-head selected proof ran successfully (or validly retained). */ -export function coveredCategories(selected: { selections: Record; results: Record; retained: string[] }): Set { +/** Hosted categories the exact-head selected proof ran successfully. */ +export function coveredCategories(selected: { selections: Record; results: Record }): Set { const covered = new Set(["changeset"]); for (const category of CATEGORIES) { if (category === "changeset" || selected.selections[category] !== "true") continue; - if (selected.results[category] === "success" || selected.retained.includes(category)) covered.add(category); + if (selected.results[category] === "success") covered.add(category); } return covered; } diff --git a/scripts/check-unused-exports.ts b/scripts/check-unused-exports.ts index 9a8583ddf2..23cd5ceea5 100644 --- a/scripts/check-unused-exports.ts +++ b/scripts/check-unused-exports.ts @@ -71,7 +71,7 @@ export const ALLOWLIST: AllowlistEntry[] = [ { file: "packages/ui-server/src/bin/brain-ui-cron.ts", name: "USAGE", reason: "tests/release-manifest.test.ts reads the subcommand list from the `export const USAGE` source text" }, ...["listSpecFromInput", "formSpecFromInput", "rankSpecFromInput"].map(name => ({ file: "packages/ui-react/src/hooks/websocket-handlers/chat.ts", name, - reason: "scripts/source-browser-dispatch.ts pins this file's sha256; an edit needs a reviewed re-pin there", + reason: "kept while a retired source pin held this file's hash (#4107); #4119 drops the keyword", })), ]; diff --git a/scripts/ci-plan.ts b/scripts/ci-plan.ts index f5d7e62c48..d170699c9a 100644 --- a/scripts/ci-plan.ts +++ b/scripts/ci-plan.ts @@ -26,7 +26,6 @@ export const FAST_TESTS: Readonly> = { "tests/diagram-export-installation.test.ts", // 0.03s finite installed input controls. "tests/local-checks.test.ts", "tests/hosted-proof.test.ts", "tests/browser-shards.test.ts", "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/heavy-feedback.test.ts", "tests/release-manifest.test.ts", "tests/ci-pack.test.ts", "tests/lockfile.test.ts", @@ -79,10 +78,6 @@ export const FAST_TESTS: Readonly> = { * Keep the input scopes beside their invariant, including non-Markdown inputs. */ export const FILE_INPUT_TESTS: Readonly> = { - // The fixture copies these sources as bytes, so import discovery misses edits. - "tests/source-browser-dispatch.test.ts": [ - /^packages\/ui-react\/src\/(?:connection\.ts|hooks\/use-websocket\.ts|hooks\/websocket-handlers\/[^/]+\.ts|lib\/stats\/context-text\.ts)$/, - ], // Links, path kinds and short citations can resolve to arbitrary repo targets. // New/deleted targets anywhere can break a doc without changing its Markdown. "tests/docs-paths.test.ts": [/.+/], @@ -132,8 +127,6 @@ export const FILE_INPUT_TESTS: Readonly> = { "tests/candidate-admission.test.ts": [/^\.github\/workflows\/ci\.yml$/], "tests/project-sync-main.test.ts": [/^\.github\/workflows\/project-sync\.yml$/], "tests/ci-timings.test.ts": [/^\.github\/workflows\/ci-timings\.yml$/], - "tests/generated-build-inputs.test.ts": [/^\.github\/workflows\/ci\.yml$/], - "tests/generated-theme-inputs.test.ts": [/^\.github\/workflows\/ci\.yml$/], }; export interface CheckPlan { @@ -150,6 +143,8 @@ export interface CheckPlan { 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; + /** Bun test files a pull request adds or modifies; each repeats under CPU load before merge (#4109). */ + determinism?: string[]; } export function workspaces(root: string): Workspace[] { @@ -308,7 +303,22 @@ export function planChecks(changed: readonly string[], packages: readonly Worksp // Explicit roots identify a real harness; two-argument synthetic workspace diagnostics stay conservative. const explicitRoot = arguments.length >= 3; const plan = planBeforeBrowserClosures(changed, packages, root, enableConsumerSelection, explicitRoot); - return explicitRoot && !plan.global ? selectBrowserClosures(plan, discoverBrowserClosures(root)) : plan; + const selected = explicitRoot && !plan.global ? selectBrowserClosures(plan, discoverBrowserClosures(root)) : plan; + // Main pushes and their red-main replans pass enableConsumerSelection=false: repetition is pre-merge proof. + const determinism = explicitRoot && enableConsumerSelection ? determinismTests(root, changed) : []; + return determinism.length ? { ...selected, determinism } : selected; +} + +/** + * The Bun test files among `changed` that exist in this checkout: what a + * change adds or modifies, never what it deletes (#4109). Same roots, name + * suffixes and directory exclusions as `discoverTests` (scripts/test-shards.ts). + */ +export function determinismTests(root: string, changed: readonly string[]): string[] { + return [...new Set(changed)].filter(path => /^(?:packages|tests)\//.test(path) && + /(?:\.test|\.spec|_test|_spec)\.(?:[cm]?[jt]s|[jt]sx)$/i.test(basename(path)) && + !path.split("/").slice(0, -1).some(part => part.startsWith(".") || part.toLowerCase() === "node_modules") && + lstatSync(join(root, path), { throwIfNoEntry: false })?.isFile() === true).sort(); } /** @@ -425,11 +435,14 @@ export function proofSelections(plan: CheckPlan, draft = false): Record 0; + return { ...Object.fromEntries(Object.entries({ verify: plan.typecheck || ((feedback || !plan.local.fullTests) && plan.tests.length > 0), pack: !feedback && plan.pack, unit: !feedback && plan.local.fullTests, browser: !feedback && plan.local.browser, layout: !feedback && plan.local.layout, captures: !feedback && plan.local.captures, runtime: !feedback && plan.local.runtime, runtime_host: !feedback && plan.local.runtime, endurance: !feedback && plan.local.endurance, - }).map(([name, selected]) => [name, !draft && !(confirmation && isPostMerge(name as Category)) && selected])); + }).map(([name, selected]) => [name, !draft && !(confirmation && isPostMerge(name as Category)) && selected])), determinism }; } function git(root: string, args: string[]): string { diff --git a/scripts/ci-proof.ts b/scripts/ci-proof.ts index 9d354e1447..4e9a33a402 100644 --- a/scripts/ci-proof.ts +++ b/scripts/ci-proof.ts @@ -1,4 +1,3 @@ -import {logWorkerAuditDiagnostic} from "./browser-worker-audit"; /** Complete affected hosted proof. Reuses the opt-in local command inventory. */ import { requireCandidate, validateSelections } from "./candidate-proof"; import { cpus, freemem, totalmem } from "node:os"; @@ -9,26 +8,29 @@ import { runCommands, type Command } from "./ci-runner"; import type { CheckPlan } from "./ci-plan"; import { balanceTests, discoverTests } from "./test-shards"; import { resolveBrowserPin } from "./captures/provenance"; -import { diagramInstallationIdentity } from "./diagram-export-installation.mjs"; -import { diagramProducerRuntime } from "./diagram-export-producer.mjs"; import { startUnitMemorySampler } from "./unit-memory"; import { diskSampler, floorProblem } from "./ci-disk"; -import { browserInventory, checkout, git, proofInputs, runnerIdentity, type Reusable, type Inputs } from "./proof-inputs"; -import { contextFromEvent, GitHubProofAPI, RECEIPT_MARKER, retainedCategories } from "./proof-reuse"; -export const PROOF_JOBS = ["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance"] as const; -export type ProofCategory = "unit" | "browser" | "layout" | "captures" | "runtime" | "runtime_host" | "endurance"; +export const PROOF_JOBS = ["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "determinism"] as const; +export type ProofCategory = "unit" | "browser" | "layout" | "captures" | "runtime" | "runtime_host" | "endurance" | "determinism"; +export const DETERMINISM_REPORT = "tmp/determinism-report.json"; -/** Aggregate requires passed selected jobs; missing/false-looking output is not proof. */ -export function proofProblems(needs: Record }>, retained: ReadonlySet = new Set()): string[] { +/** The planner's added or modified Bun test files; an empty selection is never a job (#4109). */ +export function determinismFiles(plan: CheckPlan): string[] { + if (!plan.determinism?.length) throw new Error("Repeated-run proof was not selected"); + return [...plan.determinism]; +} + +/** Aggregate requires passed selected jobs; missing/false-looking output is not proof. + * Every selected category runs fresh: a skipped selected job never passes (#4107). */ +export function proofProblems(needs: Record }>): string[] { const problems: string[] = []; if (needs.changeset?.result !== "success") problems.push("metadata did not pass"); for (const name of PROOF_JOBS) { const selected = needs.changeset?.outputs?.[name]; const result = needs[name]?.result; if (selected !== "true" && selected !== "false") problems.push(`${name}: selection output is missing or invalid`); - else if (selected === "true" && retained.has(name) && result !== "skipped") problems.push(`${name}: retained proof must skip fresh execution (${result ?? "missing"})`); - else if (selected === "true" && result !== "success" && !(result === "skipped" && retained.has(name))) problems.push(`${name}: selected proof did not pass (${result ?? "missing"})`); + else if (selected === "true" && result !== "success") problems.push(`${name}: selected proof did not pass (${result ?? "missing"})`); else if (selected === "false" && result !== "skipped") problems.push(`${name}: unselected job must be intentionally skipped (${result ?? "missing"})`); } return problems; @@ -56,7 +58,11 @@ export function categoryCommands(category: ProofCategory, plan: CheckPlan, root: : [process.execPath, "run", "test", ...unitFiles(plan, root, shard).map(file => join(root, file)), "--reporter=junit", "--reporter-outfile=tmp/unit-report.xml", "--timings=tmp/unit-timings.json", "--update-timings"], env: { BRAIN_REQUIRE_CHROME: "1" } }]; - const names: Record, string[]> = { + // The unit job's serial form, repeated: changed files may drive real Chrome too. + if (category === "determinism") return [{ name: "changed Bun test files repeated under CPU load", + argv: [process.execPath, join(root, "scripts/test-determinism.ts"), `--report=${DETERMINISM_REPORT}`, ...determinismFiles(plan)], + env: { BRAIN_REQUIRE_CHROME: "1" } }]; + const names: Record, string[]> = { browser: ["workspace build for real browser checks", "complete pinned visual/accessibility/pointer suite"], layout: ["workspace build for real browser checks", "complete pinned layout/offline suite"], endurance: ["workspace build for real browser checks", "complete pinned endurance suite"], @@ -83,21 +89,17 @@ if (import.meta.main) { const event = process.env.GITHUB_EVENT_PATH ? await Bun.file(process.env.GITHUB_EVENT_PATH).json() : {}; await requireCandidate(root, event, process.env); if (process.env.GITHUB_ACTIONS === "true") validateSelections(root, event, process.env, needs?.changeset?.outputs); - const context = contextFromEvent(event, process.env); - const value = needs?.changeset?.outputs?.reuse; - const retained = value ? await retainedCategories(root, JSON.parse(value), context, - context && process.env.GH_TOKEN ? new GitHubProofAPI(context.repository, process.env.GH_TOKEN) : undefined) : new Set(); - if (process.env.GITHUB_ACTIONS === "true" && !value) throw new Error("Missing current-head proof ledger"); - for (const category of retained) if (needs?.changeset?.outputs?.[category] !== "true") throw new Error("Retained proof was not selected"); - const problems = proofProblems(needs, retained); + const problems = proofProblems(needs); if (problems.length) throw new Error(problems.join("\n")); - for (const category of retained) console.log(`Validated equivalent ${category} proof; original run/job/checkout identity remains in the ledger.`); - console.log(`BRAIN_SELECTED_PROOF_RECEIPT ${JSON.stringify({ selections: Object.fromEntries(PROOF_JOBS.map(name => [name, needs.changeset.outputs[name]])), results: Object.fromEntries(PROOF_JOBS.map(name => [name, needs[name]?.result])), retained: [...retained], unitShards: needs.changeset.outputs.unit_shards ?? null })}`); + // `retained` is always empty since proof retention was retired (#4107). The field stays so + // a checkout that predates the retirement, and the timing collector reading older runs, + // still parse this receipt. + console.log(`BRAIN_SELECTED_PROOF_RECEIPT ${JSON.stringify({ selections: Object.fromEntries(PROOF_JOBS.map(name => [name, needs.changeset.outputs[name]])), results: Object.fromEntries(PROOF_JOBS.map(name => [name, needs[name]?.result])), retained: [], unitShards: needs.changeset.outputs.unit_shards ?? null })}`); console.log("All selected hosted proof passed; remaining skips are planner-intended."); } else { const root = resolve(import.meta.dir, ".."); const category = process.argv[2] as ProofCategory; - if (!["unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance"].includes(category)) throw new Error("Unknown proof category"); + if (!["unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "determinism"].includes(category)) throw new Error("Unknown proof category"); const args = process.argv.slice(3); const shardArg = args.find(arg => arg.startsWith("--shard=")); const workersArg = args.find(arg => arg.startsWith("--workers=")); @@ -106,29 +108,22 @@ if (import.meta.main) { const shard = shardArg?.slice("--shard=".length); const unitWorkers = workersArg ? Number(workersArg.slice("--workers=".length)) : 2; const plan = await Bun.file(process.env.CI_PLAN_PATH ?? join(root, "tmp/ci-plan.json")).json() as CheckPlan; - let inputs:Inputs|undefined; - if (category === "browser" || category === "layout") { - try { - if (git(root, "diff", "HEAD", "--").trim()) throw new Error("Dirty tracked inputs"); - inputs = proofInputs(root, category as Reusable, await browserInventory(root), runnerIdentity()); - } catch (error) { logWorkerAuditDiagnostic(error); console.log(`Fresh execution remains required: reusable input inventory is unavailable: ${String(error)}`); } - } const identity = Bun.spawnSync(["git", "show", "-s", "--format=%H %T %P", "HEAD"], { cwd: root, stdout: "pipe", stderr: "pipe" }); if (identity.exitCode !== 0) throw new Error("Cannot record actual proof checkout"); const [sha, tree, ...parents] = new TextDecoder().decode(identity.stdout).trim().split(" "); await Bun.write(join(root, "tmp/proof-checkout.json"), JSON.stringify({ category, shard, - checkout: { sha, tree, parents }, plan, inputs, files: category === "unit" ? unitFiles(plan, root, shard) : undefined }, null, 2)); - const native = category === "unit" || category === "runtime" || category === "runtime_host"; + checkout: { sha, tree, parents }, plan, files: category === "unit" ? unitFiles(plan, root, shard) : category === "determinism" ? determinismFiles(plan) : undefined }, null, 2)); + const native = category === "unit" || category === "runtime" || category === "runtime_host" || category === "determinism"; const chrome = requireRuntimeTools({ ...plan, local: { ...plan.local, fullTests: native, browser: !native, layout: !native, captures: !native } }); - if (chrome && category === "unit") await runCommands([{ name: "first real Chrome launch and render", + if (chrome && (category === "unit" || category === "determinism")) await runCommands([{ name: "first real Chrome launch and render", argv: [process.execPath, "packages/ui-render-puppeteer/tests/cold-start.ts", chrome] }], root); const commands = categoryCommands(category, plan, root, shard, unitWorkers).map(command => ({ ...command, - env: { ...(chrome ? { PUPPETEER_EXECUTABLE_PATH: chrome } : {}), ...command.env, ...(inputs?.nativeDiagram?{BRAIN_PROOF_NATIVE_DIAGRAM_INPUTS:JSON.stringify(inputs.nativeDiagram)}:{}) } })); + env: { ...(chrome ? { PUPPETEER_EXECUTABLE_PATH: chrome } : {}), ...command.env } })); // The host/container lease regression deliberately uses --pull=never // under the offline test harness. Prepare its actual pinned image once, // only on the partition that discovers that test, before entering tests. - if (category === "unit" && unitFiles(plan, root, shard).includes("tests/workspace-lease.test.ts")) { + if ((category === "unit" ? unitFiles(plan, root, shard) : category === "determinism" ? determinismFiles(plan) : []).includes("tests/workspace-lease.test.ts")) { if (!Bun.which("docker")) throw new Error("The native workspace lease test requires Docker"); const { image } = await resolveBrowserPin(root); commands.unshift({ name: "pinned offline workspace lease container prerequisite", argv: ["docker", "pull", image], env: {} }); @@ -176,11 +171,6 @@ if (import.meta.main) { await Bun.file(join(root, "tmp/unit-report.xml")).text(), await Bun.file(join(root, "tmp/unit-timings.json")).json()); await Bun.write(join(root, "tmp/unit-report-summary.json"), JSON.stringify({ checkout: { sha, tree, parents }, shard, unitWorkers, ...report }, null, 2)); } - if (inputs) { - if(inputs.nativeDiagram&&(diagramInstallationIdentity(root).sha256!==inputs.nativeDiagram.installation||diagramProducerRuntime().sha256!==inputs.nativeDiagram.runtime))throw Error("Native diagram installed or runtime inputs changed during reusable execution"); - if (git(root, "diff", "HEAD", "--").trim()) throw new Error("Reusable execution changed tracked inputs"); - console.log(RECEIPT_MARKER + JSON.stringify({ version: 1, category, shard, checkout: checkout(root), inputs })); - } } } catch (error) { console.error(error); process.exit(1); } } diff --git a/scripts/ci-timings.ts b/scripts/ci-timings.ts index ac9121aa6d..bc77372249 100644 --- a/scripts/ci-timings.ts +++ b/scripts/ci-timings.ts @@ -159,6 +159,7 @@ export async function collectAttempt(api: TimingAPI, repository: string, raw: Ra const rows = log.split("\n").filter(line => line.includes("BRAIN_SELECTED_PROOF_RECEIPT ")); if (rows.length !== 1) throw new Error("Selected-proof timing metadata missing or ambiguous"); const receipt = JSON.parse(rows[0]!.split("BRAIN_SELECTED_PROOF_RECEIPT ")[1]!); + // Always empty since proof retention was retired (#4107); archived runs before it could retain. if (!Array.isArray(receipt.retained) || receipt.retained.some((c: unknown) => c !== "browser" && c !== "layout") || !CATEGORIES.every(c => ["true", "false"].includes(receipt.selections?.[c]))) throw new Error("Invalid selected-proof timing metadata"); snapshot.selection = { selections: Object.fromEntries(CATEGORIES.map(c => [c, receipt.selections[c]])), retained: receipt.retained }; diff --git a/scripts/generated-build-inputs.ts b/scripts/generated-build-inputs.ts deleted file mode 100644 index efb50b81dd..0000000000 --- a/scripts/generated-build-inputs.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** Exact source binding for freshly compiled browser CSS; never reads dist. */ -import { createHash } from "node:crypto"; -import { existsSync, readFileSync, realpathSync } from "node:fs"; -import { isAbsolute, relative, resolve } from "node:path"; -// These sources establish: tracked source entry, cleaned package dist, locked -// Tailwind CLI, build-before-browser order, checked exits and post-success receipt. -// This deliberately supports one audited producer, not arbitrary build tools. -const auditedProducer: Record = { - "scripts/build.ts": "6e83f426cf6a084e531f7e1aacc6d1574600dedfca890747df33199e2b3c9fd7", - "scripts/build-execution.ts": "89571c3af89489abe25f2b1113411c128c51a06fcd5f5b948e0899e4f6df8e89", - "scripts/build-receipt.ts": "b22743a8a943cd63d56519f4551715c4bbf2ff05e17ae8bd65cca2aeed88fa68", - "scripts/build-repeat-observation.ts": "8c497d87eddbc5682441574674b178960b54352a319228527a62fedff3279047", - "scripts/bin-modes.ts": "5e412f4743b388558a00d1068881ff6d6a0916e852e9ed2e973bc0a97a83c8ce", - "scripts/publishable-packages.ts": "c43a3fbea72217fc42c3514313dcb16d1b337242fc251b61d7f1a3c83ca25740", - "scripts/workspace-lease.mjs": "d1e427171a70f906f219b43ea6e47f69c628e60c126a2bb7ac30ff5e2c9a81ad", - "scripts/ci-proof.ts": "17e0c248792ebe7abc22bd93eb4bd402356cc395c6cab548b8cf65810238eae7", - "scripts/check-pr.ts": "a5ef505c320306ecfef9cb2d9452ad78898c09be6567201649913d01636a27a0", - "scripts/ci-runner.ts": "1f65e665afa202c2e8a72938fb193dcee7cebeb7c6d4e97456520e461e52609f", - ".github/workflows/ci.yml": "a5b3f82fa11111ed9bff29a5423873b6fc91bc4187370754e16e85ad06f11d56", - "package.json": "fb862fa1374a2e31a4d4eb317fabb1453e5325a9cd154ede1ecc8c91e9acc16c" -}; -export function generatedCssInputs(root: string, artifact: string): { entry: string; producer: string[] } | undefined { - const normalized=relative(root,resolve(root,artifact)).replaceAll("\\","/"); - if(isAbsolute(normalized)||normalized.startsWith("../")) return undefined; - const match=/^packages\/(ui-kit|ui-react)\/dist\/(styles|theme|tokens)\.css$/.exec(normalized); - if(!match || match[1] === "ui-react" && match[2] === "tokens") return undefined; - for(const [file,digest] of Object.entries(auditedProducer)) { - const path=resolve(root,file); - if(!existsSync(path)||realpathSync(path)!==path||createHash("sha256").update(readFileSync(path)).digest("hex")!==digest) return undefined; - } - const entry=`packages/${match[1]}/src/${match[2]}.css`,absolute=resolve(root,entry); - if(!existsSync(absolute)||realpathSync(absolute)!==absolute) return undefined; - return {entry,producer:[...Object.keys(auditedProducer),`packages/${match[1]}/package.json`]}; -} - -// These commands run with the audited browser runner's packages/ui-kit cwd. -const auditedReaders: Record = { - "packages/ui-kit/tests/visual/form-browser.ts": "5def3875a8e16e41b22bf1ff2a25b045a3adc59bdc2df2e0c7754126f3c8e27b", - "packages/ui-react/tests/browser/offline/cold-capture/commands.ts": "1b9063232ed794ed206cb09520641ff25897a3133e6168ceff10f18cca746ef0", - "packages/ui-react/tests/browser/share-review/commands.ts": "49dc3fd14d370ddf087986fc135343b2419efd0f1924096edd669b6e0d0f6e33" -}; -export function generatedCssReadInputs(root:string,owner:string,literal:string) { - const expected=auditedReaders[owner],path=resolve(root,owner); - if(!expected||!existsSync(path)||realpathSync(path)!==path||createHash("sha256").update(readFileSync(path)).digest("hex")!==expected) return undefined; - return generatedCssInputs(root,resolve(root,"packages/ui-kit",literal)); -} diff --git a/scripts/generated-theme-inputs.ts b/scripts/generated-theme-inputs.ts deleted file mode 100644 index 48fa42da01..0000000000 --- a/scripts/generated-theme-inputs.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** Source-audited temporary CSS producer with checked process completion. */ -import {createHash} from "node:crypto"; -import {existsSync,readFileSync,realpathSync} from "node:fs"; -import {resolve} from "node:path"; -import type {BrowserImporters} from "./bound-browser-runtime-inputs"; -import {generatedCssInputs} from "./generated-build-inputs"; -import {lockedPackageAsset} from "./locked-browser-assets"; -const sources={ - "packages/ui-kit/tests/visual/dictation-motion.ts": "426a9ae556c11ea60ab8563c71ee220a3bb7140638b0ef1062aacf1bb3b65e70", - "packages/ui-kit/vitest.config.ts": "89ea7a414a191a5624fce2dff8e0434aac5474c4c5b74d13499848cd17e2b257", - "packages/ui-kit/tests/visual/dictation-theme.css": "dfe3bb18ef30797d9d2ded77a675520035bf0eb8b3d82de180fe640bea84c7c6" -}; -export function generatedThemeInputs(root:string,files:readonly string[],importers:BrowserImporters){ - const owner="packages/ui-kit/tests/visual/dictation-motion.ts",caller="packages/ui-kit/vitest.config.ts",entry="packages/ui-kit/tests/visual/dictation-theme.css"; - if(!files.includes(owner)||!files.includes(caller)||[...(importers.get(owner)??[])].some(file=>file!==caller))return; - for(const [file,expected] of Object.entries(sources)){const path=resolve(root,file);if(!existsSync(path)||realpathSync(path)!==path||createHash("sha256").update(readFileSync(path)).digest("hex")!==expected)return;} - const theme=generatedCssInputs(root,"packages/ui-react/dist/theme.css"),compiler=lockedPackageAsset(root,"@tailwindcss/cli","dist/index.mjs"); - if(!theme||!compiler)return; - // The exact command body: owns mkdtemp output, uses this locked CLI and - // constant entry/arguments, awaits execFile success, then reads and cleans it. - // Only the precise promisify/createRequire uses below may cross alias checks. - return {owner,read:'readFile(output, "utf8")',css:[entry,theme.entry],bytes:theme.producer,compiler, - aliases:new Map([["execFile",new Set(["promisify(execFile)"])],["require",new Set(['require = createRequire(import.meta.url)','require.resolve("@tailwindcss/cli/package.json")'])]])}; -} diff --git a/scripts/heavy-feedback-workflow.ts b/scripts/heavy-feedback-workflow.ts index e6146a680a..c120616c39 100644 --- a/scripts/heavy-feedback-workflow.ts +++ b/scripts/heavy-feedback-workflow.ts @@ -13,7 +13,7 @@ import { annotateActionPins } from "./action-pins"; 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 CATEGORY_JOBS = ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism"] 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'"; @@ -51,7 +51,6 @@ export function renderHeavyFeedbackWorkflow(ciText: string): string { 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. const workflow = { name: "Draft heavy feedback", on: { @@ -62,7 +61,7 @@ export function renderHeavyFeedbackWorkflow(ciText: string): 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" }, + permissions: { contents: "read", actions: "read" }, concurrency: { group: FEEDBACK_GROUP, "cancel-in-progress": true }, jobs: { supersede: { @@ -86,7 +85,6 @@ export function renderHeavyFeedbackWorkflow(ciText: string): string { { 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" }, ], }, ...Object.fromEntries(CATEGORY_JOBS.map(name => [name, categoryJob(ci.jobs[name]!)])), diff --git a/scripts/heavy-feedback.ts b/scripts/heavy-feedback.ts index abd8fde70d..41d1d24b16 100644 --- a/scripts/heavy-feedback.ts +++ b/scripts/heavy-feedback.ts @@ -13,7 +13,7 @@ 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"; +import { GitHubProofAPI, type API } from "./proof-api"; export const FEEDBACK_WORKFLOW = "heavy-feedback.yml"; export const FEEDBACK_AGGREGATE = "draft heavy feedback"; diff --git a/scripts/inclusion-inputs.ts b/scripts/inclusion-inputs.ts deleted file mode 100644 index 9c55239790..0000000000 --- a/scripts/inclusion-inputs.ts +++ /dev/null @@ -1,124 +0,0 @@ -/** Immutable inclusion fingerprints. Unknown runtime ownership always executes fresh. */ -import ts from "typescript"; -import { includeBrowserScreenshots } from "./browser-screenshot-inputs"; -import { auditedInactiveCommands } from "./browser-command-activation"; -import {inspectWorkerAudit,WorkerAuditError,pdfWorkerInput} from "./browser-worker-audit"; -import { createHash } from "node:crypto"; -import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join } from "node:path"; -import { discoverInputClosure, type InputDeclaration } from "./browser-input-closure"; -import { balanceBrowserSpecs, readBrowserCosts } from "./browser-shards"; -import { PROOF_SHARDS } from "./proof-shards"; -import { selectedSpecs, treeEntries, type Inputs, type Reusable, type Spec } from "./proof-inputs"; - -const required = ["package.json", "bun.lock", "tsconfig.json", "bunfig.toml", ".github/workflows/ci.yml", - "packages/ui-kit/tests/proof-inputs.json", "packages/ui-kit/vitest.config.ts", "packages/ui-kit/vite.config.ts", - "packages/ui-kit/.storybook/main.ts", "packages/ui-kit/.storybook/preview.ts", "scripts/browser-shard-costs.json", - "scripts/visual.mjs", "scripts/build.ts", "scripts/workspace-lease.mjs", "scripts/css-proof-inputs.json", - "packages/ui-kit/src/styles.css", "packages/ui-react/src/styles.css"]; -const harness = (path: string) => path.startsWith("scripts/") || path.startsWith(".github/workflows/") || - required.includes(path) || /(?:^|\/)(?:package\.json|bun\.lock|bunfig\.toml|tsconfig(?:\.[^/]+)?\.json)$/.test(path); - -/** Each immutable tree is materialized independently; current untracked/dist outputs never join discovery. */ -export function inclusionInputs(root: string, category: Reusable, inventory: Spec[], runner: string, ref = "HEAD"): Inputs { - if (!runner) throw new Error("Unknown runner image requires fresh proof"); - const entries = treeEntries(root, ref), paths = new Map(entries.map(entry => [entry.path, entry])); - if (required.some(path => !paths.has(path))) throw new Error("Missing immutable proof configuration"); - // Resolution uses the one frozen install. Different lockfiles/manifests/algorithm - // cannot be interpreted through that install or current helper implementation. - const current = new Map(treeEntries(root, "HEAD").map(entry => [entry.path, entry])); - const policyPaths = new Set([...paths.keys(), ...current.keys()].filter(harness)); - for (const path of policyPaths) if (paths.get(path)?.oid !== current.get(path)?.oid || paths.get(path)?.mode !== current.get(path)?.mode) - throw new Error("Changed immutable algorithm or dependency inputs require fresh proof"); - const snapshot = mkdtempSync(join(tmpdir(), "brain-proof-inputs-")); - try { - // Read raw Git blobs, not archive filters/export-ignore/substitution or - // current worktree bytes. No generated output enters the snapshot. - const blobs = Bun.spawnSync(["git", "cat-file", "--batch"], { cwd: root, - stdin: new TextEncoder().encode(entries.map(entry => entry.oid).join("\n") + "\n"), stdout: "pipe", stderr: "pipe" }); - if (blobs.exitCode) throw new Error("Cannot materialize immutable proof blobs"); - const bytes = Buffer.from(blobs.stdout); let offset = 0; - for (const entry of entries) { - const end = bytes.indexOf(10, offset); - if (end < offset) throw new Error("Missing immutable blob header"); - const header = bytes.subarray(offset, end).toString("ascii").split(" "); - const size = Number(header[2]); - if (header[0] !== entry.oid || header[1] !== "blob" || !Number.isSafeInteger(size) || size < 0 || end + 1 + size >= bytes.length) - throw new Error("Invalid immutable blob inventory"); - const contents = bytes.subarray(end + 1, end + 1 + size), target = join(snapshot, entry.path); - mkdirSync(dirname(target), { recursive: true }); - if (entry.mode === "120000") symlinkSync(contents.toString("utf8"), target); - else if (entry.mode === "100644" || entry.mode === "100755") { writeFileSync(target, contents); chmodSync(target, entry.mode === "100755" ? 0o755 : 0o644); } - else throw new Error("Unsupported immutable input mode"); - offset = end + 1 + size + 1; - } - if (offset !== bytes.length) throw new Error("Unexpected immutable blob output"); - if (!existsSync(join(root, "node_modules"))) throw new Error("Locked dependency resolution unavailable"); - // Workspace package symlinks must resolve INSIDE this immutable snapshot. - // External packages remain read-only links to the matching frozen install. - const workspaces = new Map(); - for (const entry of entries.filter(entry => /^packages\/[^/]+\/package\.json$/.test(entry.path))) { - const manifest = JSON.parse(readFileSync(join(snapshot, entry.path), "utf8")); - if (typeof manifest.name !== "string") throw new Error("Unknown workspace package identity"); - workspaces.set(manifest.name, entry.path.slice(0, -"/package.json".length)); - } - mkdirSync(join(snapshot, "node_modules")); - for (const entry of readdirSync(join(root, "node_modules"), { withFileTypes: true })) { - if (entry.name.startsWith(".")) continue; - if (entry.name.startsWith("@")) { - mkdirSync(join(snapshot, "node_modules", entry.name)); - for (const child of readdirSync(join(root, "node_modules", entry.name))) { - const name = `${entry.name}/${child}`; - symlinkSync(workspaces.has(name) ? join(snapshot, workspaces.get(name)!) : join(root, "node_modules", name), join(snapshot, "node_modules", name), "dir"); - } - } else symlinkSync(workspaces.has(entry.name) ? join(snapshot, workspaces.get(entry.name)!) : join(root, "node_modules", entry.name), join(snapshot, "node_modules", entry.name), "dir"); - } - const declarations = ["packages/ui-kit/tests/proof-inputs.json", "scripts/css-proof-inputs.json"].flatMap(file => { - const value = JSON.parse(readFileSync(join(snapshot, file), "utf8")); - if (!Array.isArray(value)) throw new Error("Invalid immutable input declarations"); - return value as InputDeclaration[]; - }); - if (!Array.isArray(declarations)) throw new Error("Invalid immutable input declarations"); - const selected = selectedSpecs(category, inventory); - const inputs = [...required.filter(path => path.startsWith("packages/ui-kit/") || path === "packages/ui-react/src/styles.css"), ...selected.map(spec => spec.file)]; - const activation = category === "browser" ? auditedInactiveCommands(snapshot, selected) : undefined; - const closure = includeBrowserScreenshots(snapshot, discoverInputClosure(snapshot, inputs, declarations, activation), selected, new Set(paths.keys())); - // Mandatory for this browser capability, even when a changed source hides - // the recognizable constructor behind a new alias/realm. Such edits cannot - // turn an absent audit into a generally closed domain. - if(category==="browser"){ - const audit=inspectWorkerAudit(snapshot,closure,selected); - if(!audit.qualified)throw new WorkerAuditError(audit.diagnostic); - closure.unresolved=closure.unresolved.filter(input=>input!==pdfWorkerInput); - } - if (closure.unresolved.length) throw new Error(`Unresolved immutable ${category} inputs require fresh proof: ${closure.unresolved.slice(0, 3).join("; ")}`); - const included = new Set([...closure.files, ...entries.filter(entry => harness(entry.path)).map(entry => entry.path)]); - // Builds compile their expanded source inventories; compilation hashes - // source bytes without interpreting dormant runtime filesystem calls. - for (const entry of entries.filter(entry => /^packages\/[^/]+\/tsconfig\.build\.json$/.test(entry.path))) { - const config = ts.readConfigFile(join(snapshot, entry.path), ts.sys.readFile); - if (config.error) throw new Error("Unknown immutable compiler configuration"); - const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, join(snapshot, entry.path.slice(0, entry.path.lastIndexOf("/")))); - if (parsed.errors.length) throw new Error("Unknown immutable compiler inventory"); - for (const path of parsed.fileNames) { - if (!path.startsWith(snapshot + "/")) throw new Error("Compiler input escapes immutable repository"); - included.add(path.slice(snapshot.length + 1)); - } - } - // Directory ownership expands from the immutable tree, not from current disk. - for (const directory of closure.directories ?? []) for (const entry of entries) - if (entry.path.startsWith(directory + "/")) included.add(entry.path); - for (const path of included) { - if (closure.directories?.includes(path)) continue; - if (!paths.has(path) || !existsSync(join(snapshot, path))) throw new Error("Missing immutable input ownership"); - if (!["100644", "100755"].includes(paths.get(path)!.mode)) throw new Error("Unsupported symbolic input requires fresh proof"); - } - const partitions = balanceBrowserSpecs(selected.map(spec => ({ key: `${spec.project}::${spec.file}`, project: spec.project })), - PROOF_SHARDS[category], readBrowserCosts(join(snapshot, "scripts/browser-shard-costs.json"))).map(part => part.map(spec => spec.key)); - const files = entries.filter(entry => included.has(entry.path)); - const material = { version: 2, category, runner, inventory, partitions, directories: closure.directories ?? [], external: closure.external ?? [], files }; - return { version: 2, category, runner, inventory, partitions, excluded: [], - fingerprint: createHash("sha256").update(JSON.stringify(material)).digest("hex") }; - } finally { rmSync(snapshot, { recursive: true, force: true }); } -} diff --git a/scripts/integrate.ts b/scripts/integrate.ts index 8bac1fcf3d..d740d766ea 100644 --- a/scripts/integrate.ts +++ b/scripts/integrate.ts @@ -9,7 +9,7 @@ import { isAncestor } from "./red-main-cli"; import { expeditedProblems, expeditedTests, fixProbeTitle, probeReceipt, type FeedbackEvidence, type ProbeEvidence } from "./red-main-expedite"; import { receiptFromBody, receiptRefusal } from "./check-receipt"; import { reviewGate } from "./review-receipt"; -import type { API } from "./proof-reuse"; +import type { API } from "./proof-api"; /** * A refusal no retry can cure: the candidate changed or the reservation no longer diff --git a/scripts/integration-proof.ts b/scripts/integration-proof.ts index 2509501c26..279781a533 100644 --- a/scripts/integration-proof.ts +++ b/scripts/integration-proof.ts @@ -2,7 +2,7 @@ import { validateCandidate } from "./candidate-proof"; import { checkout, type Checkout } from "./proof-inputs"; import type { Candidate } from "./integration-reservation"; -import type { API } from "./proof-reuse"; +import type { API } from "./proof-api"; import { PROOF_JOBS, proofProblems } from "./ci-proof"; import { MAX_UNIT_PARTITIONS, shardNumbers, unitPartitionLimit } from "./proof-shards"; import { coveredCategories } from "./check-receipt"; @@ -110,14 +110,15 @@ export async function verifyIntegrationProof(root: string, repository: string, c const selectedLines = proofLog.split("\n").filter(line => line.includes("BRAIN_SELECTED_PROOF_RECEIPT ")); if (selectedLines.length !== 1) throw new Error("Fresh structured selected-proof receipt required"); const selected = JSON.parse(selectedLines[0]!.split("BRAIN_SELECTED_PROOF_RECEIPT ")[1]!) as { - selections: Record; results: Record; retained: string[]; unitShards: string | null; + selections: Record; results: Record; retained?: unknown; unitShards: string | null; }; - if (!Array.isArray(selected.retained) || selected.retained.some(name => !["browser", "layout"].includes(name))) throw new Error("Unsupported retained proof identity"); + // Retention is retired (#4107): a receipt naming a retained category is not fresh proof. + if (selected.retained !== undefined && (!Array.isArray(selected.retained) || selected.retained.length)) throw new Error("Retained proof is retired: every selected category must run fresh"); const needs = { changeset: { result: "success", outputs: selected.selections }, ...Object.fromEntries(PROOF_JOBS.map(name => [name, { result: selected.results[name] }])) }; - if (proofProblems(needs, new Set(selected.retained)).length) throw new Error("Selected proof did not satisfy the aggregate policy"); + if (proofProblems(needs).length) throw new Error("Selected proof did not satisfy the aggregate policy"); const expected = ["changeset:success", "proof:success"]; for (const name of PROOF_JOBS) { - const fresh = selected.selections[name] === "true" && !selected.retained.includes(name); + const fresh = selected.selections[name] === "true"; if (fresh && (name === "browser" || name === "layout")) expected.push(...shardNumbers(name).map(shard => `${name} (${shard}):success`)); else if (fresh && name === "unit") { const shards: unknown = JSON.parse(selected.unitShards ?? "null"); diff --git a/scripts/locked-browser-assets.ts b/scripts/locked-browser-assets.ts deleted file mode 100644 index ada3893632..0000000000 --- a/scripts/locked-browser-assets.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** Bounded installed asset identity; matching locked install remains required. */ -import { createHash } from "node:crypto"; -import { existsSync, lstatSync, readFileSync, realpathSync } from "node:fs"; -import { join, resolve, sep } from "node:path"; -export interface LockedBrowserAsset { package: string; version: string; asset: string; sha256: string; mode: number; } -const readers: Record = { - "packages/ui-react/tests/browser/offline/cold-capture/commands.ts": "1b9063232ed794ed206cb09520641ff25897a3133e6168ceff10f18cca746ef0", - "packages/ui-react/tests/browser/share-review/commands.ts": "49dc3fd14d370ddf087986fc135343b2419efd0f1924096edd669b6e0d0f6e33" -}; -/** The audited digest pinned for `owner`, if it is an audited reader. A reader - * whose bytes drift from it reads an unknown asset (fresh proof) until a - * post-merge re-audit refreshes the pin (#2408, ruling of 2026-11-04). */ -export function auditedReaderDigest(owner:string):string|undefined { return readers[owner]; } -export function lockedBrowserAsset(root:string,owner:string,literal:string):LockedBrowserAsset|undefined { - if(literal!=="../../node_modules/axe-core/axe.min.js"||!readers[owner]) return undefined; - const source=resolve(root,owner); - if(!existsSync(source)||realpathSync(source)!==source||createHash("sha256").update(readFileSync(source)).digest("hex")!==readers[owner]) return undefined; - return lockedPackageAsset(root,"axe-core","axe.min.js"); -} -/** Only these audited installed assets have a supported read boundary. */ -export function lockedPackageAsset(root:string,packageName:string,assetName:string):LockedBrowserAsset|undefined { - if(!["axe-core/axe.min.js","@tailwindcss/cli/dist/index.mjs","@vitest/browser/dist/index.js"].includes(`${packageName}/${assetName}`))return undefined; - if(!existsSync(join(root,"bun.lock"))||!existsSync(join(root,"package.json"))) return undefined; - const directory=join(root,"node_modules",packageName),asset=join(directory,assetName),manifest=join(directory,"package.json"); - if(!existsSync(asset)||!existsSync(manifest)) return undefined; - const base=realpathSync(directory),real=realpathSync(asset),stat=lstatSync(asset); - if(!real.startsWith(base+sep)||!stat.isFile()||stat.isSymbolicLink()||lstatSync(manifest).isSymbolicLink()) return undefined; - const data=JSON.parse(readFileSync(manifest,"utf8")); - if(data.name!==packageName||typeof data.version!=="string"||!/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(data.version)) return undefined; - return {package:packageName,version:data.version,asset:assetName,sha256:createHash("sha256").update(readFileSync(asset)).digest("hex"),mode:stat.mode&0o777}; -} diff --git a/scripts/proof-api.ts b/scripts/proof-api.ts new file mode 100644 index 0000000000..7c063a839d --- /dev/null +++ b/scripts/proof-api.ts @@ -0,0 +1,41 @@ +/** Bounded read-only GitHub client for proof identities: candidate admission, + * draft feedback admission, the merge path and the cost refresh. It carries no + * passing-result cache and reads nothing a job could have written as a claim. */ +export interface API { json(path: string): Promise; log(job: number): Promise; } + +export class GitHubProofAPI implements API { + private readonly deadline = Date.now() + 45000; + private requests = 0; + constructor(private readonly repository: string, private readonly token: string) {} + private async read(path: string, log = false): Promise { + if (++this.requests > 32 || Date.now() >= this.deadline) throw new Error("Proof lookup budget exhausted"); + let url = `https://api.github.com/repos/${this.repository}/${path}`; + let response: Response; + for (let redirects = 0;; redirects++) { + response = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(Math.min(8000, this.deadline - Date.now())), + headers: { Accept: "application/vnd.github+json", ...(url.startsWith("https://api.github.com/") ? { Authorization: `Bearer ${this.token}` } : {}) } }); + if (![301, 302, 303, 307, 308].includes(response.status)) break; + if (redirects >= 2 || !log) throw new Error("Unexpected proof API redirect"); + await response.body?.cancel(); + url = new URL(response.headers.get("location") ?? "", url).href; + if (!url.startsWith("https://")) throw new Error("Unsafe log redirect"); + } + if (!response.ok) throw new Error(`Proof API refused ${response.status}`); + const reader = response.body?.getReader(); + if (!reader) throw new Error("Missing proof API response"); + const chunks: Uint8Array[] = []; let length = 0; + for (;;) { + const { done, value } = await reader.read(); if (done) break; + length += value.length; + if (length > (log ? 16000000 : 2000000)) { await reader.cancel(); throw new Error("Unbounded proof response"); } + chunks.push(value); + } + return new TextDecoder().decode(Buffer.concat(chunks)); + } + async json(path: string): Promise { + const text = await this.read(path); + try { return JSON.parse(text); } + catch { throw new Error(`Invalid GitHub proof JSON: ${path}`); } + } + async log(job: number): Promise { return this.read(`actions/jobs/${job}/logs`, true); } +} diff --git a/scripts/proof-inputs.ts b/scripts/proof-inputs.ts index c4e099b9be..da583cdf90 100644 --- a/scripts/proof-inputs.ts +++ b/scripts/proof-inputs.ts @@ -1,24 +1,11 @@ -/** Immutable inclusion-based browser inputs. Native/Git-derived proof stays fresh. */ +/** Checkout identities and browser spec discovery shared by the planner, the + * proof jobs and the merge path. */ import { createHash } from "node:crypto"; import { mkdirSync, readFileSync, rmSync, statSync } from "node:fs"; import { dirname, join, relative } from "node:path"; -import { inclusionInputs } from "./inclusion-inputs"; -export const REUSABLE = ["browser", "layout"] as const; -export type Reusable = typeof REUSABLE[number]; export interface Spec { project: string; file: string; } export interface Checkout { sha: string; tree: string; parents: string[]; } -export interface Inputs { - version: 2; category: Reusable; fingerprint: string; runner: string; - inventory: Spec[]; partitions: string[][]; excluded: string[]; - /** - * Never produced since #4105 retired the frozen native diagram qualification. - * `scripts/ci-proof.ts` and `scripts/visual.mjs` still read it, and do - * nothing when it is absent; they are audited sources, so the dead branches - * go when those files next change under their own re-audit. - */ - nativeDiagram?:{source:string;installation:string;runtime:string}; -} export function git(root: string, ...args: string[]): string { const p = Bun.spawnSync(["git", ...args], { cwd: root, stdout: "pipe", stderr: "pipe" }); if (p.exitCode) throw new Error(`Cannot inspect proof Git inputs: ${new TextDecoder().decode(p.stderr).trim()}`); @@ -29,13 +16,6 @@ export function checkout(root: string, ref = "HEAD"): Checkout { if (!sha || !tree) throw new Error("Missing immutable checkout identity"); return { sha, tree, parents }; } -export function treeEntries(root: string, ref: string): { mode: string; oid: string; path: string }[] { - return git(root, "ls-tree", "-r", "-z", ref).split("\0").filter(Boolean).map(line => { - const tab = line.indexOf("\t"), [mode, kind, oid] = line.slice(0, tab).split(" "); - if (tab < 0 || !mode || !oid || kind !== "blob") throw new Error("Unknown Git input (including submodules) requires fresh proof"); - return { mode, oid, path: line.slice(tab + 1) }; - }); -} export function normalizeInventory(value: unknown, root?: string): Spec[] { if (!Array.isArray(value) || !value.length || value.length > 5000) throw new Error("Missing or unbounded browser discovery"); const specs = value.map((item: { project?: unknown; projectName?: unknown; file?: unknown }) => { @@ -45,21 +25,9 @@ export function normalizeInventory(value: unknown, root?: string): Spec[] { return { project, file }; }).sort((a, b) => a.project < b.project ? -1 : a.project > b.project ? 1 : a.file < b.file ? -1 : a.file > b.file ? 1 : 0); if (new Set(specs.map(s => `${s.project}::${s.file}`)).size !== specs.length) throw new Error("Duplicate browser discovery"); - if (JSON.stringify(specs).length > 60000) throw new Error("Unbounded browser input receipt"); + if (JSON.stringify(specs).length > 60000) throw new Error("Unbounded browser discovery inventory"); return specs; } -export function selectedSpecs(category: Reusable, inventory: readonly Spec[]): Spec[] { - const selected = inventory.filter(s => category === "layout" ? s.project === "ui-react-layout" : ! ["ui-react-layout", "ui-react-endurance"].includes(s.project)); - if (selected.length < 2) throw new Error("Incomplete browser category inventory"); - return selected; -} - -export function proofInputs(root: string, category: Reusable, inventory: Spec[], runner: string, - ref = "HEAD", excluded: string[] = []): Inputs { - if (excluded.length) throw new Error("Invalid legacy input ownership"); - return inclusionInputs(root, category, inventory, runner, ref); -} - /** Drain both native pipes without retaining arbitrarily large warning output. */ async function discoveryOutput(stream: ReadableStream) { let bytes = 0, tail = Buffer.alloc(0); @@ -124,11 +92,11 @@ export async function browserInventory(root: string, deadlineMs = 30000): Promis // may contain colored diagnostics; it is not the machine envelope. const inventory = normalizeInventory(await Bun.file(output).json(), root); const declaration = /const projects = projectArgs\.length \?[^\n]+ : (\[[^\n]+\]);/.exec(readFileSync(join(root, "scripts/visual.mjs"), "utf8")); - if (!declaration) throw new Error("Unknown browser project selection requires fresh proof"); + if (!declaration) throw new Error("Unknown browser project selection"); const defaults = JSON.parse(declaration[1]!) as string[]; const expected = [...defaults, "ui-react-layout", "ui-react-endurance"].sort(); const actual = [...new Set(inventory.map(spec => spec.project))].sort(); - if (!defaults.length || new Set(expected).size !== expected.length || JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error("Unknown or missing browser project discovery requires fresh proof"); + if (!defaults.length || new Set(expected).size !== expected.length || JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error("Unknown or missing browser project discovery"); return inventory; } catch (error) { stopDiscovery(); @@ -143,9 +111,3 @@ export async function browserInventory(root: string, deadlineMs = 30000): Promis rmSync(output, { force: true }); } } -export function runnerIdentity(env: NodeJS.ProcessEnv = process.env): string { - // No externally hosted Storybook or alternate runtime context can be retained. - if (["BRAIN_ROOT", "BRAIN_WORKER_DATA_ROOT", "BRAIN_WORKER_CONFIG_ROOT"].some(name => env[name] !== undefined) || - env.SB_URL || env.NODE_OPTIONS || !env.ImageVersion || env.RUNNER_OS !== "Linux" || env.RUNNER_ARCH !== "X64") return ""; - return `ubuntu-24.04/${env.ImageVersion}/Linux/X64/bun-${Bun.version}/brain-roots-absent-v1`; -} diff --git a/scripts/proof-reuse.ts b/scripts/proof-reuse.ts deleted file mode 100644 index f9c1e2f723..0000000000 --- a/scripts/proof-reuse.ts +++ /dev/null @@ -1,204 +0,0 @@ -import {logWorkerAuditDiagnostic} from "./browser-worker-audit"; -/** Bounded immutable GitHub receipts; no passing-result cache or privileged event. */ -import { appendFileSync } from "node:fs"; -import { join, resolve } from "node:path"; -import { PROOF_SHARDS, shardNumbers } from "./proof-shards"; -import { browserInventory, checkout, git, normalizeInventory, proofInputs, REUSABLE, runnerIdentity, - type Checkout, type Inputs, type Reusable } from "./proof-inputs"; -import { proofSelections, type CheckPlan } from "./ci-plan"; - -export const RECEIPT_MARKER = "BRAIN_PROOF_RECEIPT "; -export interface FreshReceipt { version: 1; category: Reusable; shard: string; checkout: Checkout; inputs: Inputs; } -export interface Source { run: number; attempt: number; jobs: number[]; checkout: Checkout; inputs: Inputs; } -export interface Ledger { version: 1; checkout: Checkout; retained: Partial>; } -export interface Context { repository: string; headRepository: string; branch: string; pr: number; run: number; } -export interface API { json(path: string): Promise; log(job: number): Promise; } -const SHA = /^[a-f0-9]{40}$/; -const validID = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value > 0; - -export function contextFromEvent(event: any, env: NodeJS.ProcessEnv): Context | undefined { - const pr = event.pull_request; - if (env.GITHUB_ACTIONS !== "true" || env.GITHUB_EVENT_NAME !== "pull_request" || pr?.draft || !validID(pr?.number) || - !pr.head?.repo?.full_name || !pr.head.ref || !validID(Number(env.GITHUB_RUN_ID)) || - env.GITHUB_REPOSITORY !== "schlessera/brain-kit") return undefined; - return { repository: env.GITHUB_REPOSITORY, headRepository: pr.head.repo.full_name, - branch: pr.head.ref, pr: pr.number, run: Number(env.GITHUB_RUN_ID) }; -} -export class GitHubProofAPI implements API { - private readonly deadline = Date.now() + 45000; - private requests = 0; - constructor(private readonly repository: string, private readonly token: string) {} - private async read(path: string, log = false): Promise { - if (++this.requests > 32 || Date.now() >= this.deadline) throw new Error("Proof lookup budget exhausted"); - let url = `https://api.github.com/repos/${this.repository}/${path}`; - let response: Response; - for (let redirects = 0;; redirects++) { - response = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(Math.min(8000, this.deadline - Date.now())), - headers: { Accept: "application/vnd.github+json", ...(url.startsWith("https://api.github.com/") ? { Authorization: `Bearer ${this.token}` } : {}) } }); - if (![301, 302, 303, 307, 308].includes(response.status)) break; - if (redirects >= 2 || !log) throw new Error("Unexpected proof API redirect"); - await response.body?.cancel(); - url = new URL(response.headers.get("location") ?? "", url).href; - if (!url.startsWith("https://")) throw new Error("Unsafe log redirect"); - } - if (!response.ok) throw new Error(`Proof API refused ${response.status}`); - const reader = response.body?.getReader(); - if (!reader) throw new Error("Missing proof API response"); - const chunks: Uint8Array[] = []; let length = 0; - for (;;) { - const { done, value } = await reader.read(); if (done) break; - length += value.length; - if (length > (log ? 16000000 : 2000000)) { await reader.cancel(); throw new Error("Unbounded proof response"); } - chunks.push(value); - } - return new TextDecoder().decode(Buffer.concat(chunks)); - } - async json(path: string): Promise { - const text = await this.read(path); - try { return JSON.parse(text); } - catch { throw new Error(`Invalid GitHub proof JSON: ${path}`); } - } - async log(job: number): Promise { return this.read(`actions/jobs/${job}/logs`, true); } -} -async function ensureCommit(root: string, sha: string): Promise { - if (!SHA.test(sha)) throw new Error("Invalid source commit"); - const present = Bun.spawnSync(["git", "cat-file", "-e", `${sha}^{commit}`], { cwd: root, stdout: "pipe", stderr: "pipe" }); - if (present.exitCode === 0) return; - const p = Bun.spawn(["git", "fetch", "--no-tags", "--quiet", "origin", sha], { cwd: root, stdout: "pipe", stderr: "pipe" }); - const timer = setTimeout(() => p.kill("SIGKILL"), 8000); - try { if (await p.exited) throw new Error("Source commit is unavailable"); } - finally { clearTimeout(timer); } -} -export function receiptFromLog(text: string, category: Reusable, shard: number): FreshReceipt { - const clean = text.replace(/\u001b\[[0-9;]*[A-Za-z]/g, ""); - const rows = clean.split("\n").filter(line => /^\S+ BRAIN_PROOF_RECEIPT /.test(line)); - if (rows.length !== 1) throw new Error("Missing or ambiguous fresh execution receipt"); - const receipt = JSON.parse(rows[0]!.slice(rows[0]!.indexOf(RECEIPT_MARKER) + RECEIPT_MARKER.length)) as FreshReceipt; - if (receipt.version !== 1 || receipt.category !== category || receipt.shard !== `${shard}/${PROOF_SHARDS[category]}` || - !SHA.test(receipt.checkout?.sha ?? "") || !SHA.test(receipt.checkout?.tree ?? "") || !receipt.inputs) throw new Error("Wrong fresh execution receipt"); - if (!clean.split("\n").some(line => /^\S+ /.test(line) && line.trim().endsWith(`Z ${receipt.checkout.sha}`))) throw new Error("Receipt is not the actual job checkout"); - return receipt; -} - -/** Recompute BOTH immutable trees; artifact/log claims cannot authorize retention. */ -export async function validateSource(root: string, category: Reusable, source: Source, inputs: Inputs, - context: Context, api: API): Promise { - if (!validID(source?.run) || source.run === context.run || !validID(source.attempt) || - !Array.isArray(source.jobs) || source.jobs.length !== PROOF_SHARDS[category] || source.jobs.some(id => !validID(id)) || new Set(source.jobs).size !== PROOF_SHARDS[category] || - source.inputs?.fingerprint !== inputs.fingerprint || JSON.stringify(source.inputs) !== JSON.stringify(inputs)) throw new Error("Missing complete input equivalence"); - const run = await api.json(`actions/runs/${source.run}/attempts/${source.attempt}`); - if (run.id !== source.run || run.run_attempt !== source.attempt || run.event !== "pull_request" || - run.status !== "completed" || run.conclusion !== "success" || run.path !== ".github/workflows/ci.yml" || - run.head_branch !== context.branch || run.repository?.full_name !== context.repository || run.head_repository?.full_name !== context.headRepository || - !SHA.test(run.head_sha ?? "") || !Number.isFinite(Date.parse(run.created_at)) || Date.now() - Date.parse(run.created_at) > 7 * 86400000 || Date.parse(run.created_at) > Date.now()) throw new Error("Source is not recent successful automatic proof for this contribution"); - const page = await api.json(`actions/runs/${source.run}/attempts/${source.attempt}/jobs?per_page=100`); - if (!Array.isArray(page.jobs) || page.total_count !== page.jobs.length || page.jobs.length > 30) throw new Error("Incomplete source job inventory"); - const found: FreshReceipt[] = []; - for (const shard of shardNumbers(category)) { - const matching = page.jobs.filter((j: any) => j.name === `${category} (${shard})`); - const job = matching[0]; - if (matching.length !== 1 || job?.id !== source.jobs[shard - 1] || job.run_id !== source.run || job.head_sha !== run.head_sha || - job.status !== "completed" || job.conclusion !== "success" || - !job.steps?.some((s: any) => s.name === `Complete ${category} proof` && s.status === "completed" && s.conclusion === "success") || - !String(job.check_run_url).startsWith(`https://api.github.com/repos/${context.repository}/check-runs/`)) throw new Error("Source has no fresh successful job for every shard"); - const checkId = String(job.check_run_url).split("/").at(-1)!; - if (!/^\d+$/.test(checkId)) throw new Error("Invalid source check identity"); - const check = await api.json(`check-runs/${checkId}`); - if (String(check.id) !== checkId || check.app?.slug !== "github-actions" || check.head_sha !== run.head_sha || - check.status !== "completed" || check.conclusion !== "success") throw new Error("Source check does not establish successful execution"); - const log = await api.log(job.id); - if (!log.includes(`refs/remotes/pull/${context.pr}/merge`) && !log.includes(`refs/pull/${context.pr}/merge`)) throw new Error("Job checkout does not belong to the source pull request"); - const receipt = receiptFromLog(log, category, shard); - if (JSON.stringify(receipt.checkout) !== JSON.stringify(source.checkout) || JSON.stringify(receipt.inputs) !== JSON.stringify(inputs)) throw new Error("Job receipt has no complete input equivalence"); - found.push(receipt); - } - const commit = await api.json(`git/commits/${source.checkout.sha}`); - if (commit.sha !== source.checkout.sha || commit.tree?.sha !== source.checkout.tree || - JSON.stringify(commit.parents?.map((p: any) => p.sha)) !== JSON.stringify(source.checkout.parents) || - source.checkout.parents.length !== 2 || source.checkout.parents[1] !== run.head_sha) throw new Error("Source checkout/tree/parents do not match immutable GitHub execution"); - await ensureCommit(root, source.checkout.sha); - if (JSON.stringify(checkout(root, source.checkout.sha)) !== JSON.stringify(source.checkout) || - git(root, "rev-parse", `${source.checkout.sha}:.github/workflows/ci.yml`).trim() !== git(root, "rev-parse", "HEAD:.github/workflows/ci.yml").trim()) throw new Error("Source workflow or Git identity changed"); - const recomputed = proofInputs(root, category, normalizeInventory(source.inputs.inventory), inputs.runner, - source.checkout.sha, inputs.excluded); - if (recomputed.fingerprint !== inputs.fingerprint || JSON.stringify(recomputed.partitions) !== JSON.stringify(inputs.partitions) || found.length !== PROOF_SHARDS[category]) throw new Error("Immutable source inputs do not establish input equivalence"); -} - -export async function findRetained(root: string, selected: Record, context: Context, api: API, - inventory: ReturnType, runner: string): Promise { - const retained: Ledger["retained"] = {}; - const candidates = REUSABLE.filter(category => selected[category]); - if (!candidates.length || !runner) return retained; - const currentInputs = new Map(); - for (const category of candidates) { - try { currentInputs.set(category, proofInputs(root, category, inventory, runner)); } - catch(error) { logWorkerAuditDiagnostic(error); /* Unresolved ownership stays fresh without API lookup. */ } - } - const targets = candidates.filter(category => currentInputs.has(category)); - if (!targets.length) return retained; - const page = await api.json(`actions/workflows/ci.yml/runs?event=pull_request&status=success&branch=${encodeURIComponent(context.branch)}&per_page=3`); - if (!Array.isArray(page.workflow_runs) || page.workflow_runs.length > 3) throw new Error("Unbounded source runs"); - for (const run of page.workflow_runs) { - if (run.id === context.run || run.status !== "completed" || run.conclusion !== "success") continue; - const jobs = await api.json(`actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100`); - for (const category of targets) { - if (retained[category]) continue; - try { - const pair = shardNumbers(category).map(shard => jobs.jobs.find((j: any) => j.name === `${category} (${shard})` && j.conclusion === "success")); - if (pair.some(j => !j)) continue; // Never form transitive chains through skipped/reused jobs. - const first = receiptFromLog(await api.log(pair[0].id), category, 1); - const inputs = currentInputs.get(category)!; - const source: Source = { run: run.id, attempt: run.run_attempt, jobs: pair.map(j => j.id), checkout: first.checkout, inputs: first.inputs }; - await validateSource(root, category, source, inputs, context, api); - retained[category] = source; - } catch { /* Unknown/missing/mismatched source evidence means fresh execution. */ } - } - if (targets.every(category => retained[category])) break; - } - return retained; -} - -export async function retainedCategories(root: string, ledger: unknown, context: Context | undefined, api: API | undefined): Promise> { - const value = ledger as Ledger; - if (value?.version !== 1 || !value.retained || typeof value.retained !== "object" || Array.isArray(value.retained) || JSON.stringify(value.checkout) !== JSON.stringify(checkout(root))) throw new Error("Missing or mismatched current-head proof ledger"); - if (Object.keys(value.retained).some(key => !(REUSABLE as readonly string[]).includes(key))) throw new Error("Unknown retained proof domain"); - const accepted = new Set(); - if (!Object.keys(value.retained).length) return accepted; - if (!context || !api) throw new Error("Retention requires an automatic ready PR"); - const inventory = await browserInventory(root); - for (const category of REUSABLE) { - const source = value.retained[category]; if (!source) continue; - await validateSource(root, category, source, proofInputs(root, category, inventory, runnerIdentity()), context, api); - accepted.add(category); - } - return accepted; -} - -/** Leave headroom for the aggregate's other outputs below Linux's per-env limit. - * Measure the escaped outer JSON envelope, not just the receipt JSON bytes. */ -export function boundedLedger(ledger: Ledger): Ledger { - return Buffer.byteLength(JSON.stringify(JSON.stringify(ledger))) <= 90000 ? ledger : { ...ledger, retained: {} }; -} - -if (import.meta.main) { - try { - const root = resolve(import.meta.dir, ".."); - const plan = await Bun.file(join(root, "tmp/ci-plan.json")).json() as CheckPlan; - let ledger: Ledger = { version: 1, checkout: checkout(root), retained: {} }; - const selected = proofSelections(plan, process.env.PR_DRAFT === "true"); - const event = process.env.GITHUB_EVENT_PATH ? await Bun.file(process.env.GITHUB_EVENT_PATH).json() : {}; - const context = contextFromEvent(event, process.env); - const start = performance.now(); - if (context && process.env.GH_TOKEN && runnerIdentity() && REUSABLE.some(category => selected[category])) { - try { - if (git(root, "diff", "HEAD", "--").trim()) throw new Error("Dirty tracked inputs require fresh proof"); - ledger.retained = await findRetained(root, selected, context, new GitHubProofAPI(context.repository, process.env.GH_TOKEN), await browserInventory(root), runnerIdentity()); - } catch (error) { console.log(`Proof retention unavailable; execute fresh: ${String(error).slice(0, 200)}`); } - } - ledger = boundedLedger(ledger); - await Bun.write(join(root, "tmp/proof-reuse.json"), JSON.stringify(ledger, null, 2)); - if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, - `reuse=${JSON.stringify(ledger)}\n` + REUSABLE.map(category => `run_${category}=${selected[category] && !ledger.retained[category]}\n`).join("")); - console.log(JSON.stringify({ ...ledger, lookupSeconds: (performance.now() - start) / 1000 })); - } catch (error) { console.error(error); process.exit(1); } -} diff --git a/scripts/proof-shards.ts b/scripts/proof-shards.ts index 0631c5f082..dc56dad93f 100644 --- a/scripts/proof-shards.ts +++ b/scripts/proof-shards.ts @@ -1,5 +1,5 @@ /** Hosted shard counts for the measured browser domains. The ci.yml matrices, - * retention, weight refresh and input partitions all read this one table (#2414). */ + * the merge path's job inventory and the weight refresh all read this one table (#2414). */ export const PROOF_SHARDS = { browser: 3, layout: 2 } as const; export type ShardedDomain = keyof typeof PROOF_SHARDS; diff --git a/scripts/refresh-browser-costs.ts b/scripts/refresh-browser-costs.ts index 54e646822d..eabdb68737 100644 --- a/scripts/refresh-browser-costs.ts +++ b/scripts/refresh-browser-costs.ts @@ -3,7 +3,7 @@ import { resolve } from "node:path"; import { browserCostsFromLogs, browserTimingReports, type BrowserCosts } from "./browser-shards"; import { PROOF_SHARDS, shardNumbers } from "./proof-shards"; import { browserPinUsesProducer, parseBrowserPin, resolveBrowserPin } from "./captures/provenance"; -import type { API } from "./proof-reuse"; +import type { API } from "./proof-api"; type Domain = "browser" | "layout"; type CostTable = BrowserCosts & { measurement?: unknown; measurements?: Partial> }; @@ -11,7 +11,7 @@ const SHA = /^[a-f0-9]{40}$/; const layoutKey = (key: string) => key.startsWith("ui-react-layout::"); const cleanLog = (log: string) => log.replace(/\u001b\[[0-9;]*[A-Za-z]/g, ""); -/** Admit complete successful measurements only; retained proof is not a timing source. */ +/** Admit complete successful measurements only; a skipped or partial domain is not a timing source. */ export async function refreshBrowserCosts(domain: Domain, run: number, attempt: number, previous: CostTable, image: string, api: API): Promise { const info = await api.json(`actions/runs/${run}/attempts/${attempt}`); diff --git a/scripts/refresh-unit-costs.ts b/scripts/refresh-unit-costs.ts index 9e7c679387..bc8b615d76 100644 --- a/scripts/refresh-unit-costs.ts +++ b/scripts/refresh-unit-costs.ts @@ -3,7 +3,7 @@ import { createHash } from "node:crypto"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import type { API } from "./proof-reuse"; +import type { API } from "./proof-api"; import type { Checkout } from "./proof-inputs"; import { unitPartitionLimit } from "./proof-shards"; diff --git a/scripts/replay-browser-selection.ts b/scripts/replay-browser-selection.ts index 8fa6b997ca..cf8057cced 100644 --- a/scripts/replay-browser-selection.ts +++ b/scripts/replay-browser-selection.ts @@ -1,10 +1,15 @@ -/** Read-only replay over immutable squash diffs; no historical source speedup is implied. */ +/** Read-only replay over immutable squash diffs; no historical source speedup is implied. + * Given the report another tree produced from the same snapshot, it also lists every + * category that tree's rule selected and this one omits: the qualification a change + * to browser selection attaches (docs/process/proof-domains.md). */ import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { changedFiles, planChecks, selectBrowserClosures, workspaces } from "./ci-plan"; import { discoverBrowserClosures } from "./browser-input-closure"; -export function replayBrowserSelection(root: string, snapshot: { prs: { number: number; mergeCommit: string; changed: string[] }[] }) { +const CATEGORIES = ["browser", "layout", "endurance", "captures"] as const; +export interface ReplayBaseline { plans: { number: number; changedSha256: string; after: Record }[]; } +export function replayBrowserSelection(root: string, snapshot: { prs: { number: number; mergeCommit: string; changed: string[] }[] }, baseline?: ReplayBaseline) { if (snapshot.prs.length !== 100 || new Set(snapshot.prs.map(pr => pr.number)).size !== 100) throw new Error("Replay requires exactly 100 distinct PRs"); const packages = workspaces(root), closures = discoverBrowserClosures(root); const plans = snapshot.prs.map(pr => { @@ -14,7 +19,14 @@ export function replayBrowserSelection(root: string, snapshot: { prs: { number: const before = planChecks(changed, packages), after = selectBrowserClosures(before, closures); return { number: pr.number, mergeCommit: pr.mergeCommit, changedSha256: createHash("sha256").update(JSON.stringify(changed)).digest("hex"), before: before.local, after: after.local }; }); + const omittedSinceBaseline = baseline ? plans.flatMap(pr => { + const earlier = baseline.plans.find(plan => plan.number === pr.number); + if (!earlier || earlier.changedSha256 !== pr.changedSha256) throw new Error(`Baseline does not replay the same change: #${pr.number}`); + return CATEGORIES.filter(category => earlier.after[category] && !pr.after[category]).map(category => ({ number: pr.number, category })); + }) : undefined; + if (baseline && baseline.plans.length !== plans.length) throw new Error("Baseline replays a different PR set"); return { version: 1, plans, noLongerBrowser: plans.filter(pr => pr.before.browser && !pr.after.browser).map(pr => pr.number), + ...(omittedSinceBaseline ? { omittedSinceBaseline } : {}), domains: Object.fromEntries(Object.entries(closures).map(([category, closure]) => [category, { files: closure.files.length, directories: closure.directories?.length ?? 0, unresolved: closure.unresolved.length, closureSha256: createHash("sha256").update(JSON.stringify(closure)).digest("hex"), @@ -23,11 +35,12 @@ export function replayBrowserSelection(root: string, snapshot: { prs: { number: } if (import.meta.main) { const root = resolve(import.meta.dir, ".."); - const input = process.argv[2], output = process.argv[3]; - if (!input || !output) throw new Error("Usage: bun scripts/replay-browser-selection.ts <100-PR-snapshot.json> "); + const input = process.argv[2], output = process.argv[3], earlier = process.argv[4]; + if (!input || !output) throw new Error("Usage: bun scripts/replay-browser-selection.ts <100-PR-snapshot.json> [baseline-report.json]"); const snapshot = JSON.parse(readFileSync(input, "utf8")); - const report = replayBrowserSelection(root, snapshot); + const report = replayBrowserSelection(root, snapshot, earlier ? JSON.parse(readFileSync(earlier, "utf8")) : undefined); await Bun.write(output, JSON.stringify(report, null, 2) + "\n"); console.log(JSON.stringify({ browserBefore: report.plans.filter(pr => pr.before.browser).length, - browserAfter: report.plans.filter(pr => pr.after.browser).length, noLongerBrowser: report.noLongerBrowser, domains: report.domains }, null, 2)); + browserAfter: report.plans.filter(pr => pr.after.browser).length, noLongerBrowser: report.noLongerBrowser, + ...(report.omittedSinceBaseline ? { omittedSinceBaseline: report.omittedSinceBaseline } : {}), domains: report.domains }, null, 2)); } diff --git a/scripts/request-heavy-feedback.ts b/scripts/request-heavy-feedback.ts index 0885439a62..4412111fb8 100644 --- a/scripts/request-heavy-feedback.ts +++ b/scripts/request-heavy-feedback.ts @@ -9,7 +9,7 @@ * feedback on draft heads". */ import { FEEDBACK_WORKFLOW, requireLiveDraftHead } from "./heavy-feedback"; -import type { API } from "./proof-reuse"; +import type { API } from "./proof-api"; /** One `gh` invocation: argv plus optional stdin, resolving stdout. */ export type GH = (args: string[], input?: string) => Promise; diff --git a/scripts/source-browser-dispatch.ts b/scripts/source-browser-dispatch.ts deleted file mode 100644 index c27f51dfe9..0000000000 --- a/scripts/source-browser-dispatch.ts +++ /dev/null @@ -1,133 +0,0 @@ -/** Finite private registries retain every handler's normal runtime input audit. */ -import {createHash} from "node:crypto"; -import {existsSync,readFileSync,realpathSync} from "node:fs"; -import {resolve} from "node:path"; -import ts from "typescript"; -import type {BrowserImporters} from "./bound-browser-runtime-inputs"; -// These two consumers import/re-export runStateForFrame only. They never -// acquire the mutable chat handler map. Any consumer edit requires re-audit. -const helperConsumers:Record={ - // Re-audited for #3155: hello and every other frame also reach the account's - // attachment-reads client beside the trackers; still only runStateForFrame. - // Re-audited for #3604: safety frames route to their separate host-evidence - // driver before demux; this consumer still imports only runStateForFrame. - // Re-audited when #1362 moved inbound routing out of connection.ts: only - // runStateForFrame is imported; it never acquires or mutates chatFrameHandlers. - // Re-audited for #3812: inbound.ts gained refusalReason from lib/turn-failure.ts, - // which imports only protocol types and constants; still only runStateForFrame - // from the chat handlers. - // Re-audited for #3389: inbound.ts now dispatches the voice-owned frames - // connection-wide through dispatchServerMessage and hands the conversation - // client's receive to the context; from chat.ts it still imports only - // runStateForFrame and never acquires or mutates chatFrameHandlers. - "packages/ui-react/src/ws-client/inbound.ts":"4de90794456038a9e424c034c36c95a7c20651b529adb7a5a20d18c0490051c1", - "packages/ui-react/src/hooks/use-websocket.ts":"6edd8b289fa4dcf7f0a512ce1275bd9e9c70661ce5630e22503b4b1d888cf557" -}; -// Re-audited for #3155: chat.ts only gained `attachmentFiles` in its history -// message mapping; chatFrameHandlers and its dispatch are unchanged. -// Re-audited for #3389: index.ts only retyped dispatchServerMessage's frame -// as ConsumerServerMessage, and chat.ts only lost its `pong` no-op entry and -// union member; the registry, its spreads and its one call site are unchanged. -const declarations=[ - { - "owner": "packages/ui-react/src/hooks/websocket-handlers/index.ts", - "source": "72b7747cf4704cd16718919610d71b3aa74d17c6d5adbece3426eb5ed4da823d", - "registry": "serverMessageHandlers", - "expression": "serverMessageHandlers[msg.type](msg as never, context)", - "maps": [ - { - "owner": "packages/ui-react/src/hooks/websocket-handlers/chat.ts", - "name": "chatFrameHandlers", - "source": "e1728b598b8c187f5776e092de4be685e29912949af24171890e6a9c81130a51" - }, - { - "owner": "packages/ui-react/src/hooks/websocket-handlers/activity.ts", - "name": "activityFrameHandlers", - "source": "401e15e6b6105dc9336ca45fa57eb6d235efba19178c3e1b6f6fcd0babca6ba5" - }, - // Re-audited for #3975: the added markup_request handler, like - // mask_request, copies only the frame's own fields into the markup - // store's open(); it reads no other runtime input. - { - "owner": "packages/ui-react/src/hooks/websocket-handlers/mask.ts", - "name": "maskFrameHandlers", - "source": "a094761650c031d627ef5aa6b17011c7bae1dfd41f5888e53c6e7215812a0061" - }, - { - "owner": "packages/ui-react/src/hooks/websocket-handlers/provider.ts", - "name": "providerFrameHandlers", - "source": "0de9131781f27ba26a4469640e849170b9e063ed1d595a90361ac815128b617f" - }, - // Re-audited for #3589: the added attachment_read handler is a no-op - // that reads no runtime input, like chat_retired. Re-audited for #3155: - // only its comment changed; the reads client takes the frame instead. - // Re-audited for #3617: the added live_persona handler is a no-op that - // reads no runtime input; the conversation client takes the frame. - // Re-audited for #3616: the added live_settings handler is a no-op that - // reads no runtime input; the root conversation client reads the frame. - // Re-audited for #3389: the eight voice-owned entries (dialogue_history, - // tool_resolution, conversation_*) now only pass their frame to - // context.conversation, the conversation client's receive, which read - // the same frames from its prefilter before; they read nothing else. - { - "owner": "packages/ui-react/src/hooks/websocket-handlers/connection.ts", - "name": "connectionFrameHandlers", - "source": "76b9ca482cc1cf0d2cc990fd25bbdc4862e5e3c78b0231ead36184edb06b6f8e" - }, - { - "owner": "packages/ui-react/src/hooks/websocket-handlers/handoff.ts", - "name": "handoffFrameHandlers", - "source": "e1ff17fc6d995a81aa64e1150c560f977e1e4c6bfcfcd2a7798528e0cb96ada9" - } - ] - }, - { - "owner": "packages/ui-react/src/lib/stats/context-text.ts", - "source": "76fb1634a81ed2a794def6e9de3f69961bc50a52ab68e5a6f907f0304395956c", - "registry": "REQUIRED", - "expression": "REQUIRED[kind as StatsSection[\"kind\"]](section as Record)", - "maps": [] - } -]; -function definition(source:ts.SourceFile,name:string,privateOnly:boolean):ts.ObjectLiteralExpression|undefined { - const variables=source.statements.filter(ts.isVariableStatement).filter(statement=>!privateOnly||!statement.modifiers?.some(modifier=>modifier.kind===ts.SyntaxKind.ExportKeyword)).flatMap(statement=>statement.declarationList.flags&ts.NodeFlags.Const?[...statement.declarationList.declarations]:[]).filter(declaration=>ts.isIdentifier(declaration.name)&&declaration.name.text===name); - if(variables.length!==1)return;let value=variables[0]!.initializer; - while(value&&(ts.isSatisfiesExpression(value)||ts.isAsExpression(value)||ts.isParenthesizedExpression(value)))value=value.expression; - return value&&ts.isObjectLiteralExpression(value)?value:undefined; -} -export function sourceBrowserDispatch(root:string,files:readonly string[],importers:BrowserImporters):Map> { - const result=new Map>(); - const source=(owner:string,expected:string)=>{const path=resolve(root,owner);if(!files.includes(owner)||!existsSync(path)||realpathSync(path)!==path)return; - const bytes=readFileSync(path,"utf8");if(createHash("sha256").update(bytes).digest("hex")!==expected)return;return ts.createSourceFile(owner,bytes,ts.ScriptTarget.Latest,true);}; - for(const declaration of declarations){ - const owner=source(declaration.owner,declaration.source);if(!owner)continue; - const registry=definition(owner,declaration.registry,true);if(!registry)continue; - if(declaration.maps.length){ - if(registry.properties.length!==declaration.maps.length||registry.properties.some(property=>!ts.isSpreadAssignment(property)||!ts.isIdentifier(property.expression)||!declaration.maps.some(map=>map.name===property.expression.getText(owner))))continue; - let valid=true; - for(const map of declaration.maps){ - const ast=source(map.owner,map.source),value=ast&&definition(ast,map.name,false); - const foreign=[...(importers.get(map.owner)??[])].filter(file=>file!==declaration.owner); - if(!value||foreign.some(file=>map.name!=="chatFrameHandlers"||!helperConsumers[file]||!source(file,helperConsumers[file]!))||value.properties.some(property=>{ - if(ts.isSpreadAssignment(property)||ts.isComputedPropertyName(property.name))return true; - if(ts.isMethodDeclaration(property))return !property.body; - return !ts.isPropertyAssignment(property)||!(ts.isArrowFunction(property.initializer)||ts.isFunctionExpression(property.initializer)); - })) {valid=false;break;} - } - if(!valid)continue; - }else if(registry.properties.some(property=>!ts.isPropertyAssignment(property)||ts.isComputedPropertyName(property.name)||!(ts.isArrowFunction(property.initializer)||ts.isFunctionExpression(property.initializer))))continue; - let callSites=0,escaped=false; - const walk=(node:ts.Node)=>{ - if(ts.isIdentifier(node)&&node.text===declaration.registry){ - const parent=node.parent; - if(ts.isVariableDeclaration(parent)&&parent.name===node) { /* Private const definition. */ } - else if(ts.isElementAccessExpression(parent)&&parent.expression===node&&ts.isCallExpression(parent.parent)&&parent.parent.expression===parent&&parent.parent.getText(owner)===declaration.expression)callSites++; - else if(ts.isCallExpression(parent)&&parent.expression.getText(owner)==="Object.hasOwn"&&parent.arguments[0]===node) { /* Own-key guard, not an escaping callable. */ } - else escaped=true; - } - ts.forEachChild(node,walk); - };walk(owner); - if(callSites===1&&!escaped)result.set(declaration.owner,new Set([declaration.expression])); - } - return result; -} diff --git a/scripts/source-browser-payloads.ts b/scripts/source-browser-payloads.ts deleted file mode 100644 index 04f12905da..0000000000 --- a/scripts/source-browser-payloads.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** Two audited literal payloads contain no scripts, resource URLs, imports or external bytes. */ -import { createHash } from "node:crypto"; -import { existsSync, readFileSync, realpathSync } from "node:fs"; -import { resolve } from "node:path"; -// Literal SVG rectangle and black/white pixel probe. Exact owner and call -// identities preserve the actual Playwright sink and lexical receiver binding. -// Other HTML (including interpolated fixture payloads) remains unresolved. -const literals:Record = { - "packages/ui-kit/tests/visual/form-browser.ts": { - "source": "5def3875a8e16e41b22bf1ff2a25b045a3adc59bdc2df2e0c7754126f3c8e27b", - "expression": "route.fulfill({ status: 200, contentType: \"image/svg+xml\", body: '' })" - }, - "packages/ui-kit/tests/visual/ghost-browser.ts": { - "source": "004c45bd7261997efccc74623ee2f67db4fc832b99039bc2f49cea81e75fb799", - "expression": "page.setContent('
')" - } -}; -export function sourceBrowserPayload(root:string,owner:string,expression:string):boolean { - const declaration=literals[owner];if(!declaration||declaration.expression!==expression) return false; - const path=resolve(root,owner); - return existsSync(path)&&realpathSync(path)===path&&createHash("sha256").update(readFileSync(path)).digest("hex")===declaration.source; -} diff --git a/scripts/test-determinism.ts b/scripts/test-determinism.ts new file mode 100644 index 0000000000..e5837c144a --- /dev/null +++ b/scripts/test-determinism.ts @@ -0,0 +1,312 @@ +/** + * Repeats a change's added or modified Bun test files under CPU load (#4109). + * + * Most red-main incidents were cleared by changing only a test: a racy wait, an + * unpinned clock, a deadline a loaded shard missed. Such a test passes once and + * fails later on someone else's merge. This command runs each changed file + * several times before it merges, while busy loops occupy the CPUs. + * + * bun scripts/test-determinism.ts --base origin/main [--json] + * bun scripts/test-determinism.ts tests/a.test.ts ... # an explicit selection (hosted job) + * + * The files run in one invocation of the offline wrapper (`bun run test`, + * scripts/test.ts), so its preload, lease and single preparation build apply, + * with Bun's `--rerun-each= --bail=1`. Verified against Bun 1.4.2: each file + * runs n times in a row in one process, its module is evaluated again for each + * run, `globalThis` and process state persist between runs, and a run with + * output is headed `: (run #k)` on stderr. Under GitHub Actions the same + * header opens a log group, `::group::: (run #k)`. A file that leaks + * state into its next run therefore fails here too. + * + * Bounded: five repetitions by default, reduced uniformly to a floor of two + * when the reviewed weights (scripts/test-shard-costs.json) exceed the budget. + * No selected file is dropped; the report lists each with its repetitions. + * Policy: docs/decisions/ci-utility.md, "Changed tests repeat under load before merge". + */ +import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { availableParallelism, constants } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { changedFiles, determinismTests } from "./ci-plan"; +import { ensureHostAdmission } from "./host-admission.mjs"; +import { discoverTests, FILE_COST_SECONDS } from "./test-shards"; + +export const DEFAULT_REPETITIONS = 5; +export const FLOOR_REPETITIONS = 2; +/** Total reviewed-weight seconds the repetitions may cost before they are reduced. */ +export const BUDGET_SECONDS = 600; +/** A file without a reviewed weight costs the small-file default (scripts/test-shards.ts). */ +const UNWEIGHTED_SECONDS = 0.1; +/** A burner outlives its parent by one slice at most, and never this long. */ +const BURNER_LIFETIME_MS = 2 * 60 * 60_000, BURNER_SLICE_MS = 200; +export const REPORT_KIND = "brain-test-determinism"; +const JUNIT_PATH = "tmp/determinism-junit.xml"; + +export interface FileRepetitions { file: string; weightSeconds: number; weighted: boolean; repetitions: number; observed?: number; } +export interface RepetitionPlan { + requested: number; floor: number; repetitions: number; reduced: boolean; + budgetSeconds: number; weightSeconds: number; estimatedSeconds: number; overBudget: boolean; + files: FileRepetitions[]; +} +export interface Failure { file: string | null; repetition: number | null; test: string | null; reason: string; } +export interface Report extends RepetitionPlan { + kind: typeof REPORT_KIND; version: 1; base: string | null; + outcome: "passed" | "failed" | "none-selected"; + failure: Failure | null; load: { burners: number; cpus: number }; elapsedSeconds: number; exitCode: number; +} + +/** + * The same count for every file: the most repetitions that fit the budget, + * never more than requested and never fewer than the floor. A selection too + * heavy for the floor still runs at the floor and is reported over budget. + */ +export function planRepetitions(files: readonly string[], options: { repetitions?: number; floor?: number; budgetSeconds?: number; + costs?: Readonly> } = {}): RepetitionPlan { + const requested = options.repetitions ?? DEFAULT_REPETITIONS, floor = options.floor ?? FLOOR_REPETITIONS; + const budgetSeconds = options.budgetSeconds ?? BUDGET_SECONDS, costs = options.costs ?? FILE_COST_SECONDS; + if (!Number.isSafeInteger(floor) || floor < 2) throw new Error("The repetition floor is at least two: one run proves nothing about the next"); + if (!Number.isSafeInteger(requested) || requested < floor) throw new Error(`Repetitions must be an integer of at least ${floor}`); + if (!Number.isFinite(budgetSeconds) || budgetSeconds <= 0) throw new Error("The time budget must be positive seconds"); + if (new Set(files).size !== files.length) throw new Error("A test file was selected twice"); + const weights = files.map(file => { + const weighted = Object.hasOwn(costs, file), weightSeconds = weighted ? costs[file]! : UNWEIGHTED_SECONDS; + if (!Number.isFinite(weightSeconds) || weightSeconds <= 0) throw new Error(`Test file costs must be positive finite seconds: ${file}`); + return { file, weightSeconds, weighted }; + }); + const weightSeconds = weights.reduce((sum, entry) => sum + entry.weightSeconds, 0); + const fit = weightSeconds > 0 ? Math.floor(budgetSeconds / weightSeconds) : requested; + const repetitions = Math.max(floor, Math.min(requested, fit)); + const estimatedSeconds = weightSeconds * repetitions; + return { requested, floor, repetitions, reduced: repetitions < requested, budgetSeconds, weightSeconds, estimatedSeconds, + overBudget: estimatedSeconds > budgetSeconds, files: weights.map(entry => ({ ...entry, repetitions })) }; +} + +/** The wrapper's argv: one invocation, so preparation builds once for every repetition. */ +export function repetitionArgv(files: readonly string[], repetitions: number): string[] { + return [process.execPath, "run", "test", `--rerun-each=${repetitions}`, "--bail=1", + "--reporter=junit", `--reporter-outfile=${JUNIT_PATH}`, ...files.map(file => `./${file}`)]; +} + +const plain = (text: string) => text.replace(/\x1b\[[0-9;]*m/g, ""); + +/** + * The first failure in the wrapper's stderr: Bun heads a run's output with + * `: (run #k)`, as a `::group::` annotation under GitHub Actions, and + * reports the case as `(fail) [