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 2dd6fbe090..45b63c5bb4 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, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b17e0d5f53..c2c25d2431 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: @@ -38,9 +37,6 @@ 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 }} red_main_oid: ${{ steps.plan.outputs.red_main_oid }} steps: - uses: actions/checkout@v7 @@ -74,14 +70,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 +88,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@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 +410,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 +475,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: diff --git a/.github/workflows/heavy-feedback.yml b/.github/workflows/heavy-feedback.yml index 5322a51276..9cbcda8285 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,6 @@ 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 }}" red_main_oid: "${{ steps.plan.outputs.red_main_oid }}" base_sha: "${{ steps.admit.outputs.base_sha }}" steps: @@ -88,9 +85,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 +299,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 +338,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: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ca628ae45f..3a86ae43f0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -84,30 +84,28 @@ Before instrumenting installed dependencies, follow [dependency diagnostic preparation](docs/process/diagnostic-installs.md): worktrees alone do not isolate Bun cache hardlinks. -The frozen native diagram control also requires the independently qualified -installation bytes and modes. An `installation-mismatch` with matching frozen -source is an install problem: keep its source revision, 859-file inventory and -qualification fingerprints unchanged. A frozen lockfile does not repair a -modified shared package cache, and copying that cache copies the modifications -([#1980](https://github.com/schlessera/brain-kit/issues/1980)). Recover only the -owned checkout through a fresh private cache and independent file copies, -**under umask `022`**. The installation identity includes file modes, and the -installer's umask narrows them. The qualified install was made under `022`, so -an install under any other umask, such as `0077`, never matches, even though its -package, file and byte counts are identical. The preparation script sets its own umask so -your own umask is unchanged: +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 +a fresh private cache and independent file copies, under umask `022`; the +preparation script sets its own umask so yours is unchanged: ```sh # Preserve evidence and move aside this owned checkout's node_modules first. sh scripts/prepare-diagnostic-install.sh -bun run test ./tests/native-diagram-inputs.test.ts ``` -Retain the failed and restored installation identities. Verify any suspected -package edits against the lockfile's archive integrity; never normalize unknown -bytes or modes to force qualification. Leave shared caches and other checkouts -alone. Use the same preparation before future dependency instrumentation; retain the -original failure evidence as described in the diagnostic guide. +Verify any suspected package edits against the lockfile's archive integrity; +never normalize unknown bytes or modes to force a pass. Leave shared caches and +other checkouts alone. Use the same preparation before future dependency +instrumentation; retain the original failure evidence as described in the +diagnostic guide. The Linux backend nonpersistence tests require `bubblewrap` and permitted user namespaces. They launch the installed Claude and pi adapters with a loopback @@ -241,7 +239,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 @@ -296,7 +294,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 530166972e..33d65cad72 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 @@ -538,8 +550,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 @@ -668,9 +680,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 @@ -925,130 +935,93 @@ 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 native diagram SVG/PNG/PDF fixture has a separate finite operation binding. +**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. + +**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 @@ -1056,12 +1029,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. @@ -1084,177 +1055,34 @@ retains the original SVG/reference zero-request replay and raster/font/PDF assertions. Different launches never share a prepared output root. The browser-side pinned font cache remains a separately owned browser input. -Qualification is tied to the exact operation, source and installed identities; -unknown readers, drift or missing inputs retain complete fresh proof. The fresh -shard independently passes its computed identity to host preparation and checks -installation/runtime identity again before emitting its existing receipt. Both -shards, independent immutable source/current validation and whole-workflow -successful eligibility retain the existing complete-domain protocol. 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. +**The frozen qualification is retired (maintainer, 2026-11-16, +[#4105](https://github.com/schlessera/brain-kit/issues/4105)).** #2293 pinned the +producer's source (`e8502b6f…`, the frozen #2293 snapshot), its installation +(a hash over every package, file, byte and mode in `node_modules`) and three +source files. That let a ready PR retain browser proof from an earlier green +run. The pin no longer protected anything live: + +- Under the [hybrid ruling](#hybrid-post-merge-heavy-proof), ready confirmation + no longer runs browser proof, and the squash's main run is always fresh. +- All three pinned source files had drifted, so the binding could not qualify + on the current tree in any case. +- Any dependency change moved the installation hash and turned `unit` red. That + needed a manual requalification run on a Docker host and a second merge + cycle. It happened three times (#3320, #3968, #4102), and the frozen + producer's SVG and PNG came out byte-identical every time. + +The binding (`scripts/native-diagram-inputs.ts`) and its self-test are +removed, and the browser input closure no longer binds the producer's reads. +The browser domain therefore always runs fresh. This supersedes the +requalification rulings of 2026-11-02 (#2509/#3320) and 2026-11-11 (#3968). +The container boundary above, the producer's own run-time identity checks and +the browser's validation of the handoff are unchanged. 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 @@ -1263,9 +1091,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). @@ -1646,7 +1473,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. @@ -1775,7 +1603,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)). @@ -1815,7 +1643,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:417-426`) 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. @@ -2006,7 +1834,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 056937e3cd..b652180ca5 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 16267cfc63..0df4b21774 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:355-356`): any path + number of files (`const packageCode`, `scripts/ci-plan.ts:348-349`): 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 6c59997057..e9db7c392a 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/diagnostic-installs.md b/docs/process/diagnostic-installs.md index af12fbe708..c6a72d652c 100644 --- a/docs/process/diagnostic-installs.md +++ b/docs/process/diagnostic-installs.md @@ -35,8 +35,7 @@ copy alone proves neither provenance nor pristine package bytes. Keep the original and recovered observations separate. Do not change package versions, locks, assertions, qualification pins or file modes to force a pass. Rebuild as required and rerun the original focused check through its offline -wrapper. For the frozen native diagram fixture, retain the failed/restored -installation identities and run `bun run test ./tests/native-diagram-inputs.test.ts`. +wrapper. Once evidence is retained and no process uses it, remove only the owned old installation. Never delete or repair shared caches while others may use them. Repeat preparation before a new independent diagnostic; an installation you 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/testing.md b/docs/process/testing.md index bf7d70c538..8f254352f9 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 @@ -655,17 +655,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. @@ -817,7 +814,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). @@ -831,18 +828,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 7c0a9485e6..d608c05503 100644 --- a/scripts/browser-input-closure.ts +++ b/scripts/browser-input-closure.ts @@ -1,18 +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 { nativeDiagramInputs, type NativeDiagramIdentity, type NativeDiagramDiagnostic } from "./native-diagram-inputs"; -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"; @@ -27,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[]; nativeDiagram?:NativeDiagramIdentity; nativeDiagramDiagnostic?:NativeDiagramDiagnostic; 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"]); @@ -37,36 +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 nativeBinding:ReturnType; - let nativeDiagramDiagnostic:NativeDiagramDiagnostic|undefined; - 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); - nativeBinding = nativeDiagramInputs(root, audit.files, importers,value=>{nativeDiagramDiagnostic=value;}); - } - 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))) { @@ -82,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; } @@ -95,10 +64,10 @@ 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 native inputs. + if (scanOnly) return; // Byte inventories: Tailwind text or exact mount-bound inputs. if (file.endsWith(".css")) { const css = cssInputs(readFileSync(absolute, "utf8")); const uses = new Set(); @@ -123,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; @@ -141,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[] = []; @@ -204,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); @@ -227,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); @@ -266,51 +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 boundNative = nativeBinding?.sites.get(normalized)?.has(expression)===true; - if(boundNative)for(const target of nativeBinding!.files)visit(target,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 && !boundNative) 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 { ...(nativeBinding?{nativeDiagram:nativeBinding.identity}:{}), ...(nativeDiagramDiagnostic?{nativeDiagramDiagnostic}:{}), 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 e3226e5ddd..0000000000 --- a/scripts/browser-worker-audit.json +++ /dev/null @@ -1,56 +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.", - "native": { - "source": "e8502b6ffb3c575f2e9a1c93dea8dbf5ceda93ece367da9d542cb10b1c9ac32b", - "installation": "0c2758c046f2b69d5f33b66521baf3098db5f44256b73ec96961c98d381e6245", - "trackedInputs": 859, - "packages": 843, - "installedBytes": 1833832361, - "runtime": "bf65590d9d594d238c2c7b6e01e038a26402a676ccf16a1caf596f1179bdc9fb" - } - }, - "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 8d5db6ee5e..0000000000 --- a/scripts/browser-worker-audit.ts +++ /dev/null @@ -1,75 +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??[],...(closure.nativeDiagram?{nativeDiagram:closure.nativeDiagram}:{}),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 expectedNative=Object.fromEntries(["source","installation","runtime"].flatMap(key=>typeof audit?.sourceAudit?.native?.[key]==="string"&&/^[a-f0-9]{64}$/.test(audit.sourceAudit.native[key])?[[key,audit.sourceAudit.native[key]]]:[])); - 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,expectedNative,native:closure.nativeDiagramDiagnostic,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"); @@ -56,10 +56,11 @@ export function workflowProblems(text: string, file: string): string[] { 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 ?? []; @@ -88,7 +89,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)) || @@ -102,7 +103,6 @@ export function workflowProblems(text: string, file: string): string[] { 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"); @@ -161,7 +161,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-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 d199e2c85b..595cb54d5d 100644 --- a/scripts/ci-plan.ts +++ b/scripts/ci-plan.ts @@ -25,7 +25,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", @@ -78,10 +77,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": [/.+/], @@ -131,8 +126,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 { diff --git a/scripts/ci-proof.ts b/scripts/ci-proof.ts index 9d354e1447..2deb6d25dc 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,22 @@ 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"; -/** Aggregate requires passed selected jobs; missing/false-looking output is not proof. */ -export function proofProblems(needs: Record }>, retained: ReadonlySet = new Set()): string[] { +/** 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; @@ -83,16 +78,12 @@ 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, ".."); @@ -106,25 +97,18 @@ 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)); + checkout: { sha, tree, parents }, plan, files: category === "unit" ? unitFiles(plan, root, shard) : undefined }, null, 2)); const native = category === "unit" || category === "runtime" || category === "runtime_host"; 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", 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. @@ -176,11 +160,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 e2566a6bc2..4d3c501c45 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 c5d32b331c..abd243db4d 100644 --- a/scripts/heavy-feedback-workflow.ts +++ b/scripts/heavy-feedback-workflow.ts @@ -50,7 +50,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: { @@ -61,7 +60,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: { @@ -85,7 +84,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 823af8c197..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 ?? [], ...(closure.nativeDiagram?{nativeDiagram:closure.nativeDiagram}:{}), files }; - return { version: 2, category, runner, inventory, partitions, excluded: [], ...(closure.nativeDiagram?{nativeDiagram:closure.nativeDiagram}:{}), - 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 1a9af0bdf2..b26f27f595 100644 --- a/scripts/integrate.ts +++ b/scripts/integrate.ts @@ -8,7 +8,7 @@ import { declareFix, gateDecision, recordExpedited, type RedMainRecord } from ". 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 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 6501bbd46e..33eea4941a 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 { shardNumbers } 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/native-diagram-inputs.ts b/scripts/native-diagram-inputs.ts deleted file mode 100644 index 5001b073f4..0000000000 --- a/scripts/native-diagram-inputs.ts +++ /dev/null @@ -1,92 +0,0 @@ -/** One fixed mount-bound native SVG/PNG/PDF operation; drift keeps fresh proof. */ -import {createHash} from "node:crypto"; -import {existsSync,lstatSync,readFileSync,readdirSync,realpathSync} from "node:fs"; -import {resolve} from "node:path"; -import {diagramSourceDomains,diagramSourceSetup,diagramSourceIdentity} from "./diagram-export-source.mjs"; -import {diagramInstallationIdentity} from "./diagram-export-installation.mjs"; -import {diagramProducerRuntime} from "./diagram-export-producer.mjs"; -import type {BrowserImporters} from "./bound-browser-runtime-inputs"; -export interface NativeDiagramIdentity {source:string;installation:string;runtime:string;} -export interface NativeDiagramDiagnostic { - version:1;status:string;stage:string;expected:{source:string;installation:string}; - actual?:Partial;sourceInputs?:number; - installation?:{packages:number;files:number;bytes:number}; - pins?:{path:string;expected:string;actual?:string;owned:boolean}[];errorCode?:string;recovery?:string; -} - -// Candidate qualification is exact: all source/installation drift requires fresh -// execution and requalification. The separate Docker mount boundary closes -// active initialization/shared-library reads; byte hashes alone do not. -const qualified:Omit={source:"e8502b6ffb3c575f2e9a1c93dea8dbf5ceda93ece367da9d542cb10b1c9ac32b",installation:"ea866695f2a83f9da2fcf18e75e95e936668ecb28e1449845a2584aa1025b728"}; -// The installation identity includes file modes, which the installer's umask -// narrows: the qualified install was made under umask 022, and any other umask -// (such as 0077) can never match. Recovery replaces only this owned install. -const installationRecovery="Preserve evidence and move aside this owned checkout's node_modules, then run sh scripts/prepare-diagnostic-install.sh. It sets umask 022 and installs the unchanged lock through a fresh private cache and copyfile. The installation identity includes file modes, so an install under any other umask (such as 0077) never matches. See CONTRIBUTING.md; never refresh qualification pins."; -const caller="packages/ui-kit/vitest.config.ts",owner="packages/ui-react/tests/browser/diagram-export-command.ts"; -const sourcePins:Record={ - "packages/ui-kit/vitest.config.ts": "e724696a55955e9f32d396b2031214600086533c3f9b8baabcc1c6bb7311f1db", - "packages/ui-react/tests/browser/diagram-export-command.ts": "f7c3d14ccf96438bf4e28ecc1929b1208fb99520d21a9947086bb43bca933328", - "scripts/ci-proof.ts": "c58de06eba788b6b892416ddda3abb28fa1e8e908f25c0800482fbe05e0de678" -}; -/** The same complete source family the trusted host preparer enumerates. */ -export function nativeDiagramSourceInventory(root:string){ - const inputs:{path:string;mode:string;sha256:string}[]=[]; - const read=(path:string)=>{const absolute=resolve(root,path),stat=lstatSync(absolute); - if(realpathSync(absolute)!==absolute||stat.isSymbolicLink())throw Error("Unsupported native source alias"); - if(stat.isDirectory()){for(const entry of readdirSync(absolute).sort())read(`${path}/${entry}`);} - else if(stat.isFile())inputs.push({path,mode:stat.mode&0o111?"100755":"100644",sha256:createHash("sha256").update(readFileSync(absolute)).digest("hex")}); - else throw Error("Unsupported native source entry");}; - for(const file of diagramSourceSetup)read(file); - for(const domain of diagramSourceDomains)read(`packages/${domain}`); - return{inputs,sha256:diagramSourceIdentity(inputs)}; -} -/** Input identity supplements the existing complete fresh-shard receipt. */ -export function nativeDiagramInputs(root:string,files:readonly string[],importers:BrowserImporters,observe?:(value:NativeDiagramDiagnostic)=>void){ - const diagnostic:NativeDiagramDiagnostic={version:1,status:"unavailable",stage:"role",expected:{...qualified}}; - const report=()=>observe?.(diagnostic); - if(![caller,owner].every(path=>files.includes(path)))return; - if(!qualified.source||!qualified.installation||[...(importers.get(owner)??[])].some(path=>path!==caller)){diagnostic.status="unsealed-role";report();return;} - try{ - diagnostic.stage="pins"; - diagnostic.pins=Object.entries(sourcePins).map(([path,expected])=>{const absolute=resolve(root,path),owned=existsSync(absolute)&&realpathSync(absolute)===absolute;return{path,expected,owned,...(owned?{actual:createHash("sha256").update(readFileSync(absolute)).digest("hex")}:{} )};}); - if(diagnostic.pins.some(pin=>!pin.owned||pin.actual!==pin.expected)){diagnostic.status="source-pin-mismatch";report();return;} - diagnostic.stage="source";const source=nativeDiagramSourceInventory(root);diagnostic.actual={source:source.sha256};diagnostic.sourceInputs=source.inputs.length; - diagnostic.stage="installation";const installation=diagramInstallationIdentity(root);diagnostic.actual.installation=installation.sha256;diagnostic.installation={packages:installation.packages,files:installation.files,bytes:installation.bytes}; - diagnostic.stage="runtime";const runtime=diagramProducerRuntime();diagnostic.actual.runtime=runtime.sha256; - if(source.sha256!==qualified.source||installation.sha256!==qualified.installation){if(source.sha256!==qualified.source)diagnostic.status="source-mismatch";else{diagnostic.status="installation-mismatch";diagnostic.recovery=installationRecovery;}report();return;} - const sites=new Map>([ - [owner,new Set([ - "readFileSync(resolve(prepared,\"producer.json\"),\"utf8\")", - "readFileSync(resolve(prepared,name))", - "readFileSync(resolve(directory,\"release.svg\"),\"utf8\")", - "readFileSync(resolve(directory,\"release.png\"))", - "page.setContent(`${svg}`)" -])], - ["scripts/diagram-export-producer.mjs",new Set([ - "accessSync(path,constants.X_OK)", - "statSync(path)", - "readFileSync(executable)", - "readFileSync(join(repo,\"tmp/diagram-export-source.json\"),\"utf8\")", - "readdirSync(join(repo,\"node_modules\"))", - "readdirSync(join(repo,\"node_modules\",top))", - "spawnSync(\"docker\",[\"run\",\"--rm\",\"--pull=never\",\"--read-only\",\"--network=none\",\"--shm-size=256m\",\"--user\",`${process.getuid()}:${process.getgid()}`,\"--tmpfs\",\"/tmp:rw,exec,nosuid,nodev,mode=1777\",\"-v\",`${source}:${source}:ro`,\"-v\",`${modules}:${join(repo,\"node_modules\")}:ro`,\"-v\",`${executable}:/usr/local/bin/bun:ro`,\"-v\",`${output}:/proof`,\"-w\",source,\"-e\",\"HOME=/tmp/home\",runtime.image,\"/usr/local/bin/bun\",\"-e\",program],{encoding:\"utf8\",maxBuffer:4*1024*1024})", - "readFileSync(join(output,name))" -])], - ["scripts/diagram-export-source.mjs",new Set([ - 'readFileSync(archivePath(repo))','existsSync(target)','lstatSync(source)','readFileSync(source)', - 'readFileSync(join(target,"packages",name,"package.json"),"utf8")','existsSync(installed)', - 'readdirSync(join(repo,"node_modules"))','readdirSync(join(repo,"node_modules",entry))' - ])], - ["scripts/diagram-export-installation.mjs",new Set([ - 'lstatSync(absolute)','lstatSync(real)','readlinkSync(absolute)','readdirSync(absolute)','readFileSync(absolute)', - 'readdirSync(join(repo,"node_modules"))','readdirSync(join(repo,"node_modules",top))','readFileSync(join(base,"package.json"),"utf8")' - ])] - ]); - diagnostic.status="qualified";diagnostic.stage="complete";report(); - return{identity:{source:source.sha256,installation:installation.sha256,runtime:runtime.sha256},files:source.inputs.map(entry=>entry.path),sites}; - }catch(error){ - const safeMessages=["Unsupported native dependency alias","Unbounded native dependency inventory","Unsupported native dependency entry","Unbounded native dependency packages","NATIVE_DEPENDENCY_ORIGIN_CHANGED","Unsupported native dependency identity"]; - const message=error instanceof Error?error.message:""; - diagnostic.errorCode=safeMessages.includes(message)?message.replaceAll(" ","_").toUpperCase():"UNAVAILABLE";report();return; - } -} 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 b1fa7b2ee6..da583cdf90 100644 --- a/scripts/proof-inputs.ts +++ b/scripts/proof-inputs.ts @@ -1,18 +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[]; - 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()}`); @@ -23,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 }) => { @@ -39,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); @@ -118,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(); @@ -137,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 8ea658395e..f40593456f 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 5940bcfaee..5450a71f75 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"; export interface UnitEvidenceAPI extends API { 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-shard-costs.json b/scripts/test-shard-costs.json index f3c0bfeece..4c001f8fe2 100644 --- a/scripts/test-shard-costs.json +++ b/scripts/test-shard-costs.json @@ -1016,16 +1016,12 @@ "tests/autonomous-dispatch.test.ts": 29.688, "tests/autonomous-runtime.test.ts": 48.58, "tests/bin-modes.test.ts": 0.1, - "tests/bound-browser-documents.test.ts": 26.329, - "tests/bound-browser-runtime-inputs.test.ts": 0.276, "tests/brain-db-contract.test.ts": 0.256, "tests/bridge-tools.test.ts": 0.217, - "tests/browser-command-activation.test.ts": 0.153, "tests/browser-image-pin.test.ts": 0.138, "tests/browser-input-closure.test.ts": 3.34, "tests/browser-inventory-process.test.ts": 3.253, "tests/browser-shards.test.ts": 0.139, - "tests/browser-worker-audit.test.ts": 0.107, "tests/browser-worker-boundary.test.ts": 0.1, "tests/build-concurrency.test.ts": 16.85, "tests/build-freshness.test.ts": 27.867, @@ -1082,8 +1078,6 @@ "tests/font-cache-binding.test.ts": 0.1, "tests/frontmatter-parse-gate.test.ts": 4.853, "tests/generated-audio-input.test.ts": 0.103, - "tests/generated-build-inputs.test.ts": 0.552, - "tests/generated-theme-inputs.test.ts": 1.463, "tests/geo-render.test.ts": 2.895, "tests/haiku-model-selection.test.ts": 0.1, "tests/hosted-proof.test.ts": 5.722, @@ -1092,7 +1086,6 @@ "tests/hygiene-reconcile-shipped.test.ts": 0.458, "tests/hygiene-screenshot-retention.test.ts": 0.1, "tests/inbox-actions-stream.test.ts": 0.665, - "tests/inclusion-inputs.test.ts": 3.313, "tests/index-query-consumers.test.ts": 9.305, "tests/installed-turn-surface.test.ts": 0.637, "tests/integration-command.test.ts": 18.773, @@ -1106,7 +1099,6 @@ "tests/layer-direction-gate.test.ts": 0.1, "tests/leakage-gate.test.ts": 0.84, "tests/local-checks.test.ts": 2.659, - "tests/locked-browser-assets.test.ts": 0.1, "tests/lockfile.test.ts": 0.1, "tests/manual-only-skills.test.ts": 0.1, "tests/markdown-anchors.test.ts": 0.1, @@ -1115,7 +1107,6 @@ "tests/module-hygiene-queries.test.ts": 0.785, "tests/module-public-imports.test.ts": 0.1, "tests/native-dead-root-trace.test.ts": 0.1, - "tests/native-diagram-inputs.test.ts": 18.314, "tests/native-event-log.test.ts": 0.1, "tests/offline-test-launcher.test.ts": 0.123, "tests/opportunity-cli-agreement.test.ts": 2.381, @@ -1132,7 +1123,6 @@ "tests/project-sync-main.test.ts": 0.1, "tests/proof-case-report.test.ts": 3.134, "tests/proof-inventory.test.ts": 10.253, - "tests/proof-reuse.test.ts": 2.912, "tests/prose-links-render.test.tsx": 3.412, "tests/public-docs.test.ts": 1.889, "tests/raw-buttons-gate.test.ts": 0.61, @@ -1149,8 +1139,6 @@ "tests/shipped-claude-runtime-pin.test.ts": 0.1, "tests/shipped-skills-lint.test.ts": 0.1, "tests/show-block-schema-forms.test.ts": 0.1, - "tests/source-browser-dispatch.test.ts": 0.171, - "tests/source-browser-payloads.test.ts": 0.1, "tests/stats-answer-render.test.tsx": 1.727, "tests/subscription-completions.test.ts": 0.1, "tests/suggestions-strict-input.test.ts": 0.1, diff --git a/tests/bound-browser-documents.test.ts b/tests/bound-browser-documents.test.ts deleted file mode 100644 index e2ef430ca3..0000000000 --- a/tests/bound-browser-documents.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import {frozenBrowserFiles,frozenBrowserSource} from "./frozen-browser-source"; -import {afterEach,expect,test} from "bun:test"; -import {mkdirSync,mkdtempSync,readFileSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; -import {tmpdir} from "node:os"; -import {dirname,join,resolve} from "node:path"; -import {browserImporters} from "../scripts/bound-browser-runtime-inputs"; -import ts from "typescript"; -import {boundBrowserDocuments,browserDocumentRefusals,reviewedBrowserDocuments} from "../scripts/bound-browser-documents"; -const repo=resolve(import.meta.dir,".."),roots:string[]=[],owner="packages/ui-kit/tests/visual/form-browser.ts",caller="packages/ui-react/tests/browser/destination-press.pointer.tsx",config="packages/ui-kit/vitest.config.ts",files=[owner,caller,config]; -afterEach(()=>{for(const root of roots.splice(0))rmSync(root,{recursive:true,force:true});}); -function fixture(extra:readonly string[]=[]){const root=mkdtempSync(join(tmpdir(),"bound-browser-documents-"));roots.push(root);const write=(file:string,text:string)=>{mkdirSync(dirname(join(root,file)),{recursive:true});writeFileSync(join(root,file),text);};symlinkSync(join(repo,"node_modules"),join(root,"node_modules"),"dir");for(const file of [...files,...extra])write(file,frozenBrowserSource(file).toString("utf8"));return{root,write};} -test("the exact HTML fixture has only source-owned reporting document and cleanup calls",()=>{ - const {root}=fixture(),bound=boundBrowserDocuments(root,files,browserImporters(root,files)); - expect([...bound.get(owner)!.values()]).toEqual([{runtime:[caller],bytes:[]}]); -}); -test("additional direct, renamed and dynamic command callers cannot supply unchecked HTML",()=>{ - for(const source of [ - 'import {commands} from "vitest/browser"; commands.htmlPreviewFixture("x", external);', - 'import {commands as api} from "vitest/browser"; api.htmlPreviewFixture("x", external);', - "const {commands: api}=await import('vitest/browser'); api.htmlPreviewFixture('x',external);", - ]){const {root,write}=fixture();write("extra.ts",source);const selected=[...files,"extra.ts"];expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(owner)).toBe(false);} -}); -test("producer/caller/config edits or direct command-owner imports require fresh input proof",()=>{ - for(const file of files){const {root,write}=fixture();write(file,readFileSync(join(root,file),"utf8")+"\n// origin drift\n");expect(boundBrowserDocuments(root,files,browserImporters(root,files)).has(owner)).toBe(false);} - const {root,write}=fixture();write("extra.ts",`import {htmlPreviewFixture} from "./${owner}";`);const selected=[...files,"extra.ts"];expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(owner)).toBe(false); -}); -const ghost="packages/ui-kit/tests/visual/ghost-browser.ts",ghostCaller="packages/ui-kit/tests/visual/ghost-sweep.visual.tsx",guard="packages/ui-kit/tests/visual/zero-request-replay.ts"; -const ghostFiles=[ghost,ghostCaller,guard,"packages/ui-kit/stories/states/GhostSweep.stories.tsx","packages/ui-kit/.storybook/preview.ts","packages/ui-kit/.storybook/preview.css","packages/ui-kit/tests/visual/design-font-setup.ts","packages/ui-kit/tests/visual/design-font-checks.ts","packages/ui-kit/tests/visual/rank-footer-browser.ts","scripts/captures/fonts.ts","scripts/captures/font-lock.json","scripts/captures/fonts.css","packages/ui-kit/.storybook/preview-head.html"]; -test("argument-free replay binds its Performance producer, zero-request guard and verified inline fonts",()=>{ - const {root}=fixture(ghostFiles),selected=[...files,...ghostFiles],bound=boundBrowserDocuments(root,selected,browserImporters(root,selected)); - const inputs=[...bound.get(ghost)!.values()][0]!;expect(inputs.runtime).toContain(guard);expect(inputs.runtime).toContain(ghostCaller);expect(inputs.bytes).toContain("scripts/captures/fonts.css"); -}); -test("replay caller, guard, CSS and font-origin drift or an additional caller stays unknown",()=>{ - for(const file of [ghostCaller,guard,"packages/ui-kit/.storybook/preview.css","scripts/captures/fonts.css"]){const {root,write}=fixture(ghostFiles),selected=[...files,...ghostFiles];write(file,readFileSync(join(root,file),"utf8")+"\n/* drift */\n");expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(ghost)).toBe(false);} - const {root,write}=fixture(ghostFiles);write("extra.ts",'import {commands} from "vitest/browser"; commands.ghostTrace();');const selected=[...files,...ghostFiles,"extra.ts"];expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(ghost)).toBe(false); -}); - -const diagram="packages/ui-react/tests/browser/diagram-proof-command.ts",diagramCaller="packages/ui-react/tests/browser/diagrams-renderer.layout.tsx"; -const sceneCaller="packages/ui-react/tests/browser/diagrams-scene-bounds.layout.tsx",sceneFixture="packages/module-diagrams/tests/fixtures/origin-group.ts"; -const diagramFiles=[diagram,diagramCaller,sceneCaller,sceneFixture,"packages/ui-react/tests/browser/diagrams-callouts.layout.tsx","packages/module-diagrams/tests/fixtures/callouts.ts","packages/ui-react/tests/browser/diagrams-axis.layout.tsx","packages/ui-react/tests/browser/diagrams-positional.layout.tsx","packages/ui-react/tests/browser/diagrams-node-link.layout.tsx",...frozenBrowserFiles("packages/module-diagrams/skills/diagram/references/examples").filter(file=>file.endsWith(".yaml")),"packages/module-diagrams/tests/fixtures/axis-examples.ts",guard,"packages/ui-kit/tests/visual/form-browser.ts","packages/ui-kit/tests/visual/design-font-setup.ts","packages/ui-kit/tests/visual/design-font-checks.ts","packages/ui-kit/tests/visual/rank-footer-browser.ts","scripts/captures/fonts.ts","scripts/captures/font-lock.json","scripts/captures/fonts.css","packages/ui-kit/.storybook/preview-head.html","packages/module-diagrams/tests/fixtures/renderer-fixture.ts","packages/module-diagrams/tests/fixtures/adopted-homecoming-relay.diagram.yaml",...frozenBrowserFiles("packages/module-diagrams/src").filter(file=>/^packages\/module-diagrams\/src\/[^/]+\.tsx?$/.test(file))]; -test("diagram replay binds all six exact callers and every SVG, fixture, CSS and inline-font producer",()=>{ - const {root}=fixture(diagramFiles),selected=[...files,...diagramFiles],bound=boundBrowserDocuments(root,selected,browserImporters(root,selected)); - expect(bound.has(diagram),"REVIEWED_DIAGRAM_DOCUMENT_BINDS").toBe(true); - const input=[...bound.get(diagram)!.values()][0]!;expect(input.runtime).toContain(diagramCaller);expect(input.runtime,"SCENE_CALLER_INCLUDED").toContain(sceneCaller);expect(input.runtime,"SCENE_FIXTURE_INCLUDED").toContain(sceneFixture);expect(input.runtime,"SCENE_FLATTEN_INCLUDED").toContain("packages/module-diagrams/src/flatten.ts");for(const file of ["packages/ui-react/tests/browser/diagrams-callouts.layout.tsx","packages/module-diagrams/tests/fixtures/callouts.ts","packages/module-diagrams/src/callout-path.ts","packages/module-diagrams/src/callouts.ts","packages/module-diagrams/src/legend.ts"])expect(input.runtime,"REVIEWED_CALLOUT_PRODUCER_INCLUDED").toContain(file);expect(input.runtime).toContain("packages/ui-react/tests/browser/diagrams-positional.layout.tsx");expect(input.runtime).toContain("packages/ui-react/tests/browser/diagrams-node-link.layout.tsx");expect(input.runtime).toContain("packages/module-diagrams/src/svg-model.ts");expect(input.runtime).toContain(guard);expect(input.bytes).toContain("packages/module-diagrams/tests/fixtures/adopted-homecoming-relay.diagram.yaml"); -}); -test("changing the reviewed HTML sink to an unchecked argument refuses diagram binding",()=>{ - const {root,write}=fixture(diagramFiles),selected=[...files,...diagramFiles]; - expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(diagram),"CONTROL_REVIEWED_DOCUMENT_BINDS").toBe(true); - const source=readFileSync(join(root,diagram),"utf8"); - const changed=source.replace("${drawing.html}","${externalHtml}"); - expect(changed).not.toBe(source); - write(diagram,changed); - expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(diagram),"UNCHECKED_HTML_SINK_REFUSED").toBe(false); -}); -test("diagram caller, renderer, fixture, guard and font drift or extra caller refuse document binding",()=>{ - for(const file of [diagram,diagramCaller,"packages/ui-react/tests/browser/diagrams-axis.layout.tsx","packages/ui-react/tests/browser/diagrams-positional.layout.tsx","packages/ui-react/tests/browser/diagrams-node-link.layout.tsx","packages/module-diagrams/skills/diagram/references/examples/architecture.diagram.yaml","packages/module-diagrams/src/svg-model.ts","packages/module-diagrams/tests/fixtures/adopted-homecoming-relay.diagram.yaml",guard,"scripts/captures/fonts.css"]){const {root,write}=fixture(diagramFiles),selected=[...files,...diagramFiles];write(file,readFileSync(join(root,file),"utf8")+"\n/* drift */\n");expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(diagram)).toBe(false);} - const {root,write}=fixture(diagramFiles);write("extra.ts",'import {commands as api} from "vitest/browser"; api.diagramCapture("figure","new");');const selected=[...files,...diagramFiles,"extra.ts"];expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(diagram)).toBe(false); -}); - -const exportOwner="packages/ui-react/tests/browser/diagram-export-command.ts",exportCaller="packages/ui-react/tests/browser/diagrams-export.layout.tsx"; -const exportFiles=[...diagramFiles,exportOwner,exportCaller,...[2,4,6,7].map(face=>`packages/module-diagrams/assets/fonts/${face}.ttf`)]; -function exportFixture(){const {root,write}=fixture();for(const file of exportFiles){mkdirSync(dirname(join(root,file)),{recursive:true});writeFileSync(join(root,file),frozenBrowserSource(file));}return{root,write};} -test("export raster replay binds actual flattening, SVG inputs and four bundled font blobs",()=>{ - const {root}=exportFixture(),selected=[...files,...exportFiles],bound=boundBrowserDocuments(root,selected,browserImporters(root,selected)); - expect(bound.has(exportOwner),"REVIEWED_RASTER_DOCUMENT_BINDS").toBe(true); - const input=[...bound.get(exportOwner)!.values()][0]!;expect(input.runtime).toContain(exportCaller);expect(input.runtime).toContain("packages/module-diagrams/src/flatten.ts");for(const face of [2,4,6,7])expect(input.bytes).toContain(`packages/module-diagrams/assets/fonts/${face}.ttf`); -}); -test("raster argument producer, font bytes and additional or escaped command callers fail fresh",()=>{ - for(const file of [exportOwner,exportCaller,"packages/module-diagrams/src/flatten.ts","packages/module-diagrams/assets/fonts/2.ttf"]){const {root}=exportFixture();writeFileSync(join(root,file),Buffer.concat([readFileSync(join(root,file)),Buffer.from("drift")]));const selected=[...files,...exportFiles];expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(exportOwner)).toBe(false);} - for(const extra of ['import {commands as api} from "vitest/browser"; api.diagramRasterComparison("new",external,external);','import {commands} from "vitest/browser"; const invoke=commands.diagramRasterComparison;']){const {root,write}=exportFixture();write("extra.ts",extra);const selected=[...files,...exportFiles,"extra.ts"];expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(exportOwner)).toBe(false);} -}); - -test("callout caller, source math and literal fixture drift refuse replay binding",()=>{ - for(const file of ["packages/ui-react/tests/browser/diagrams-callouts.layout.tsx","packages/module-diagrams/src/callout-path.ts","packages/module-diagrams/src/callouts.ts","packages/module-diagrams/src/legend.ts","packages/module-diagrams/tests/fixtures/callouts.ts"]){ - const {root,write}=fixture(diagramFiles),selected=[...files,...diagramFiles]; - expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(diagram),"CONTROL_REVIEWED_CALLOUT_DOCUMENT_BINDS").toBe(true); - write(file,readFileSync(join(root,file),"utf8")+"\n/* callout source drift */\n"); - expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(diagram),"CHANGED_CALLOUT_SOURCE_REFUSED").toBe(false); - } -}); - -test("a stale reviewed producer pin or an unreviewed caller refuses binding and names the file",()=>{ - const producer="packages/module-diagrams/src/callouts.ts"; - {const {root,write}=fixture(diagramFiles),selected=[...files,...diagramFiles];write(producer,readFileSync(join(root,producer),"utf8")+"\n// drift\n"); - expect(browserDocumentRefusals(root,selected,browserImporters(root,selected)).get(diagram),"STALE_PIN_NAMED").toBe(`stale reviewed pin: ${producer}`);} - {const {root,write}=fixture(diagramFiles),extra="packages/ui-react/tests/browser/diagrams-unreviewed.layout.tsx"; - write(extra,'import {commands} from "vitest/browser"; await commands.diagramCapture("[data-content-renderer=\\"diagram\\"]","odysseus");'); - const selected=[...files,...diagramFiles,extra]; - expect(browserDocumentRefusals(root,selected,browserImporters(root,selected)).get(diagram),"UNREVIEWED_CALLER_NAMED").toBe(`unreviewed caller: ${extra}`);} -}); - -/** Static relative imports, resolved the way the build resolves sibling sources. */ -function sourceClosure(starts:readonly string[]):Set{ - const seen=new Set(),queue=[...starts]; - while(queue.length){ - const file=queue.pop()!;if(seen.has(file)||!/\.[cm]?[jt]sx?$/.test(file))continue;seen.add(file); - const source=ts.createSourceFile(file,readFileSync(join(repo,file),"utf8"),ts.ScriptTarget.Latest,true); - const visit=(node:ts.Node)=>{ - const spec=(ts.isImportDeclaration(node)||ts.isExportDeclaration(node))&&node.moduleSpecifier&&ts.isStringLiteral(node.moduleSpecifier)?node.moduleSpecifier.text:undefined; - if(spec?.startsWith(".")){const base=join(dirname(file),spec);const target=[base,base.replace(/\.js$/,".ts"),base.replace(/\.js$/,".tsx"),`${base}.ts`,`${base}.tsx`].find(path=>{try{return readFileSync(join(repo,path))&&true;}catch{return false;}});if(target)queue.push(target);} - ts.forEachChild(node,visit); - };visit(source); - } - return seen; -} -test("every module-diagrams source a reviewed binding imports is pinned among its producers",()=>{ - const reviewed=reviewedBrowserDocuments.filter(entry=>Object.keys(entry.producers).some(file=>file.startsWith("packages/module-diagrams/src/"))); - expect(reviewed.length,"DIAGRAM_BINDINGS_PRESENT").toBeGreaterThan(0); - for(const entry of reviewed){ - const pinned=new Set(Object.keys(entry.producers)); - const unpinned=[...sourceClosure([entry.caller,...Object.keys(entry.additionalCallers??{}),...pinned].filter(file=>/\.[cm]?[jt]sx?$/.test(file)))].filter(file=>file.startsWith("packages/module-diagrams/src/")&&!pinned.has(file)).sort(); - expect(unpinned,`UNPINNED_PRODUCER_IMPORTS ${entry.command}`).toEqual([]); - } -}); - -// Each guard has a passing control before mutation; a stale earlier producer -// must not make a later refusal look effective. -test("origin-scene caller and each changed producer retain exact drift refusal",()=>{ - for(const file of [sceneCaller,sceneFixture,...["callouts.ts","geometry.ts","layout.ts","svg-model.ts","ui.tsx","render.ts","flatten.ts"].map(name=>`packages/module-diagrams/src/${name}`)]){ - const {root,write}=fixture(diagramFiles),selected=[...files,...diagramFiles]; - expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(diagram),"CONTROL_SCENE_DOCUMENT_BINDS").toBe(true); - write(file,readFileSync(join(root,file),"utf8")+"\n// scene source drift\n"); - expect(browserDocumentRefusals(root,selected,browserImporters(root,selected)).get(diagram),"SCENE_DRIFT_NAMED").toBe(`stale reviewed pin: ${file}`); - } -}); -test("a missing origin caller, direct owner import or unknown aliased caller refuses scene binding",()=>{ - {const {root}=fixture(diagramFiles),selected=[...files,...diagramFiles].filter(file=>file!==sceneCaller); - expect(browserDocumentRefusals(root,selected,browserImporters(root,selected)).get(diagram),"MISSING_SCENE_CALLER_NAMED").toBe(`not selected: ${sceneCaller}`);} - for(const source of [`import {diagramCapture} from "./${diagram}";`, - 'import {commands as api} from "vitest/browser"; await api.diagramCapture("figure","origin");', - 'const {commands:api}=await import("vitest/browser"); await api.diagramCapture("figure","origin");']){ - const {root,write}=fixture(diagramFiles),extra="extra.ts",selected=[...files,...diagramFiles,extra]; - expect(boundBrowserDocuments(root,[...files,...diagramFiles],browserImporters(root,[...files,...diagramFiles])).has(diagram),"CONTROL_SCENE_IMPORTERS_BINDS").toBe(true); - write(extra,source); - expect(boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(diagram),"UNKNOWN_SCENE_IMPORTER_REFUSED").toBe(false); - } -}); - -// Every document family gets a positive before replacing any audited input -// with real candidate bytes. Compare to the independent owner, never to a -// newly computed production pin or the binder's own result. -test.each([...reviewedBrowserDocuments])("current document sources retain only their reviewed binding: $command",entry=>{ - const selected=[...new Set([...files,...ghostFiles,...exportFiles])]; - const {root}=fixture(ghostFiles); - for(const file of exportFiles){mkdirSync(dirname(join(root,file)),{recursive:true});writeFileSync(join(root,file),frozenBrowserSource(file));} - const bind=()=>boundBrowserDocuments(root,selected,browserImporters(root,selected)).has(entry.owner); - expect(bind(),`FROZEN_DOCUMENT_CONTROL_QUALIFIES ${entry.command}`).toBe(true); - for(const file of new Set([config,entry.owner,entry.caller,...Object.keys(entry.additionalCallers??{}),...Object.keys(entry.producers)])){ - const frozen=frozenBrowserSource(file),current=readFileSync(join(repo,file)); - if(current.equals(frozen)) continue; // The positive above already exercised these exact bytes. - writeFileSync(join(root,file),current); - expect(bind(),`CURRENT_DOCUMENT_SOURCE_DRIFT_REQUIRES_FRESH_PROOF ${entry.command} ${file}`).toBe(false); - writeFileSync(join(root,file),frozen); - } -}); diff --git a/tests/bound-browser-runtime-inputs.test.ts b/tests/bound-browser-runtime-inputs.test.ts deleted file mode 100644 index 81153e4379..0000000000 --- a/tests/bound-browser-runtime-inputs.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { afterEach, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join, resolve } from "node:path"; -import { boundBrowserRuntimeInputs, browserImporters } from "../scripts/bound-browser-runtime-inputs"; -const repo=resolve(import.meta.dir,".."),roots:string[]=[]; -const files=["scripts/browser-shards.ts","scripts/browser-sequencer.ts","scripts/captures/fonts.ts","packages/ui-kit/tests/visual/rank-footer-browser.ts"]; -const data=["scripts/captures/font-lock.json","scripts/captures/fonts.css","packages/ui-kit/.storybook/preview-head.html"]; -afterEach(()=>{for(const root of roots.splice(0))rmSync(root,{recursive:true,force:true});}); -function fixture(){const root=mkdtempSync(join(tmpdir(),"bound-browser-runtime-"));roots.push(root); - const write=(file:string,bytes:string)=>{mkdirSync(dirname(join(root,file)),{recursive:true});writeFileSync(join(root,file),bytes);}; - symlinkSync(join(repo,"node_modules"),join(root,"node_modules"),"dir");for(const file of [...files,...data])write(file,readFileSync(join(repo,file),"utf8"));return{root,write};} -test("exact sealed callers bind only the cost default and checksum-verified font reader bytes",()=>{ - const {root}=fixture(),bindings=boundBrowserRuntimeInputs(root,files); - expect(bindings.get("scripts/browser-shards.ts")?.get('readFileSync(path, "utf8")')).toEqual(["scripts/browser-shard-costs.json"]); - expect(bindings.get("scripts/captures/fonts.ts")?.size).toBe(4); - expect(bindings.get("scripts/captures/fonts.ts")?.get('readFile(resolve(cache, entry.file))')).toEqual(["scripts/captures/font-lock.json"]); - expect(boundBrowserRuntimeInputs(root,files.filter(file=>!file.includes("rank-footer"))).has("scripts/captures/fonts.ts")).toBe(false); -}); -test("new imports, reexports and literal loaders cannot extend a sealed reader's caller domain",()=>{ - for(const source of ['import {readFontLock} from "./scripts/captures/fonts.ts";','export {verifyFontCache} from "./scripts/captures/fonts.ts";','await import("./scripts/captures/fonts.ts");','require("./scripts/captures/fonts.ts");']){ - const {root,write}=fixture();write("extra.ts",source);expect(boundBrowserRuntimeInputs(root,[...files,"extra.ts"]).has("scripts/captures/fonts.ts")).toBe(false); - } -}); -test("reader, caller and pinned font data drift fail fresh rather than trusting parameter claims",()=>{ - for(const file of ["scripts/captures/fonts.ts","packages/ui-kit/tests/visual/rank-footer-browser.ts",...data]){ - const {root,write}=fixture();write(file,readFileSync(join(root,file),"utf8")+"\n// drift\n");expect(boundBrowserRuntimeInputs(root,files).has("scripts/captures/fonts.ts")).toBe(false); - } - const {root,write}=fixture();write("scripts/browser-sequencer.ts",readFileSync(join(root,"scripts/browser-sequencer.ts"),"utf8").replace("readBrowserCosts()","readBrowserCosts(externalPath)"));expect(boundBrowserRuntimeInputs(root,files).has("scripts/browser-shards.ts")).toBe(false); -}); - -const diagramOwner="packages/module-diagrams/src/fonts.ts",diagramCaller="packages/ui-react/tests/browser/diagram-export-command.ts"; -const diagramFonts=[2,4,6,7].map(face=>`packages/module-diagrams/assets/fonts/${face}.ttf`); -function diagramFixture(){const {root,write}=fixture();for(const file of [diagramOwner,diagramCaller,...diagramFonts]){mkdirSync(dirname(join(root,file)),{recursive:true});writeFileSync(join(root,file),readFileSync(join(repo,file)));}return{root,write};} -test("argument-free diagram font producer binds all four exact bundled font blobs",()=>{ - const {root}=diagramFixture(),selected=[diagramOwner,diagramCaller]; - expect([...boundBrowserRuntimeInputs(root,selected).get(diagramOwner)!.values()]).toEqual([diagramFonts]); -}); -test("diagram font, reader, caller, symlink and new importer drift refuse the binding",()=>{ - for(const file of [diagramOwner,diagramCaller,...diagramFonts]){const {root}=diagramFixture();writeFileSync(join(root,file),Buffer.concat([readFileSync(join(root,file)),Buffer.from("drift")]));expect(boundBrowserRuntimeInputs(root,[diagramOwner,diagramCaller]).has(diagramOwner)).toBe(false);} - const {root}=diagramFixture();rmSync(join(root,diagramFonts[0]!));symlinkSync(join(repo,diagramFonts[0]!),join(root,diagramFonts[0]!));expect(boundBrowserRuntimeInputs(root,[diagramOwner,diagramCaller]).has(diagramOwner)).toBe(false); - for(const source of [`import {diagramFontCss as css} from "./${diagramOwner}";`,`export * from "./${diagramOwner}";`,`await import("./${diagramOwner}");`]){const {root,write}=diagramFixture();write("extra.ts",source);expect(boundBrowserRuntimeInputs(root,[diagramOwner,diagramCaller,"extra.ts"]).has(diagramOwner)).toBe(false);} -}); - -test("runtime importer seals address JavaScript implementations rather than declaration neighbors",()=>{ - const{root,write}=fixture();write("entry.ts",'import{readFixture}from"./reader.mjs";readFixture("Odysseus");');write("reader.mjs","export const readFixture=value=>value;");write("reader.d.mts","export declare const readFixture:(value:string)=>string;"); - const imports=browserImporters(root,["entry.ts","reader.mjs","reader.d.mts"]);expect([...imports.get("reader.mjs")??[]]).toEqual(["entry.ts"]);expect(imports.has("reader.d.mts")).toBe(false); -}); diff --git a/tests/browser-command-activation.test.ts b/tests/browser-command-activation.test.ts deleted file mode 100644 index 45432e4d4d..0000000000 --- a/tests/browser-command-activation.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -import {frozenBrowserSource} from "./frozen-browser-source"; -import { afterEach, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { auditedInactiveCommands, auditCommandActivation } from "../scripts/browser-command-activation"; -import { discoverInputClosure } from "../scripts/browser-input-closure"; -const roots: string[] = []; -afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); -function fixture() { - const root = mkdtempSync(join(tmpdir(), "command-activation-")); roots.push(root); - symlinkSync(join(import.meta.dir,"../node_modules"),join(root,"node_modules"),"dir"); - const write = (file: string, content: string) => { mkdirSync(join(root, file, ".."), { recursive: true }); writeFileSync(join(root, file), content); }; - write("command.ts", `import {readFileSync} from "node:fs"; import type {BrowserCommand} from "vitest/node"; -export const heavy:BrowserCommand<[],unknown> = async () => readFileSync(process.env.INPUT!, "utf8");`); - const config = `import {heavy} from "./command.ts"; -export default {test:{setupFiles:["./setup.ts"],projects:[{test:{name:"layout",browser:{commands:{heavy}}}}]}};`; - write("config.ts", config); write("setup.ts", `import {commands} from "vitest/browser"; await commands.light();`); - write("spec.ts", `import {commands} from "vitest/browser"; await commands.light();`); - const audit = () => auditCommandActivation(root, "config.ts", [{ project:"browser", file:"spec.ts" }], [{ owner:"command.ts", name:"heavy" }]); - return {root,write,audit,config}; -} -test("literal unselected registration is audited without suppressing callback or top-level inputs", () => { - const {root,write,audit}=fixture(); - expect(audit()).toEqual({candidates:[{owner:"command.ts",name:"heavy",projects:["layout"]}],files:["command.ts","config.ts","setup.ts","spec.ts"],roots:["config.ts","setup.ts","spec.ts"],unresolved:[],executionExcluded:false}); - expect(discoverInputClosure(root,["config.ts"]).unresolved.some(value=>value.includes("Undeclared input command.ts"))).toBe(true); - write("dependency.ts", `import {readFileSync} from "node:fs"; readFileSync(process.env.INPUT!,"utf8");`); - write("command.ts", `import "./dependency.ts"; import type {BrowserCommand} from "vitest/node"; export const heavy:BrowserCommand<[],unknown>=async()=>0;`); - expect(audit().executionExcluded).toBe(false); - expect(discoverInputClosure(root,["config.ts"]).unresolved.some(value=>value.includes("Undeclared input dependency.ts"))).toBe(true); -}); -test("inherited setup roots retain normal runtime reads and declared input bytes",()=>{ - const {root,write}=fixture();write("setup.ts",'import {readFileSync} from "node:fs"; readFileSync("hook-input.txt","utf8");');write("hook-input.txt","owned hook bytes"); - const activation={config:"config.ts",selected:[{project:"browser",file:"spec.ts"}],candidates:[{owner:"command.ts",name:"heavy"}]}; - const unknown=discoverInputClosure(root,["config.ts"],[],activation); - expect(unknown.files).toContain("setup.ts");expect(unknown.unresolved).toContain('Undeclared input setup.ts: readFileSync("hook-input.txt","utf8")'); - const closed=discoverInputClosure(root,["config.ts"],[{owner:"setup.ts",inputs:[{expression:'readFileSync("hook-input.txt","utf8")',targets:["hook-input.txt"]}]}],activation); - expect(closed.unresolved).toEqual([]);expect(closed.files).toContain("hook-input.txt"); -}); -test("activating dormant command through selected project, spec or inherited setup rejects nonactivation", () => { - for(const activation of ["project","spec","setup"]) { - const {write,audit,config}=fixture(); - if(activation==="project") write("config.ts",config.replace('name:"layout"','name:"browser"')+"\nheavy();"); - else write(activation==="spec"?"spec.ts":"setup.ts",`import {commands} from "vitest/browser"; await commands.heavy();`); - expect(audit().unresolved.some(value=>/Active or ambiguous|Selected command invocation/.test(value))).toBe(true); - } -}); -test("dynamic, aliased and imported command activation and computed hooks remain unknown", () => { - for(const spec of [ - `import {commands} from "vitest/browser"; await commands[process.env.OP!]();`, - `import {commands} from "vitest/browser"; const alias=commands; await alias.heavy();`, - `import * as browser from "vitest/browser"; await browser.commands.heavy();`, - `import {heavy as alias} from "./command.ts"; await alias();`, - `await import(process.env.SPEC!);`, - `import("vitest/browser").then(({commands})=>commands.heavy());`, - `const {commands}=require("vitest/browser"); commands.heavy();`, - `export {commands as hidden} from "vitest/browser";`, - `const execute=eval; execute("commands.heavy()");`, - ]) { const {write,audit}=fixture(); write("spec.ts",spec); expect(audit().unresolved.length).toBeGreaterThan(0); } - const {write,audit,config}=fixture(); write("config.ts",config.replace('["./setup.ts"]','[process.env.SETUP]')); - expect(audit().unresolved.some(value=>value.includes("Computed activation hook"))).toBe(true); -}); -test("ambiguous registration aliases and unknown project names cannot establish inactivity", () => { - for(const change of [ - (source:string)=>source.replace('name:"layout"','name:process.env.PROJECT'), - (source:string)=>source.replace('commands:{heavy}','commands:{renamed:heavy}'), - (source:string)=>source.replace('commands:{heavy}','commands:{...other,heavy}'), - (source:string)=>source+'\nheavy();', - ]) { const {write,audit,config}=fixture(); write("config.ts",change(config)); expect(audit().unresolved.some(value=>value.includes("Active or ambiguous"))).toBe(true); } -}); - -test("only audited inactive callback bodies defer inputs; top-level imports and callback escape stay fresh", () => { - const {root,write,config}=fixture(); - const activation={config:"config.ts",selected:[{project:"browser",file:"spec.ts"}],candidates:[{owner:"command.ts",name:"heavy"}]}; - expect(discoverInputClosure(root,["config.ts"],[],activation).unresolved).toEqual([]); - write("dependency.ts", `import {readFileSync} from "node:fs"; readFileSync(process.env.INPUT!,"utf8");`); - write("command.ts", `import "./dependency.ts"; import type {BrowserCommand} from "vitest/node"; export const heavy:BrowserCommand<[],unknown>=async()=>0;`); - expect(discoverInputClosure(root,["config.ts"],[],activation).unresolved.some(value=>value.includes("Undeclared input dependency.ts"))).toBe(true); - write("command.ts", `import type {BrowserCommand} from "vitest/node"; export const heavy:BrowserCommand<[],unknown>=async()=>0; const alias=heavy; alias();`); - expect(discoverInputClosure(root,["config.ts"],[],activation).unresolved.some(value=>value.includes("Active or ambiguous"))).toBe(true); - write("config.ts",config+'\nimport "./hook.ts";'); write("hook.ts",`import {heavy} from "./command.ts"; heavy();`); - expect(discoverInputClosure(root,["config.ts"],[],activation).unresolved.some(value=>value.includes("Selected execution imports command owner"))).toBe(true); -}); -test("dormant declared targets and their imports remain immutable input bytes", () => { - const {root,write}=fixture(); - write("command.ts", `import {readFileSync} from "node:fs"; import type {BrowserCommand} from "vitest/node"; export const heavy:BrowserCommand<[],unknown>=async()=>readFileSync("generated");`); - write("producer.ts", `import "./helper.ts"; import {readFileSync} from "node:fs"; readFileSync(process.env.INPUT!);`); - write("helper.ts", `export const helper=1;`); - const activation={config:"config.ts",selected:[{project:"browser",file:"spec.ts"}],candidates:[{owner:"command.ts",name:"heavy"}]}; - const closure=discoverInputClosure(root,["config.ts"],[{owner:"command.ts",inputs:[{expression:'readFileSync("generated")',targets:["producer.ts"]}]}],activation); - expect(closure.unresolved).toEqual([]); expect(closure.files).toContain("producer.ts"); expect(closure.files).toContain("helper.ts"); -}); - -test("actual bounded audit identity rejects config, runner, callback and imported helper drift", () => { - const {root,write}=fixture(); - const files=["packages/ui-kit/vitest.config.ts","packages/ui-kit/vite.config.ts","scripts/visual.mjs","packages/ui-react/tests/browser/hygiene-completion-frame.ts","packages/ui-react/tests/browser/mermaid-proof-command.ts","packages/ui-react/tests/browser/offline/scene-commands.ts",...[ - "hygiene-loop","hygiene-server","policy-server","dispatch-actions" - ].map(name=>`packages/ui-react/tests/browser/${name}-command.ts`)]; - for(const file of files) write(file,frozenBrowserSource(file).toString("utf8")); - const selected=[{project:"browser",file:"spec.ts"}]; - expect(auditedInactiveCommands(root,selected)).toBeDefined(); - for(const file of files) { - const original=readFileSync(join(root,file),"utf8"); write(file,original+"\n// source drift\n"); - expect(auditedInactiveCommands(root,selected)).toBeUndefined(); write(file,original); - const current=readFileSync(join(import.meta.dir,"..",file),"utf8");write(file,current); - if(current===original) expect(auditedInactiveCommands(root,selected),"UNCHANGED_COMMAND_SOURCE_QUALIFIES").toBeDefined(); - else expect(auditedInactiveCommands(root,selected),"CURRENT_COMMAND_SOURCE_DRIFT_REQUIRES_FRESH_PROOF").toBeUndefined(); - write(file,original); - } -}); - -test("real runner config import executes an inactive command module's transitive top-level input", async () => { - const {root,write}=fixture(); - write("input.txt","top-level-ran"); - write("dependency.ts",`import {readFileSync} from "node:fs"; globalThis.__activationReceipt=readFileSync(${JSON.stringify(join(root,"input.txt"))},"utf8");`); - write("command.ts",`import "./dependency.ts"; import type {BrowserCommand} from "vitest/node"; export const heavy:BrowserCommand<[],unknown>=async()=>{throw new Error("must not invoke");};`); - const child=Bun.spawn([process.execPath,"-e",`await import(${JSON.stringify(join(root,"config.ts"))}); console.log(globalThis.__activationReceipt);`],{cwd:root,stdout:"pipe",stderr:"pipe"}); - const [output,error,exit]=await Promise.all([new Response(child.stdout).text(),new Response(child.stderr).text(),child.exited]); - expect(exit,error).toBe(0); expect(output.trim()).toBe("top-level-ran"); - const activation={config:"config.ts",selected:[{project:"browser",file:"spec.ts"}],candidates:[{owner:"command.ts",name:"heavy"}]}; - expect(discoverInputClosure(root,["config.ts"],[],activation).unresolved.some(value=>value.includes("Undeclared input dependency.ts"))).toBe(true); -}); - -// A registered callback still needs complete nonactivation evidence. -test("registered selected-project callback stays dormant only with a complete sealed call inventory",()=>{ - const {root,write,audit,config}=fixture();write("config.ts",config.replace('name:"layout"','name:"browser"')); - expect(audit().unresolved,"SELECTED_REGISTRATION_WITHOUT_INVOCATION_IS_DORMANT").toEqual([]); - const activation={config:"config.ts",selected:[{project:"browser",file:"spec.ts"}],candidates:[{owner:"command.ts",name:"heavy"}]}; - expect(discoverInputClosure(root,["config.ts"],[],activation).unresolved).toEqual([]); - write("spec.ts",'import {commands} from "vitest/browser"; await commands.heavy();'); - expect(audit().unresolved,"ACTUAL_DORMANT_CALLBACK_ACTIVATION_REQUIRES_FRESH").toContain("Selected command invocation spec.ts: heavy"); - expect(discoverInputClosure(root,["config.ts"],[],activation).unresolved.length).toBeGreaterThan(0); -}); - -test("explicit JavaScript hooks cannot hide command activation behind declaration files",()=>{ - const{write,audit}=fixture();write("spec.ts",'import "./hook.mjs";');write("hook.mjs",'import{commands}from"vitest/browser";commands.heavy();');write("hook.d.mts","export {};"); - const result=audit();expect(result.files).toContain("hook.mjs");expect(result.unresolved.some(input=>input.includes("Selected command invocation hook.mjs: heavy"))).toBe(true); -}); -test("dormant explicit JavaScript imports still retain actual runtime source bytes",()=>{ - const{root,write}=fixture();write("command.ts",'import type{BrowserCommand}from"vitest/node";export const heavy:BrowserCommand<[],unknown>=async()=>await import("./dormant.mjs");');write("dormant.mjs",'import{readFileSync}from"node:fs";readFileSync(process.env.INPUT,"utf8");');write("dormant.d.mts","export {};"); - const activation={config:"config.ts",selected:[{project:"browser",file:"spec.ts"}],candidates:[{owner:"command.ts",name:"heavy"}]}; - const closure=discoverInputClosure(root,["config.ts"],[],activation);expect(closure.files).toContain("dormant.mjs");expect(closure.unresolved).toEqual([]); -}); diff --git a/tests/browser-inventory-process.test.ts b/tests/browser-inventory-process.test.ts index 3e9d36d7a4..8d97601bb8 100644 --- a/tests/browser-inventory-process.test.ts +++ b/tests/browser-inventory-process.test.ts @@ -2,7 +2,7 @@ import { expect, spyOn, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { browserInventory } from "../scripts/proof-inputs"; +import { browserInventory, normalizeInventory } from "../scripts/proof-inputs"; const controlDeadlineMs = 1000; @@ -111,3 +111,30 @@ test("native watchdog bounds inherited pipes even after the discovery leader has } expect(["gone", "Z"]).toContain(state); // An adopted zombie cannot retain descriptors or execute. }); + +test("a successful discovery reads the published JSON file, not the coloured console output", async () => { + const root = mkdtempSync(join(tmpdir(), "inventory-process-")); + mkdirSync(join(root, "packages/ui-kit"), { recursive: true }); + mkdirSync(join(root, "scripts")); + writeFileSync(join(root, "scripts/visual.mjs"), 'const projects = projectArgs.length ? [] : ["visual", "rail-fine"];\n'); + const discovered = [ + { project: "rail-fine", file: "packages/ui-react/tests/browser/shared.offline.tsx" }, + { project: "ui-react-endurance", file: "packages/ui-react/tests/browser/recordings.endurance.tsx" }, + { project: "ui-react-layout", file: "packages/ui-react/tests/browser/one.layout.tsx" }, + { project: "visual", file: "packages/ui-kit/tests/visual/one.visual.tsx" }, + ]; + const original = Bun.spawn; + const spawn = spyOn(Bun, "spawn").mockImplementationOnce(((argv: string[], options: Parameters[1]) => { + const output = argv.find(arg => arg.startsWith("--json="))!.slice(7); + writeFileSync(output, JSON.stringify(discovered.map(spec => ({ file: join(root, spec.file), projectName: `${spec.project} (chromium)` })))); + return original([process.execPath, "-e", 'console.log("\\u001b[31mconsole diagnostic\\u001b[0m");'], options); + }) as typeof Bun.spawn); + try { expect(await browserInventory(root)).toEqual(discovered); } + finally { spawn.mockRestore(); rmSync(root, { recursive: true, force: true }); } +}); + +test("distinct Chromium and WebKit projects keep separate normalized identities", () => { + const file = "packages/ui-react/tests/browser/diagrams-renderer.layout.tsx"; + expect(normalizeInventory([{ projectName: "diagrams-chromium (chromium)", file }, { projectName: "diagrams-webkit (webkit)", file }])) + .toEqual([{ project: "diagrams-chromium", file }, { project: "diagrams-webkit", file }]); +}); diff --git a/tests/browser-worker-audit.test.ts b/tests/browser-worker-audit.test.ts deleted file mode 100644 index 32de985611..0000000000 --- a/tests/browser-worker-audit.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import {frozenBrowserSource} from "./frozen-browser-source"; -import {afterEach,expect,test} from "bun:test"; -import {chmodSync,mkdirSync,mkdtempSync,readFileSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; -import {tmpdir} from "node:os"; -import {dirname,join,resolve} from "node:path"; -import {hasAuditedWorkerBoundary,inspectWorkerAudit,pdfWorkerInput,workerAuditFile,workerAuditIdentity} from "../scripts/browser-worker-audit"; -const repo=resolve(import.meta.dir,".."),roots:string[]=[],guard="scripts/browser-worker-boundary.ts",setup="packages/ui-kit/tests/visual/worker-boundary-setup.ts",config="packages/ui-kit/vitest.config.ts"; -afterEach(()=>{for(const root of roots.splice(0))rmSync(root,{recursive:true,force:true});}); -function fixture(){const root=mkdtempSync(join(tmpdir(),"browser-worker-audit-"));roots.push(root);const write=(file:string,text:string)=>{mkdirSync(dirname(join(root,file)),{recursive:true});writeFileSync(join(root,file),text);};for(const file of [guard,setup,config])write(file,frozenBrowserSource(file).toString("utf8"));write("spec.ts","export const specimen=1;");write("data.json",'{"fixture":"Odysseus"}');write("fixtures/a.txt","owned directory bytes");const closure={files:[guard,setup,config,"spec.ts","data.json","fixtures","fixtures/a.txt"].sort(),directories:["fixtures"],external:[],unresolved:[pdfWorkerInput]},selected=[{file:"spec.ts",project:"visual"}]; - const manifest=()=>write(workerAuditFile,JSON.stringify({version:2,category:"browser",identity:workerAuditIdentity(root,closure,selected),guardedFreshProofRequired:true,sourceAudit:{version:1,selected:selected.length,files:closure.files.length},historicalDiagnostic:{observed:1,workerAttempts:0}}));manifest();return{root,write,closure,selected,manifest};} -test("capability audit joins exact enforced hooks and all selected source/data/resource identities",()=>{ - const {root,closure,selected,write}=fixture();expect(hasAuditedWorkerBoundary(root,closure,selected)).toBe(true); - write("data.json",'{"fixture":"Penelope"}');expect(hasAuditedWorkerBoundary(root,closure,selected)).toBe(false); -}); -test("new callers, inventory, directory membership, mode and unsupported resources require a new audit",()=>{ - const {root,closure,selected}=fixture(); - expect(hasAuditedWorkerBoundary(root,closure,[...selected,{file:"new.ts",project:"visual"}])).toBe(false); - expect(hasAuditedWorkerBoundary(root,{...closure,directories:["changed"]},selected)).toBe(false); - expect(hasAuditedWorkerBoundary(root,{...closure,unresolved:[pdfWorkerInput,"Unknown external resource"]},selected)).toBe(false); - chmodSync(join(root,"data.json"),0o755);expect(hasAuditedWorkerBoundary(root,closure,selected)).toBe(false); -}); -test("edited enforcement cannot be blessed by merely recomputing manifest metadata",()=>{ - for(const file of [guard,setup,config]){const {root,closure,selected,write,manifest}=fixture();write(file,readFileSync(join(root,file),"utf8")+"\n// guard drift\n");manifest();expect(hasAuditedWorkerBoundary(root,closure,selected)).toBe(false);} -}); -test("missing/symbolic files and a manifest self-hash cannot establish the audit identity",()=>{ - const {root,closure,selected}=fixture();expect(workerAuditIdentity(root,{...closure,files:[...closure.files,workerAuditFile]},selected)).toBeUndefined(); - rmSync(join(root,"spec.ts"));expect(workerAuditIdentity(root,closure,selected)).toBeUndefined();symlinkSync(join(root,"data.json"),join(root,"spec.ts"));expect(workerAuditIdentity(root,closure,selected)).toBeUndefined(); -}); - -test("legacy observation metadata cannot admit the newly audited domain",()=>{ - const {root,write,closure,selected}=fixture(); - write(workerAuditFile,JSON.stringify({version:1,category:"browser",identity:workerAuditIdentity(root,closure,selected),diagnostic:{observed:selected.length,workerAttempts:0}})); - expect(hasAuditedWorkerBoundary(root,closure,selected),"OLD_OBSERVATION_IS_NOT_CURRENT_DOMAIN_ADMISSION").toBe(false); -}); - -test("missing or inconsistent current-domain capability metadata stays fresh",()=>{ - for(const mutate of [(v:any)=>delete v.sourceAudit,(v:any)=>{v.sourceAudit.selected++},(v:any)=>{v.sourceAudit.files++},(v:any)=>{v.guardedFreshProofRequired=false},(v:any)=>delete v.historicalDiagnostic]){const {root,write,closure,selected}=fixture(),record=JSON.parse(readFileSync(join(root,workerAuditFile),"utf8"));mutate(record);write(workerAuditFile,JSON.stringify(record));expect(hasAuditedWorkerBoundary(root,closure,selected)).toBe(false);} -}); - -test("covered byte drift stays unavailable and the bounded manifest names only the changed identity",()=>{ - const {root,closure,selected,write}=fixture(); - const before=inspectWorkerAudit(root,closure,selected); - write("data.json",'{"fixture":"Penelope"}'); - const after=inspectWorkerAudit(root,closure,selected); - expect(after.qualified,"COVERED_DRIFT_REMAINS_UNQUALIFIED").toBe(false); - expect(after.diagnostic.expectedIdentity).toBe(before.diagnostic.actualIdentity); - expect(after.diagnostic.actualIdentity).not.toBe(before.diagnostic.actualIdentity); - const oldFiles=(before.diagnostic as any).material.files,newFiles=(after.diagnostic as any).material.files; - const changed=newFiles.filter((entry:any)=>JSON.stringify(entry)!==JSON.stringify(oldFiles.find((old:any)=>old[0]===entry[0]))); - expect(changed.map((entry:any)=>entry[0]),"WORKER_DIAGNOSTIC_NAMES_CHANGED_BLOB").toEqual(["data.json"]); - expect(JSON.stringify(after.diagnostic)).not.toContain(root); - expect(JSON.stringify(after.diagnostic)).not.toContain("Penelope"); - expect(JSON.stringify(after.diagnostic).length).toBeLessThan(768*1024); -}); - -test("unknown native inputs expose bounded evidence without admission material",()=>{ - const {root,closure,selected}=fixture(); - const unknown={...closure,unresolved:[pdfWorkerInput,"Undeclared input spec.ts: readFile(secretSourceContents)"],nativeDiagramDiagnostic:{version:1 as const,status:"source-mismatch",stage:"runtime",expected:{source:"a".repeat(64),installation:"b".repeat(64)},actual:{source:"c".repeat(64),installation:"b".repeat(64),runtime:"d".repeat(64)}}}; - expect(workerAuditIdentity(root,unknown,selected),"UNSUPPORTED_INPUT_HAS_NO_ADMISSION_IDENTITY").toBeUndefined(); - const inspected=inspectWorkerAudit(root,unknown,selected),diagnostic=inspected.diagnostic as any; - expect(inspected.qualified,"UNKNOWN_NATIVE_INPUT_ALWAYS_REQUIRES_FRESH").toBe(false); - expect(diagnostic.admissionSupported).toBe(false); - expect(diagnostic.native?.status,"UNKNOWN_NATIVE_DIAGNOSTIC_IS_NON_NULL").toBe("source-mismatch"); - expect(diagnostic.native.actual.source).toBe("c".repeat(64)); - expect(diagnostic.material.files.some((entry:any)=>entry[0]==="data.json")).toBe(true); - expect(diagnostic.unresolved).toContainEqual({code:"undeclared-input",owner:"spec.ts"}); - expect(JSON.stringify(diagnostic)).not.toContain(root); - expect(JSON.stringify(diagnostic)).not.toContain("secretSourceContents"); -}); - -// Recomputing candidate metadata must never bless changed enforcement bytes. -test("current enforced hooks qualify only when they match the frozen audit",()=>{ - for(const file of [guard,setup,config]){ - const {root,closure,selected,write,manifest}=fixture(); - expect(hasAuditedWorkerBoundary(root,closure,selected),"FROZEN_WORKER_CONTROL_QUALIFIES").toBe(true); - const current=readFileSync(join(repo,file));write(file,current.toString("utf8"));manifest(); - expect(hasAuditedWorkerBoundary(root,closure,selected),"CURRENT_ENFORCEMENT_DRIFT_REQUIRES_FRESH_PROOF") - .toBe(current.equals(frozenBrowserSource(file))); - } -}); diff --git a/tests/candidate-proof.test.ts b/tests/candidate-proof.test.ts index b6126daabc..4a22d3e431 100644 --- a/tests/candidate-proof.test.ts +++ b/tests/candidate-proof.test.ts @@ -1,7 +1,7 @@ import { expect, test } from "bun:test"; import { proofCadence, planChecks, proofSelections } from "../scripts/ci-plan"; import { requireCandidate, validateCandidate } from "../scripts/candidate-proof"; -import type { API } from "../scripts/proof-reuse"; +import type { API } from "../scripts/proof-api"; const actual = { sha: "a".repeat(40), tree: "b".repeat(40), parents: ["c".repeat(40), "d".repeat(40)] }; const event = { action: "ready_for_review", pull_request: { number: 7, draft: false, diff --git a/tests/check-receipt.test.ts b/tests/check-receipt.test.ts index 33c3a3eb74..7855922462 100644 --- a/tests/check-receipt.test.ts +++ b/tests/check-receipt.test.ts @@ -68,9 +68,10 @@ test("the PR body carries one receipt; missing, empty markers and duplicates are }); test("merge refusal names skipped, timed-out and preempted checks whose hosted category did not run", () => { - const selected = { selections: { verify: "true", browser: "true", layout: "true", unit: "false" }, results: { verify: "success", browser: "skipped", layout: "skipped" }, retained: ["layout"] }; + const selected = { selections: { verify: "true", browser: "true", layout: "true", unit: "false" }, results: { verify: "success", browser: "skipped", layout: "skipped" } }; const covered = coveredCategories(selected); - expect([...covered].sort()).toEqual(["changeset", "layout", "verify"]); + // A selected category that was skipped is never covered: retention is retired (#4107). + expect([...covered].sort()).toEqual(["changeset", "verify"]); const r = receipt([ { name: "strict typecheck", categories: ["verify"], outcome: "timed-out" }, { name: "complete pinned visual/accessibility/pointer suite", categories: ["browser"], outcome: "skipped" }, @@ -118,7 +119,7 @@ test("check:pr CLI writes a receipt recording a forced timeout and prints the PR }); test("local skips of post-merge-only checks are proved by the squash's main run, not refused before merge", () => { - const covered = coveredCategories({ selections: { verify: "true", unit: "true" }, results: { verify: "success", unit: "success" }, retained: [] }); + const covered = coveredCategories({ selections: { verify: "true", unit: "true" }, results: { verify: "success", unit: "success" } }); const r = receipt([ { name: "workspace build for real browser checks", categories: ["browser", "layout", "endurance"], outcome: "skipped" }, { name: "complete pinned visual/accessibility/pointer suite", categories: ["browser"], outcome: "timed-out" }, diff --git a/tests/ci-plan.test.ts b/tests/ci-plan.test.ts index 770454f844..6233e779aa 100644 --- a/tests/ci-plan.test.ts +++ b/tests/ci-plan.test.ts @@ -32,14 +32,6 @@ function fixture() { } describe("affected CI checks", () => { - test("file-read dispatch audits follow reviewed consumers and handler sources", () => { - for (const path of ["packages/ui-react/src/connection.ts", "packages/ui-react/src/hooks/use-websocket.ts", - "packages/ui-react/src/hooks/websocket-handlers/chat.ts", "packages/ui-react/src/lib/stats/context-text.ts"]) { - expect(planChecks([path], [{dir: "ui-react", name: "@fixture/ui-react", dependencies: [], files: ["src"]}]).tests, - `DISPATCH_SOURCE_AUDIT_SELECTED: ${path}`).toContain("tests/source-browser-dispatch.test.ts"); - } - }); - test.each([ "docs/supported-inputs.md", "docs/decisions/provider-history.md", "docs/plans/example.md", "docs/guides/nested/example.md", "README.md", "ROADMAP.md", "AGENTS.md", "CONTRIBUTING.md", "SECURITY.md", @@ -277,7 +269,7 @@ describe("file-reading invariant inputs", () => { ["packages/module-diagrams/upstream.json", ["packages/module-diagrams/tests/module.test.ts"]], ["packages/ui-sdk/src/types.ts", ["tests/seam-list.test.ts", "tests/env-parity.test.ts", "tests/public-docs.test.ts"]], ["api-report/ui-server.txt", ["tests/env-parity.test.ts"]], - [".github/workflows/ci.yml", ["tests/ci-workflows.test.ts", "tests/lockfile.test.ts", "tests/candidate-admission.test.ts", "tests/generated-build-inputs.test.ts", "tests/generated-theme-inputs.test.ts"]], + [".github/workflows/ci.yml", ["tests/ci-workflows.test.ts", "tests/lockfile.test.ts", "tests/candidate-admission.test.ts"]], [".github/workflows/project-sync.yml", ["tests/project-sync-main.test.ts"]], [".github/workflows/ci-timings.yml", ["tests/ci-timings.test.ts"]], ] as const)("selects file consumers of %s", (path, tests) => { diff --git a/tests/ci-workflows.test.ts b/tests/ci-workflows.test.ts index 5cad2fc6e9..94e877f8f4 100644 --- a/tests/ci-workflows.test.ts +++ b/tests/ci-workflows.test.ts @@ -28,7 +28,7 @@ const pullRequest = (headRepo: string | null, extra: Obj = {}): Obj => ({ }); function runs(workflow: Workflow, job: Job, context: Obj): boolean { return String(context.event_name) in workflow.on && (job.if === undefined || evaluate(job.if, { - github: context, needs: { changeset: { result: "success", outputs: { verify: "true", pack: "true", unit: "true", runtime: "true", runtime_host: "true", browser: "true", layout: "true", captures: "true", endurance: "true", run_browser: "true", run_layout: "true" } }, pack: { result: "success" } }, + github: context, needs: { changeset: { result: "success", outputs: { verify: "true", pack: "true", unit: "true", runtime: "true", runtime_host: "true", browser: "true", layout: "true", captures: "true", endurance: "true" } }, pack: { result: "success" } }, }) === true); } function evaluate(expression: string, context: Obj): Json { @@ -131,8 +131,8 @@ describe("the authoritative jobs retain their important phases", () => { expect(ci.on.push).toEqual({ branches: ["main"] }); expect(ci.on.pull_request).toEqual({ types: ["opened", "synchronize", "reopened", "ready_for_review", "converted_to_draft"] }); expect(Object.keys(ci.jobs)).toEqual(["changeset", "verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "proof"]); - expect(ci.jobs.changeset!.outputs).toEqual({ ...Object.fromEntries(["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "cadence", "unit_shards", "red_main_oid"].map(name => [name, `\${{ steps.plan.outputs.${name} }}`])), - ...Object.fromEntries(["run_browser", "run_layout", "reuse"].map(name => [name, `\${{ steps.reuse.outputs.${name} }}`])) }); + // The planner step is the only source of a metadata output: no later step can deselect a category (#4107). + expect(ci.jobs.changeset!.outputs).toEqual(Object.fromEntries(["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "cadence", "unit_shards", "red_main_oid"].map(name => [name, `\${{ steps.plan.outputs.${name} }}`]))); const metadata = ci.jobs.changeset!.steps.filter(s => s.run).map(s => s.run); expect(metadata).toContain("bun scripts/ci-plan.ts"); expect(metadata).toContain("bun run lint"); expect(metadata).toContain("bun scripts/env-docs.ts --check"); expect(metadata).toContain("bun scripts/check-changeset-packages.ts"); @@ -249,7 +249,7 @@ describe("CI concurrency configuration (live scheduler proof remains separate)", }); describe("independent hosted proof after cheap gates", () => { - const context = (selected = "true", result = "success", execute = "true") => ({ needs: { changeset: { result, outputs: { verify: selected, pack: selected, unit: selected, runtime: selected, runtime_host: selected, browser: selected, layout: selected, captures: selected, endurance: selected, run_browser: execute, run_layout: execute } } } }); + const context = (selected = "true", result = "success") => ({ needs: { changeset: { result, outputs: { verify: selected, pack: selected, unit: selected, runtime: selected, runtime_host: selected, browser: selected, layout: selected, captures: selected, endurance: selected } } } }); test("all independent categories depend only on metadata", () => { for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"]) { expect(ci.jobs[name]!.needs).toBe("changeset"); @@ -270,9 +270,14 @@ describe("independent hosted proof after cheap gates", () => { for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"]) expect(evaluate(ci.jobs[name]!.if!, c)).toBe(false); } }); - test("retention skips only admitted browser categories; other selected proof remains fresh", () => { - for (const name of ["browser", "layout"]) expect(evaluate(ci.jobs[name]!.if!, context("true", "success", "false"))).toBe(false); - for (const name of ["unit", "verify", "pack", "runtime", "runtime_host", "captures"]) expect(evaluate(ci.jobs[name]!.if!, context("true", "success", "false"))).toBe(true); + test("a selected category runs on the planner's selection alone; no other output can skip it (#4107)", () => { + for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"]) { + expect(ci.jobs[name]!.if, `SELECTION_ALONE:${name}`).toBe(`\${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.${name} == 'true' }}`); + // The outputs retention used to set are gone; their absence must not skip a selected job. + const selected = context(); + Object.assign(selected.needs.changeset.outputs, { run_browser: "false", run_layout: "false" }); + expect(evaluate(ci.jobs[name]!.if!, selected), `RETIRED_OUTPUT_IGNORED:${name}`).toBe(true); + } }); }); @@ -280,7 +285,7 @@ describe("contributions execute without privileged credentials", () => { for (const { file, workflow } of workflows) { test(`${file}: no secret, write permission or privileged trigger`, () => { expect(read(file)).not.toMatch(/\bsecrets\.|pull_request_target|workflow_run|id-token|: write\b/); - expect(workflow.permissions).toEqual(file === "ci.yml" ? { contents: "read", actions: "read", checks: "read" } : { contents: "read" }); + expect(workflow.permissions).toEqual(file === "ci.yml" ? { contents: "read", actions: "read" } : { contents: "read" }); for (const job of Object.values(workflow.jobs)) { expect(job.permissions).toBeUndefined(); expect(job["runs-on"]).toBe("ubuntu-24.04"); const checkouts = job.steps.filter(s => s.uses?.startsWith("actions/checkout@")); @@ -671,9 +676,9 @@ test("a main push whose metadata job fails still runs its selected proof (#2942) expect(condition, `PUSH_PROOF_SURVIVES_METADATA_FAILURE:${name}`).toContain("!cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push')"); } const steps = ci.jobs.changeset!.steps!.map(step => step.id ?? step.name ?? ""); - const gate = steps.indexOf("Refuse doomed proof while main is red"), plan = steps.indexOf("plan"), reuse = steps.indexOf("reuse"); + const gate = steps.indexOf("Refuse doomed proof while main is red"), plan = steps.indexOf("plan"); expect(gate, "RED_MAIN_GATE_RUNS_FIRST").toBeGreaterThan(-1); expect(gate).toBeLessThan(plan); - // Every output-producing step precedes every metadata gate that can fail. + // The planner is the only output-producing step, and it precedes every metadata gate that can fail. for (const gateStep of ["Lint, leakage and contribution workflow guards", "Env documentation matches its descriptors", "Validate all pending changeset package names", "Require a changeset for shipped package changes"]) - expect(steps.indexOf(gateStep), `OUTPUTS_BEFORE_${gateStep}`).toBeGreaterThan(reuse); + expect(steps.indexOf(gateStep), `OUTPUTS_BEFORE_${gateStep}`).toBeGreaterThan(plan); }); diff --git a/tests/first-party-source-pins.test.ts b/tests/first-party-source-pins.test.ts new file mode 100644 index 0000000000..c19ddf0f46 --- /dev/null +++ b/tests/first-party-source-pins.test.ts @@ -0,0 +1,115 @@ +// Browser proof retention and the audited source pins that qualified it are +// retired (#4107, maintainer decision 2026-11-16). A pin was a SHA-256 of +// first-party source held in a script, so every product change to a pinned +// file turned `unit` red until its hash was recomputed. Nothing in the tooling +// may pin first-party source again, and a byte change to a file that used to +// be pinned must leave planning and the tooling tests that read it green. +import { afterAll, expect, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { appendFileSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, isAbsolute, join, relative, resolve } from "node:path"; +import { closureSelects, discoverBrowserClosures } from "../scripts/browser-input-closure"; +import { FILE_INPUT_TESTS, planUnitChecks, selectBrowserClosures, workspaces } from "../scripts/ci-plan"; + +const root = resolve(import.meta.dir, ".."); +const fixtures: string[] = []; +afterAll(() => { for (const fixture of fixtures) rmSync(fixture, { recursive: true, force: true }); }); + +function git(cwd: string, ...args: string[]): string { + const child = Bun.spawnSync(["git", ...args], { cwd, stdout: "pipe", stderr: "pipe", + env: { ...process.env, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" } }); + expect(child.exitCode, new TextDecoder().decode(child.stderr)).toBe(0); + return new TextDecoder().decode(child.stdout); +} +const worktreeFiles = () => git(root, "ls-files", "--cached", "--others", "--exclude-standard", "-z").split("\0") + .filter(file => file && lstatSync(join(root, file), { throwIfNoEntry: false })); + +// Source a tool could pin: code and configuration that a product or tooling +// change edits. Fonts, images and captured fixture data are identities of +// third-party bytes, and a fixture manifest may record them. +const SOURCE = /\.(?:[cm]?[jt]sx?|css|ya?ml|sh|py|toml)$|(?:^|\/)(?:package|tsconfig(?:\.[^/]+)?)\.json$/; +const FIXTURE = /(?:^|\/)fixtures\//; +// Where a pin would live: the tooling and its tests, in the root and in each package. +const HOLDER = /^(?:scripts|tests)\/|^packages\/[^/]+\/(?:scripts|tests)\//; +const HOLDER_TEXT = /\.(?:[cm]?[jt]sx?|json|py|sh|ya?ml)$/; +// Archived measurement records name the inputs they measured. No test compares +// them with the current tree, so a digest there cannot fail a later change. +const RECORD = /^scripts\/measurements\//; +// The capture font lock records the downloaded third-party stylesheet beside +// the fonts it names; `bun run capture:fonts` rewrites both together. +const THIRD_PARTY = new Set(["scripts/captures/font-lock.json pins scripts/captures/fonts.css"]); + +test("no script or test holds the SHA-256 of a first-party source file", () => { + const files = worktreeFiles().filter(file => lstatSync(join(root, file)).isFile()); + const digests = new Map(); + for (const file of files) if (SOURCE.test(file) && !FIXTURE.test(file)) digests.set(createHash("sha256").update(readFileSync(join(root, file))).digest("hex"), file); + const holders = files.filter(file => HOLDER.test(file) && HOLDER_TEXT.test(file) && !RECORD.test(file)); + // The scan must read the files the pins lived in, or an empty inventory passes vacuously. + expect(holders, "SCAN_COVERS_THE_SELECTION_TOOLING").toContain("scripts/browser-input-closure.ts"); + expect(digests.size, "SCAN_HASHES_PRODUCT_SOURCE").toBeGreaterThan(1000); + const pins = holders.flatMap(holder => [...new Set(readFileSync(join(root, holder), "utf8").match(/\b[0-9a-f]{64}\b/g) ?? [])] + .filter(literal => digests.has(literal)).map(literal => `${holder} pins ${digests.get(literal)}`)).filter(pin => !THIRD_PARTY.has(pin)); + expect(pins, "FIRST_PARTY_SOURCE_STAYS_UNPINNED").toEqual([]); +}); + +/** A copy of the working tree that resolves workspace packages inside itself. */ +function fixtureTree(): string { + const copy = mkdtempSync(join(tmpdir(), "odysseus-unpinned-source-")); + fixtures.push(copy); + for (const file of worktreeFiles()) { + const from = join(root, file), to = join(copy, file); + mkdirSync(dirname(to), { recursive: true }); + if (lstatSync(from).isSymbolicLink()) symlinkSync(readlinkSync(from), to); + else copyFileSync(from, to, constants.COPYFILE_FICLONE); + } + // Installed packages stay shared and read-only; a link into the repository + // (a workspace package) is re-pointed at the copy, so the copy's source is + // what resolution, planning and the tests below read. + const link = (directory: string) => { + mkdirSync(join(copy, directory), { recursive: true }); + for (const entry of readdirSync(join(root, directory), { withFileTypes: true })) { + const name = join(directory, entry.name), from = join(root, name); + if (entry.name.startsWith(".")) continue; + if (entry.isDirectory() && entry.name.startsWith("@")) { link(name); continue; } + const target = entry.isSymbolicLink() ? resolve(dirname(from), readlinkSync(from)) : from; + const inside = relative(root, target); + symlinkSync(!isAbsolute(inside) && !inside.startsWith("..") && !inside.split("/").includes("node_modules") ? join(copy, inside) : target, join(copy, name)); + } + }; + for (const directory of ["node_modules", ...readdirSync(join(root, "packages")).map(name => `packages/${name}/node_modules`)]) + if (existsSync(join(root, directory))) link(directory); + // The file-reading tests list the tree through Git. + git(copy, "init", "-q"); git(copy, "add", "-A"); + return copy; +} + +test("a byte change to product source a binding used to pin fails neither planning nor the tests that read it", async () => { + // Both were pinned by the dispatch binding; the planner's file-input table named the second. + const changed = ["packages/ui-react/src/ws-client/inbound.ts", "packages/ui-react/src/hooks/websocket-handlers/chat.ts"]; + const copy = fixtureTree(); + for (const file of changed) { + appendFileSync(join(copy, file), "\n// A product edit: the bytes differ, the behaviour does not.\n"); + expect(readFileSync(join(copy, file), "utf8"), `FIXTURE_CHANGES_BYTES:${file}`).not.toBe(readFileSync(join(root, file), "utf8")); + } + + // Planning: the change selects every browser category, from closures discovered in the copy. + const closures = discoverBrowserClosures(copy); + for (const file of changed) expect(closures.browser.files, `CLOSURE_DISCOVERED_IN_THE_COPY:${file}`).toContain(file); + for (const category of ["browser", "layout", "endurance"] as const) + expect(closureSelects(changed, closures[category], false), `CLOSURE_SELECTS_WITHOUT_THE_BROAD_RULE:${category}`).toBe(true); + const plan = selectBrowserClosures(planUnitChecks(changed, workspaces(copy), copy), closures); + expect(plan.global, "PRODUCT_EDIT_STAYS_AN_AFFECTED_PLAN").toBe(false); + expect(plan.local, "PRODUCT_EDIT_SELECTS_ITS_CATEGORIES").toMatchObject({ fullTests: true, browser: true, layout: true, endurance: true, captures: true }); + + // The unit tier's tooling tests: the root tests the planner's own table says + // read these files as bytes. A pin test has to be listed there to be selected, + // so a new one would run here and fail on the changed bytes. + const readers = Object.entries(FILE_INPUT_TESTS) + .filter(([test, inputs]) => test.startsWith("tests/") && changed.some(file => inputs.some(input => input.test(file)))).map(([test]) => test).sort(); + expect(readers.length, "PLANNER_NAMES_ROOT_TESTS_THAT_READ_THE_CHANGE").toBeGreaterThan(0); + for (const test of readers) expect(plan.tests, `READER_IS_SELECTED:${test}`).toContain(test); + const child = Bun.spawn([process.execPath, "scripts/test.ts", "--timeout", "30000", ...readers], { cwd: copy, stdout: "pipe", stderr: "pipe" }); + const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(code, `TOOLING_TESTS_PASS_ON_CHANGED_PRODUCT_BYTES\n${(out + err).split("\n").filter(line => /\(fail\)|^error|✗/.test(line)).slice(0, 20).join("\n")}\n${(out + err).slice(-2000)}`).toBe(0); +}, 240_000); diff --git a/tests/fixtures/generated-theme-vitest.config.txt b/tests/fixtures/generated-theme-vitest.config.txt deleted file mode 100644 index 691e5fbbaf..0000000000 --- a/tests/fixtures/generated-theme-vitest.config.txt +++ /dev/null @@ -1,322 +0,0 @@ -import { diagramArtifact, diagramFontStyles, diagramRasterComparison } from "../ui-react/tests/browser/diagram-export-command.ts"; -import { diagramCapture, diagramFixture } from "../ui-react/tests/browser/diagram-proof-command.ts"; -import { mermaidMedia, mermaidOutput, mermaidScreenComparison } from "../ui-react/tests/browser/mermaid-proof-command.ts"; -import { consumerParityViewport } from "./tests/visual/consumer-parity-viewport.ts"; -import { storageServer } from "../ui-react/tests/browser/storage-server-command.ts"; -import { policyServer } from "../ui-react/tests/browser/policy-server-command.ts"; -import { hygieneLoop } from "../ui-react/tests/browser/hygiene-loop-command.ts"; -import { hygieneServer } from "../ui-react/tests/browser/hygiene-server-command.ts"; -import { dispatchActions } from "../ui-react/tests/browser/dispatch-actions-command.ts"; -import { transcriptionHttp } from "../ui-react/tests/browser/offline/transcription-http.ts"; -import path from "node:path"; -import { MeasuredBrowserSequencer } from "../../scripts/browser-sequencer.ts"; -import { fileURLToPath } from "node:url"; - -import { storybookTest } from "@storybook/addon-vitest/vitest-plugin"; -import { playwright } from "@vitest/browser-playwright"; -import { defineConfig, mergeConfig } from "vitest/config"; - -import { requestLog, startRequestLog } from "./tests/visual/request-log.ts"; -import { grantMicrophone } from "./tests/visual/microphone-permission.ts"; -import { formViewport, formConsumerStyles, htmlPreviewFixture, overlayImageFixture, overlayImageRelease, codeHighlightFailure, codeHighlightFailureCount } from "./tests/visual/form-browser.ts"; -import { dictationThemeStyles, dictationMotion } from "./tests/visual/dictation-motion.ts"; -import { moduleSettingsScreenshot, moduleSettingsImportGate } from "./tests/visual/module-settings-browser.ts"; -import { dictationPointer } from "./tests/visual/dictation-pointer.ts"; -import { focusCapture } from "./tests/visual/focus-browser.ts"; -import { buttonPointer, buttonCapture } from "./tests/visual/button-browser.ts"; -import { ghostMedia, ghostPixels, ghostMaskPixels, ghostTrace } from "./tests/visual/ghost-browser.ts"; -import { rankTap, rankTouch } from "./tests/visual/rank-pointer.ts"; -import { sheetInput } from "./tests/visual/sheet-pointer.ts"; -import { overlayMouse, destinationPaint, destinationMotion, destinationSafeArea } from "./tests/visual/overlay-pointer.ts"; -import { rankFooterFonts, rankFooterDrag, rankFooterCapture } from "./tests/visual/rank-footer-browser.ts"; -import { designFontUsage } from "./tests/visual/design-font-browser.ts"; -import { canvasEncodingLoad } from "./tests/visual/canvas-encoding-load.ts"; -import { coldCapture } from "../ui-react/tests/browser/offline/cold-capture/commands.ts"; -import { shareReview } from "../ui-react/tests/browser/share-review/commands.ts"; -import { offlineScene } from "../ui-react/tests/browser/offline/scene-commands.ts"; -import { fakeMicrophoneFile } from "../ui-react/tests/browser/offline/fake-microphone-file.ts"; -import viteConfig from "./vite.config.ts"; - -const dirname = path.dirname(fileURLToPath(import.meta.url)); - -// Every story becomes a Vitest test — a render smoke test plus its play -// function — running in a real Chromium through Playwright, not happy-dom. -// This is a SEPARATE runner from the repo's `bun test`; the two coexist and -// are run as two commands. -// -// There is deliberately no `.storybook/vitest.setup.ts`: since Storybook 10.3 -// the addon applies `setProjectAnnotations` itself, and adding the file back -// makes it skip that and warn. The published docs snippets are stale on this. -// -// Two story projects, one per theme — D9's matrix. `initialGlobals` pins the -// addon-themes `theme` global for every story the project runs, so the light -// project renders all 540-odd stories on paper with the same play functions -// and the same a11y gate at `'error'`. That is the light theme's contrast -// proof: axe on every rendered story, not a table of numbers. -const storyProject = (name: string, theme: string) => ({ - extends: true, - plugins: [ - storybookTest({ - configDir: path.join(dirname, ".storybook"), - storybookScript: "bun run storybook --no-open", - storybookUrl: process.env.SB_URL, - initialGlobals: { theme }, - }), - ], - test: { - name, - provide: { storyTheme: theme }, - setupFiles: ["./tests/visual/story-theme-setup.ts"], - browser: { - enabled: true, - commands: { consumerParityViewport }, - provider: playwright({}), - headless: true, - instances: [{ browser: "chromium" }], - }, - }, -}); - -// Chromium's pointer settings are bit fields: coarse=2, fine=4. Keep each -// input scene in its own browser; the tests assert the actual media queries -// before measuring CSS or dispatching native touch input (no matchMedia mock). -// The rail, the overlay discs and the working-session strip (#949) share these -// scenes. The strip's pixel baselines are taken in `rail-mixed` only, so one -// image covers each case. -const railProject = (mode: "fine" | "coarse" | "mixed") => ({ - extends: true, - test: { - name: `rail-${mode}`, - // The app's own rail and palette (#946), phone navigation (#947) and - // pressing the current destination (#1078) and the working sessions - // (#950) and the #929 reach proof (#953) run here too, for the real - // pointer; they need the consumer stylesheet. Button's hover text - // contrast (#974) and the palette's reason rows (#1106) are measured - // under all three pointers as well. - include: ["tests/visual/native-buttons.visual.tsx", "tests/visual/side-rail-targets.visual.tsx", "tests/visual/button-hover-contrast.visual.tsx", "tests/visual/overlay-targets.visual.tsx", "tests/visual/session-strip.visual.tsx", "tests/visual/pending-follow-ups.visual.tsx", "tests/visual/palette-reasons.visual.tsx", "../ui-react/tests/browser/desktop-navigation.pointer.tsx", "../ui-react/tests/browser/keyboard-hints.pointer.tsx", "../ui-react/tests/browser/phone-navigation.pointer.tsx", "../ui-react/tests/browser/destination-press.pointer.tsx", "../ui-react/tests/browser/working-sessions.pointer.tsx", "../ui-react/tests/browser/session-drafts.pointer.tsx", "../ui-react/tests/browser/navigation-reach.pointer.tsx", "../ui-react/tests/browser/recordings-tray.offline.tsx", "../ui-react/tests/browser/dictation-notice.pointer.tsx", "../ui-react/tests/browser/overlay-stacking.pointer.tsx", "../ui-react/tests/browser/session-profile.pointer.tsx", "../ui-react/tests/browser/turn-budget.pointer.tsx"], - provide: { railPointer: mode, keyboardHintsLive: false }, - browser: { - enabled: true, - commands: { sheetInput, rankTouch, rankTap, formViewport, formConsumerStyles, htmlPreviewFixture, overlayImageFixture, overlayImageRelease, buttonPointer, focusCapture, overlayMouse, destinationPaint, destinationMotion, destinationSafeArea, dictationMotion }, - provider: playwright({ - launchOptions: { args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", `--use-file-for-fake-audio-capture=${fakeMicrophoneFile()}`, "--autoplay-policy=no-user-gesture-required", `--blink-settings=availablePointerTypes=${mode === "mixed" ? 6 : mode === "coarse" ? 2 : 4},primaryPointerType=${mode === "coarse" ? 2 : 4}`] }, - contextOptions: { reducedMotion: "reduce" }, - }), - headless: true, - instances: [{ browser: "chromium" }], - }, - }, -}); - -export default mergeConfig( - viteConfig, - defineConfig({ - // The story addon inserts preview-head.html into its runner HTML. Its - // network font links would compete with the shared locked offline faces. - plugins: [{ - name: "locked-preview-fonts", - transformIndexHtml: { - order: "post", - handler: (html) => html.replace(/]*href="https:\/\/fonts\.(?:googleapis|gstatic)\.com(?:\/[^\"]*)?"[^>]*>/g, ""), - }, - }], - test: { - sequence: { sequencer: MeasuredBrowserSequencer }, - provide: { proofWorkerMode: "selected-zero-v1" }, - setupFiles: ["./tests/visual/worker-boundary-setup.ts", "./tests/visual/design-font-setup.ts"], - browser: { commands: { designFonts: rankFooterFonts, designFontUsage } }, - projects: [ - { - extends: true, - test: { - name: "diagrams-chromium", - include: ["../ui-react/tests/browser/diagrams-*.layout.tsx"], - browser: { - enabled: true, screenshotFailures: false, - commands: { diagramRasterComparison, diagramFontStyles, diagramArtifact, mermaidScreenComparison, diagramCapture, diagramFixture, overlayMouse, mermaidMedia, mermaidOutput, formConsumerStyles, formViewport }, - provider: playwright({ contextOptions: { reducedMotion: "reduce" } }), - headless: true, - instances: [{ browser: "chromium" }], - }, - }, - }, - { - extends: true, - test: { - name: "diagrams-webkit", - include: ["../ui-react/tests/browser/diagrams-*.layout.tsx"], - browser: { - enabled: true, screenshotFailures: false, - commands: { diagramRasterComparison, diagramFontStyles, diagramArtifact, mermaidScreenComparison, diagramCapture, diagramFixture, overlayMouse, mermaidMedia, mermaidOutput, formConsumerStyles, formViewport }, - provider: playwright({ contextOptions: { reducedMotion: "reduce" } }), - headless: true, - instances: [{ browser: "webkit" }], - }, - }, - }, - { - extends: true, - test: { - name: "ui-react-layout", - provide: { proofWorkerMode: "fresh-worker-runtime-v1" }, - // Measurements of the real consumer, kept out of Bun's test glob, - // and the offline fault harness's self-tests (#1016). - include: ["../ui-react/tests/browser/**/*.layout.tsx", "../ui-react/tests/browser/**/*.offline.tsx"], - exclude: ["../ui-react/tests/browser/diagrams-*.layout.tsx"], - browser: { - enabled: true, - screenshotFailures: false, - commands: { mermaidMedia, mermaidOutput, mermaidScreenComparison, buttonCapture, overlayMouse, dictationMotion, policyServer, storageServer, hygieneLoop, hygieneServer, dispatchActions, sheetInput, focusCapture, formViewport, formConsumerStyles, rankFooterFonts, codeHighlightFailure, codeHighlightFailureCount, offlineScene, coldCapture, shareReview, transcriptionHttp, startRequestLog, requestLog, grantMicrophone }, - // The fake microphone plays the generated 10-second fixture - // (#1016). Chromium reads the file at launch, so it is written - // when this config loads; the fake UI grants the permission. - // Audio contexts start without a gesture, as the injected - // microphone and the tone check need. - provider: playwright({ - launchOptions: { args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", `--use-file-for-fake-audio-capture=${fakeMicrophoneFile()}`, "--autoplay-policy=no-user-gesture-required"] }, - contextOptions: { reducedMotion: "reduce" }, - }), - headless: true, - instances: [{ browser: "chromium" }], - }, - }, - }, - { - extends: true, - test: { - name: "ui-react-endurance", - provide: { proofWorkerMode: "fresh-worker-runtime-v1" }, - // Real-time native media proof has its own scheduling and discovery; - // keep the same offline launch, commands and lifecycle as layout. - include: ["../ui-react/tests/browser/**/*.endurance.tsx"], - browser: { - enabled: true, - screenshotFailures: false, - commands: { buttonCapture, overlayMouse, dictationMotion, policyServer, hygieneLoop, hygieneServer, dispatchActions, sheetInput, focusCapture, formViewport, formConsumerStyles, rankFooterFonts, codeHighlightFailure, codeHighlightFailureCount, offlineScene, coldCapture, shareReview, transcriptionHttp, startRequestLog, requestLog, grantMicrophone }, - // The fake microphone plays the generated 10-second fixture - // (#1016). Chromium reads the file at launch, so it is written - // when this config loads; the fake UI grants the permission. - // Audio contexts start without a gesture, as the injected - // microphone and the tone check need. - provider: playwright({ - launchOptions: { args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", `--use-file-for-fake-audio-capture=${fakeMicrophoneFile()}`, "--autoplay-policy=no-user-gesture-required"] }, - contextOptions: { reducedMotion: "reduce" }, - }), - headless: true, - instances: [{ browser: "chromium" }], - }, - }, - }, - storyProject("storybook", "dark"), - storyProject("storybook-light", "light"), - railProject("fine"), - railProject("coarse"), - railProject("mixed"), - { - extends: true, - test: { - name: "visual", - // `.visual.tsx`, deliberately NOT `.test.tsx`: the repo's `bun run test` - // globs `packages/**` for `*.test.ts(x)` and would claim these, then - // fail on the first story import because bun's runner has no Vite and - // cannot resolve `#.storybook/preview`. Two runners, two extensions. - include: ["tests/visual/**/*.visual.tsx"], - exclude: ["tests/visual/native-buttons.visual.tsx", "tests/visual/rank-footer-touch.visual.tsx", "tests/visual/module-settings.visual.tsx", "tests/visual/subjects.visual.tsx", "tests/visual/dictation-panel.visual.tsx", "tests/visual/side-rail-targets.visual.tsx", "tests/visual/button-hover-contrast.visual.tsx", "tests/visual/overlay-targets.visual.tsx", "tests/visual/session-strip.visual.tsx", "tests/visual/pending-follow-ups.visual.tsx", "tests/visual/palette-reasons.visual.tsx"], - browser: { - enabled: true, - // The link card's no-request proof reads the network from - // Playwright (`tests/visual/request-log.ts`). - commands: { sheetInput, startRequestLog, requestLog, rankTouch, rankFooterFonts, rankFooterDrag, rankFooterCapture, formViewport, formConsumerStyles, buttonPointer, buttonCapture, focusCapture, ghostMedia, ghostPixels, ghostMaskPixels, ghostTrace, canvasEncodingLoad, dictationMotion }, - // Chromium's own web-test mode retains native encoding without - // waiting for idle periods that can exceed a functional poll (#940). - provider: playwright({ launchOptions: { args: ["--enable-blink-features=NoIdleEncodingForWebTests"] } }), - headless: true, - instances: [{ browser: "chromium" }], - }, - }, - }, - { - extends: true, - test: { - // Chromium's touch-emulation disable does not restore a fine - // pointer. Keep this complete consumer fixture in its own provider - // lifetime, even when files in another project reuse their page. - name: "dictation", - include: ["tests/visual/dictation-panel.visual.tsx"], - browser: { - enabled: true, - commands: { sheetInput, formViewport, formConsumerStyles, dictationPointer, dictationThemeStyles, dictationMotion, rankTouch }, - provider: playwright({}), - headless: true, - instances: [{ browser: "chromium" }], - }, - }, - }, - { - extends: true, - test: { - // A failure screenshot in another file changes Chromium's used - // monospace fallback even after that file restores its DOM/viewport. - // Keep incumbent subject pixels in a separate browser process (#879). - name: "subjects", - include: ["tests/visual/subjects.visual.tsx"], - browser: { - enabled: true, - commands: { formViewport }, - provider: playwright({}), - headless: true, - instances: [{ browser: "chromium" }], - }, - }, - }, - { - extends: true, - test: { - // Consumer styles, viewport changes and font fallback must not - // share the kit baseline project's browser process. - name: "module-settings", - include: ["tests/visual/module-settings.visual.tsx"], - browser: { - enabled: true, - commands: { formViewport, formConsumerStyles, moduleSettingsScreenshot, moduleSettingsImportGate }, - provider: playwright({}), - headless: true, - instances: [{ browser: "chromium" }], - }, - }, - }, - { - extends: true, - test: { - name: "rank-footer-touch", - include: ["tests/visual/rank-footer-touch.visual.tsx"], - browser: { - enabled: true, - commands: { rankTouch, rankFooterFonts, rankFooterDrag, rankFooterCapture }, - provider: playwright({ contextOptions: { hasTouch: true } }), - headless: true, - instances: [{ browser: "chromium" }], - }, - }, - }, - { - extends: true, - test: { - // Touch emulation does not restore fine-pointer media on disable. - // Own its browser lifetime so live hint proof cannot affect other files. - name: "keyboard-hints-live", - include: ["../ui-react/tests/browser/keyboard-hints.pointer.tsx"], - provide: { railPointer: "fine", keyboardHintsLive: true }, - browser: { - enabled: true, - commands: { dictationPointer, formViewport, formConsumerStyles, rankTouch, rankTap }, - provider: playwright({ contextOptions: { reducedMotion: "reduce" } }), - headless: true, - instances: [{ browser: "chromium" }], - }, - }, - }, - ], - }, - }) -); diff --git a/tests/frozen-browser-source.ts b/tests/frozen-browser-source.ts deleted file mode 100644 index fb0b7d9e4f..0000000000 --- a/tests/frozen-browser-source.ts +++ /dev/null @@ -1,22 +0,0 @@ -import assert from "node:assert/strict"; -import {resolve} from "node:path"; - -// Delivered main (#2462), including the scene producers from #2369, owns -// the reviewed config and producers. Production audit pins stay unchanged. -// Read raw Git blobs offline, independently of production pins and HEAD. This -// positive is not candidate qualification; current bytes have separate controls. -const owner = "419f3a51b5017a4705e6fe4dba9982b6fc8de3bc"; -function git(args: string[]): Buffer { - const child = Bun.spawnSync(["git", ...args], { - cwd: resolve(import.meta.dir, ".."), stdout: "pipe", stderr: "pipe", - }); - assert.equal(child.exitCode, 0, "FROZEN_BROWSER_SOURCE_OWNER_AVAILABLE_OFFLINE"); - return Buffer.from(child.stdout); -} -export function frozenBrowserSource(file: string): Buffer { - return git(["show", `${owner}:${file}`]); -} -export function frozenBrowserFiles(directory: string): string[] { - return git(["ls-tree", "-r", "--name-only", "-z", owner, "--", directory]) - .toString("utf8").split("\0").filter(Boolean); -} diff --git a/tests/frozen-generated-source.ts b/tests/frozen-generated-source.ts deleted file mode 100644 index fa4a83aa79..0000000000 --- a/tests/frozen-generated-source.ts +++ /dev/null @@ -1,14 +0,0 @@ -import assert from "node:assert/strict"; -import {resolve} from "node:path"; - -// Delivered main a9bcdbd67 owns the audited producers and readers (#3548 re-audit). Read raw Git -// blobs offline: neither HEAD, worktree files nor archive substitution owns a -// frozen positive. CI checks out full history; absent history is a hard failure. -const owner = "a9bcdbd6734c1733390570e2a68c10afde3b00a9"; -export function frozenGeneratedSource(file: string): string { - const child = Bun.spawnSync(["git", "show", `${owner}:${file}`], { - cwd: resolve(import.meta.dir, ".."), stdout: "pipe", stderr: "pipe", - }); - assert.equal(child.exitCode, 0, "FROZEN_GENERATED_SOURCE_OWNER_AVAILABLE_OFFLINE"); - return child.stdout.toString("utf8"); -} diff --git a/tests/generated-build-inputs.test.ts b/tests/generated-build-inputs.test.ts deleted file mode 100644 index 6a83cb7d14..0000000000 --- a/tests/generated-build-inputs.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import {frozenGeneratedSource} from "./frozen-generated-source"; -import { afterEach, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join, resolve } from "node:path"; -import { generatedCssInputs, generatedCssReadInputs } from "../scripts/generated-build-inputs"; -import { discoverInputClosure } from "../scripts/browser-input-closure"; -const repo=resolve(import.meta.dir,".."),roots:string[]=[]; -afterEach(()=>{for(const root of roots.splice(0))rmSync(root,{recursive:true,force:true});}); -const producer=["scripts/build.ts","scripts/build-execution.ts","scripts/build-receipt.ts","scripts/build-repeat-observation.ts","scripts/bin-modes.ts","scripts/publishable-packages.ts","scripts/workspace-lease.mjs","scripts/ci-proof.ts","scripts/check-pr.ts","scripts/ci-runner.ts",".github/workflows/ci.yml","package.json"]; -function fixture(){ - const root=mkdtempSync(join(tmpdir(),"generated-css-"));roots.push(root); - const write=(file:string,bytes:string)=>{mkdirSync(dirname(join(root,file)),{recursive:true});writeFileSync(join(root,file),bytes);}; - for(const file of producer)write(file,frozenGeneratedSource(file)); - write("packages/ui-react/src/styles.css",".marker{color:red}");write("packages/ui-react/package.json",'{}'); - return {root,write}; -} -test("generated stylesheet imports own source and checked producer, without current dist artifacts",()=>{ - const {root,write}=fixture();write("packages/ui-kit/story.ts",'import css from "../ui-react/dist/styles.css?raw";'); - const closure=discoverInputClosure(root,["packages/ui-kit/story.ts"]); - expect(closure.unresolved).toEqual([]);expect(closure.files).toContain("packages/ui-react/src/styles.css");expect(closure.files).toContain("scripts/build.ts"); - expect(closure.files).not.toContain("packages/ui-react/dist/styles.css"); - write("packages/ui-react/dist/styles.css","untrusted working-tree bytes"); - expect(discoverInputClosure(root,["packages/ui-kit/story.ts"]).files).toEqual(closure.files); - expect(generatedCssInputs(root,"packages/ui-react/dist/unowned.css")).toBeUndefined(); -}); -test("producer, execution-order, receipt and package-script drift refuse generated stylesheet binding",()=>{ - const {root,write}=fixture(); - for(const file of producer){const original=readFileSync(join(root,file),"utf8");write(file,original+"\n// drift\n");expect(generatedCssInputs(root,"packages/ui-react/dist/styles.css")).toBeUndefined();write(file,original);} - expect(generatedCssInputs(root,"../outside/dist/styles.css")).toBeUndefined(); -}); -test("copied theme and kit token exports bind their source without admitting nonexistent react tokens",()=>{ - const {root,write}=fixture();write("packages/ui-react/src/theme.css",".theme{}");write("packages/ui-kit/src/theme.css",".theme{}");write("packages/ui-kit/src/tokens.css",":root{--token:1}"); - expect(generatedCssInputs(root,"packages/ui-react/dist/theme.css")?.entry).toBe("packages/ui-react/src/theme.css"); - expect(generatedCssInputs(root,"packages/ui-kit/dist/theme.css")?.entry).toBe("packages/ui-kit/src/theme.css"); - expect(generatedCssInputs(root,"packages/ui-kit/dist/tokens.css")?.entry).toBe("packages/ui-kit/src/tokens.css"); - expect(generatedCssInputs(root,"packages/ui-react/dist/tokens.css")).toBeUndefined(); -}); -test("locked offline Tailwind CLI really derives changed bytes from owned stylesheet source",async()=>{ - const {root,write}=fixture();symlinkSync(join(repo,"node_modules"),join(root,"node_modules"),"dir"); - write("packages/ui-react/src/styles.css",'@import "tailwindcss" source(none); .marker { color: red; }'); - async function compile(){const child=Bun.spawn([process.execPath,"--preload",join(repo,"scripts/test-network-child-preload.ts"),join(repo,"node_modules/@tailwindcss/cli/dist/index.mjs"),"-i",join(root,"packages/ui-react/src/styles.css"),"-o",join(root,"result.css"),"--minify"],{cwd:root,stdout:"pipe",stderr:"pipe"}); - const [,error,exit]=await Promise.all([new Response(child.stdout).text(),new Response(child.stderr).text(),child.exited]);expect(exit,error).toBe(0);return readFileSync(join(root,"result.css"),"utf8");} - const before=await compile();expect(before).toContain(".marker");write("packages/ui-react/src/styles.css",'@import "tailwindcss" source(none); .marker { color: blue; }'); - const after=await compile();expect(after).toContain(".marker");expect(after).not.toBe(before); -}); - -test("only audited filesystem reader commands bind the generated stylesheet cwd",()=>{ - const {root,write}=fixture();const owner="packages/ui-kit/tests/visual/form-browser.ts"; - const original=frozenGeneratedSource(owner);write(owner,original); - expect(generatedCssReadInputs(root,owner,"../ui-react/dist/styles.css")?.entry).toBe("packages/ui-react/src/styles.css"); - expect(generatedCssReadInputs(root,owner,"../../outside/styles.css")).toBeUndefined(); - expect(generatedCssReadInputs(root,"other.ts","../ui-react/dist/styles.css")).toBeUndefined(); - const closure=discoverInputClosure(root,[owner]); - expect(closure.unresolved.some(value=>value.includes('readFile(resolve("../ui-react/dist/styles.css"), "utf8")'))).toBe(false); - write(owner,original+'\n// reader drift\n'); - expect(generatedCssReadInputs(root,owner,"../ui-react/dist/styles.css")).toBeUndefined(); - expect(discoverInputClosure(root,[owner]).unresolved.some(value=>value.includes('readFile(resolve("../ui-react/dist/styles.css"), "utf8")'))).toBe(true); -}); - -// Keep real candidate drift separate from independently owned positives. -test("current producer bytes qualify only when they match the frozen audit",()=>{ - for(const file of producer){ - const {root,write}=fixture(),current=readFileSync(join(repo,file),"utf8"); - write(file,current); - const binding=generatedCssInputs(root,"packages/ui-react/dist/styles.css"); - if(current===frozenGeneratedSource(file)) expect(binding?.entry,"UNCHANGED_PRODUCER_RETAINS_BINDING").toBe("packages/ui-react/src/styles.css"); - else expect(binding,"CURRENT_PRODUCER_DRIFT_REQUIRES_FRESH_PROOF").toBeUndefined(); - } -}); diff --git a/tests/generated-theme-inputs.test.ts b/tests/generated-theme-inputs.test.ts deleted file mode 100644 index ca865e2b5e..0000000000 --- a/tests/generated-theme-inputs.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import {frozenGeneratedSource} from "./frozen-generated-source"; -import {afterEach,expect,test} from "bun:test"; -import {cpSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; -import {tmpdir} from "node:os"; -import {dirname,join,resolve} from "node:path"; -import {browserImporters} from "../scripts/bound-browser-runtime-inputs"; -import {generatedThemeInputs} from "../scripts/generated-theme-inputs"; -const repo=resolve(import.meta.dir,".."),roots:string[]=[],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"; -const producers=["scripts/build.ts","scripts/build-execution.ts","scripts/build-receipt.ts","scripts/build-repeat-observation.ts","scripts/bin-modes.ts","scripts/publishable-packages.ts","scripts/workspace-lease.mjs","scripts/ci-proof.ts","scripts/check-pr.ts","scripts/ci-runner.ts",".github/workflows/ci.yml","package.json","bun.lock","packages/ui-react/src/theme.css","packages/ui-react/package.json"]; -// The reviewed Storage caller has its own committed positive fixture. Shared -// producer inputs retain their independent main owner; current config edits -// cannot redefine this positive, and feature-branch Git history is not required. -const callerFixture=new URL("./fixtures/generated-theme-vitest.config.txt",import.meta.url); -afterEach(()=>{for(const root of roots.splice(0))rmSync(root,{recursive:true,force:true});}); -function fixture(){const root=mkdtempSync(join(tmpdir(),"generated-theme-"));roots.push(root);const write=(file:string,text:string)=>{mkdirSync(dirname(join(root,file)),{recursive:true});writeFileSync(join(root,file),text);};for(const file of [...producers,owner,caller,entry])write(file,file===caller?readFileSync(callerFixture,"utf8"):frozenGeneratedSource(file));symlinkSync(join(repo,"node_modules"),join(root,"node_modules"),"dir");return{root,write};} -test("temporary theme output binds the audited command, copied theme and installed compiler",()=>{ - const {root}=fixture(),files=[owner,caller],bound=generatedThemeInputs(root,files,browserImporters(root,files)); - expect(bound?.css).toEqual([entry,"packages/ui-react/src/theme.css"]); - expect(bound?.compiler.package).toBe("@tailwindcss/cli");expect(bound?.compiler.asset).toBe("dist/index.mjs"); - expect(bound?.bytes).toContain("scripts/build.ts");expect(bound?.aliases.get("execFile")?.has("promisify(execFile)")).toBe(true); -}); -test("command, input, execution-order drift and extra callers refuse the generated theme binding",()=>{ - for(const file of [owner,caller,entry,"scripts/build.ts"]){const {root,write}=fixture();write(file,readFileSync(join(root,file),"utf8")+"\n/* drift */\n");expect(generatedThemeInputs(root,[owner,caller],browserImporters(root,[owner,caller]))).toBeUndefined();} - const {root,write}=fixture();write("extra.ts",`export {dictationThemeStyles} from "./${owner}";`);const files=[owner,caller,"extra.ts"]; - expect(generatedThemeInputs(root,files,browserImporters(root,files))).toBeUndefined(); -}); -test("actual temporary-theme command compiles owned source and propagates a broken compiler input",async()=>{ - const {root,write}=fixture();rmSync(join(root,"node_modules"));mkdirSync(join(root,"node_modules/@schlessera"),{recursive:true}); - for(const name of readdirSync(join(repo,"node_modules")))if(name!=="@schlessera")symlinkSync(join(repo,"node_modules",name),join(root,"node_modules",name)); - for(const name of ["ui-react","ui-kit"]){ - write(`packages/${name}/package.json`,readFileSync(join(repo,`packages/${name}/package.json`),"utf8")); - symlinkSync(join(root,`packages/${name}`),join(root,`node_modules/@schlessera/brain-${name}`),"dir"); - } - // Reproduce the real builder's byte-for-byte theme/token copy stages. The - // source scan belongs to this fixture, never the caller's current dist. - cpSync(join(repo,"packages/ui-react/src"),join(root,"packages/ui-react/src"),{recursive:true}); - write("packages/ui-react/dist/theme.css",readFileSync(join(repo,"packages/ui-react/src/theme.css"),"utf8")); - write("packages/ui-kit/dist/tokens.css",readFileSync(join(repo,"packages/ui-kit/src/tokens.css"),"utf8")); - async function compile(){ - const child=Bun.spawn([process.execPath,"--eval",`const {dictationThemeStyles}=await import(${JSON.stringify(join(root,owner))});console.log(await dictationThemeStyles());`],{cwd:join(root,"packages/ui-kit"),stdout:"pipe",stderr:"pipe"}); - const [out,error,exit]=await Promise.all([new Response(child.stdout).text(),new Response(child.stderr).text(),child.exited]);return{out,error,exit}; - } - const before=await compile();expect(before.exit,before.error).toBe(0);expect(before.out).toContain("--bk-color-canvas"); - write(entry,readFileSync(join(root,entry),"utf8")+"\n@import './missing-owned-source.css';\n"); - const broken=await compile();expect(broken.exit).not.toBe(0);expect(broken.error).toContain("missing-owned-source.css"); -}); diff --git a/tests/heavy-feedback.test.ts b/tests/heavy-feedback.test.ts index 38201cc64c..c08413ec1a 100644 --- a/tests/heavy-feedback.test.ts +++ b/tests/heavy-feedback.test.ts @@ -8,7 +8,7 @@ import { heavyFeedbackWorkflowProblems } from "../scripts/check-ci-workflows"; import { requestHeavyFeedback, type GH } from "../scripts/request-heavy-feedback"; import { verifyIntegrationProof } from "../scripts/integration-proof"; import { MAX_MS } from "../scripts/integration-reservation"; -import type { API } from "../scripts/proof-reuse"; +import type { API } from "../scripts/proof-api"; const ROOT = resolve(import.meta.dir, ".."); const REPO = "odysseus/brain-kit"; diff --git a/tests/hosted-proof.test.ts b/tests/hosted-proof.test.ts index 1ba0d23b20..23f63c00b3 100644 --- a/tests/hosted-proof.test.ts +++ b/tests/hosted-proof.test.ts @@ -6,7 +6,6 @@ import { categoryCommands, proofProblems, PROOF_JOBS, unitFiles } from "../scrip import { planChecks, proofSelections, workspaces, type Workspace } from "../scripts/ci-plan"; import { discoverTests } from "../scripts/test-shards"; import { localChecks } from "../scripts/check-pr"; -import { checkout } from "../scripts/proof-inputs"; const ROOT = resolve(import.meta.dir, ".."); const directories: string[] = []; @@ -25,7 +24,7 @@ test("only hosted single-workspace pack and browser builds opt into two compiler }); afterEach(() => { for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true }); }); function receipt(selected = true): { changeset: { result: string; outputs: Record } } & Record }> { - return { changeset: { result: "success", outputs: { ...Object.fromEntries(PROOF_JOBS.map(name => [name, String(selected)])), reuse: JSON.stringify({ version: 1, checkout: checkout(ROOT), retained: {} }) } }, + return { changeset: { result: "success", outputs: Object.fromEntries(PROOF_JOBS.map(name => [name, String(selected)])) }, ...Object.fromEntries(PROOF_JOBS.map(name => [name, { result: selected ? "success" : "skipped" }])) }; } @@ -39,6 +38,13 @@ test("aggregate accepts actual selected passes and intentional exclusions only", } const missing = receipt(); delete missing.unit; expect(proofProblems(missing)).toContain("unit: selected proof did not pass (missing)"); + // Retention is retired (#4107): nothing excuses a selected browser or layout job that did not run. + for (const name of ["browser", "layout"] as const) { + const dropped = receipt(); delete dropped[name]; + expect(proofProblems(dropped), `DROPPED_SELECTED_JOB_FAILS:${name}`).toEqual([`${name}: selected proof did not pass (missing)`]); + const skipped = receipt(); skipped[name] = { result: "skipped" }; + expect(proofProblems(skipped), `SKIPPED_SELECTED_JOB_FAILS:${name}`).toEqual([`${name}: selected proof did not pass (skipped)`]); + } const invalid = receipt(); delete invalid.changeset.outputs.runtime; expect(proofProblems(invalid)).toContain("runtime: selection output is missing or invalid"); for (const state of ["failure", "cancelled", "skipped"]) { @@ -49,14 +55,14 @@ test("aggregate accepts actual selected passes and intentional exclusions only", expect(proofProblems(unexpected)).toContain("browser: unselected job must be intentionally skipped (success)"); }); -test("emitted aggregate executable fails a cancelled selected job and accepts its corrected receipt", async () => { - for (const result of ["cancelled", "success"]) { +test("emitted aggregate executable fails a cancelled or skipped selected job and accepts its corrected receipt", async () => { + for (const result of ["cancelled", "skipped", "success"]) { const needs = receipt(); needs.layout.result = result; const child = Bun.spawn([process.execPath, "scripts/ci-proof.ts", "aggregate"], { cwd: ROOT, env: { ...process.env, GITHUB_ACTIONS: "false", GITHUB_EVENT_PATH: "", PROOF_NEEDS: JSON.stringify(needs) }, stdout: "pipe", stderr: "pipe" }); const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); expect(code, err).toBe(result === "success" ? 0 : 1); - if (result === "cancelled") expect(err).toContain("layout: selected proof did not pass (cancelled)"); + if (result !== "success") expect(err).toContain(`layout: selected proof did not pass (${result})`); else { expect(out).toContain("All selected hosted proof passed"); const line = out.split("\n").find(line => line.startsWith("BRAIN_SELECTED_PROOF_RECEIPT ")); diff --git a/tests/inclusion-inputs.test.ts b/tests/inclusion-inputs.test.ts deleted file mode 100644 index 9cef1cf0cd..0000000000 --- a/tests/inclusion-inputs.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import {frozenGeneratedSource} from "./frozen-generated-source"; -import { afterEach, expect, test } from "bun:test"; -import { chmodSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join, resolve } from "node:path"; -import { inclusionInputs } from "../scripts/inclusion-inputs"; -import { git, type Spec } from "../scripts/proof-inputs"; -const roots: string[] = []; -afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); -const spec = "packages/ui-kit/tests/visual/one.visual.tsx", second = "packages/ui-kit/tests/visual/two.visual.tsx"; -const inventory: Spec[] = [spec, second].map(file => ({ project: "ui-react-layout", file })); -function write(root: string, file: string, text: string) { mkdirSync(dirname(join(root, file)), { recursive: true }); writeFileSync(join(root, file), text); } -function commit(root: string) { git(root, "add", "."); git(root, "-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "-c", "commit.gpgsign=false", "commit", "-qm", "fixture"); return git(root, "rev-parse", "HEAD").trim(); } -function fixture() { - const root = mkdtempSync(join(tmpdir(), "inclusion-inputs-")); roots.push(root); git(root, "init", "-q"); git(root, "config", "commit.gpgsign", "false"); - write(root, ".gitignore", "node_modules\n"); symlinkSync(resolve(import.meta.dir, "../node_modules"), join(root, "node_modules"), "dir"); - for (const path of ["package.json", "bun.lock", "tsconfig.json"]) write(root, path, "{}\n"); - for (const path of ["bunfig.toml", ".github/workflows/ci.yml", "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/visual.mjs", "scripts/build.ts", "scripts/workspace-lease.mjs", "packages/ui-kit/src/styles.css", "packages/ui-react/src/styles.css"]) write(root, path, ""); - write(root, "packages/ui-kit/tests/proof-inputs.json", "[]"); write(root, "scripts/css-proof-inputs.json", "[]"); write(root, "scripts/browser-shard-costs.json", JSON.stringify({ seconds: { [`ui-react-layout::${spec}`]: 1 } })); - write(root, spec, `import "../../../src/fixture.ts";\n`); write(root, "packages/src/fixture.ts", "export const value = 1;\n"); write(root, second, "export {};\n"); commit(root); return root; -} -test("inclusion hashes transitive immutable blobs and modes while unrelated prose can change", () => { - const root = fixture(), initial = inclusionInputs(root, "layout", inventory, "fixed-runner"); - write(root, "docs/unrelated.md", "unrelated\n"); commit(root); - expect(inclusionInputs(root, "layout", inventory, "fixed-runner").fingerprint).toBe(initial.fingerprint); - write(root, "packages/src/fixture.ts", "export const value = 2;\n"); commit(root); - expect(inclusionInputs(root, "layout", inventory, "fixed-runner").fingerprint).not.toBe(initial.fingerprint); - const beforeMode = inclusionInputs(root, "layout", inventory, "fixed-runner"); chmodSync(join(root, spec), 0o755); commit(root); - expect(inclusionInputs(root, "layout", inventory, "fixed-runner").fingerprint).not.toBe(beforeMode.fingerprint); -}); -test("immutable source closure never reads current files, and changed resolution policy fails fresh", () => { - const root = fixture(), source = commitIfNeeded(root), original = inclusionInputs(root, "layout", inventory, "fixed-runner"); - write(root, "packages/src/fixture.ts", "export const value = 3;\n"); commit(root); - expect(inclusionInputs(root, "layout", inventory, "fixed-runner", source).fingerprint).toBe(original.fingerprint); - write(root, "bun.lock", "changed resolution\n"); commit(root); - expect(() => inclusionInputs(root, "layout", inventory, "fixed-runner", source)).toThrow("algorithm or dependency"); -}); -function commitIfNeeded(root: string) { return git(root, "rev-parse", "HEAD").trim(); } -test("browser capability cannot become eligible merely by hiding a Worker constructor from syntax discovery",()=>{ - const root=fixture(),browserInventory=inventory.map(spec=>({...spec,project:"visual"})); - expect(()=>inclusionInputs(root,"browser",browserInventory,"fixed-runner")).toThrow("unvalidated selected Worker capability audit"); - write(root,spec,'const realm=globalThis; const Constructor=realm.Worker; export const make=()=>new Constructor("unowned.js");');commit(root); - expect(()=>inclusionInputs(root,"browser",browserInventory,"fixed-runner")).toThrow("unvalidated selected Worker capability audit"); -}); -test("undeclared computed runtime inputs and missing or symbolic source cannot authorize reuse", () => { - const root = fixture(); write(root, spec, "const value = await import(modulePath);\n"); commit(root); - expect(() => inclusionInputs(root, "layout", inventory, "fixed-runner")).toThrow("Unresolved immutable"); - write(root, spec, `import "../../../src/fixture.ts";\n`); rmSync(join(root, "packages/src/fixture.ts")); commit(root); - expect(() => inclusionInputs(root, "layout", inventory, "fixed-runner")).toThrow("Unresolved immutable"); - symlinkSync("/tmp/unknown-proof-input", join(root, "packages/src/fixture.ts")); commit(root); - expect(() => inclusionInputs(root, "layout", inventory, "fixed-runner")).toThrow(); -}); - - -test("declared directory inputs hash tracked additions, deletion and rename identities", () => { - const root = fixture(); - write(root, spec, `import {readdirSync} from "node:fs"; readdirSync(target);\n`); - write(root, "data/one.md", "Ithaca\n"); - write(root, "packages/ui-kit/tests/proof-inputs.json", JSON.stringify([{ owner: spec, inputs: [{ expression: "readdirSync(target)", targets: ["data"] }] }])); commit(root); - const before = inclusionInputs(root, "layout", inventory, "fixed-runner").fingerprint; - write(root, "data/two.md", "Raft\n"); commit(root); - const added = inclusionInputs(root, "layout", inventory, "fixed-runner").fingerprint; expect(added).not.toBe(before); - renameSync(join(root, "data/two.md"), join(root, "data/renamed.md")); commit(root); - const renamed = inclusionInputs(root, "layout", inventory, "fixed-runner").fingerprint; expect(renamed).not.toBe(added); - rmSync(join(root, "data/renamed.md")); commit(root); - expect(inclusionInputs(root, "layout", inventory, "fixed-runner").fingerprint).toBe(before); -}); - -test("workspace source resolution stays inside its immutable snapshot instead of current install links", () => { - const root = fixture(); - write(root, "packages/lib/package.json", JSON.stringify({ name: "@schlessera/brain-ui-react", exports: { ".": { bun: "./src/index.ts", default: "./dist/index.js" } } })); - write(root, "packages/lib/src/index.ts", "export const value = 1;\n"); - write(root, spec, `import "@schlessera/brain-ui-react";\n`); const source = commit(root); - const original = inclusionInputs(root, "layout", inventory, "fixed-runner"); - write(root, "packages/lib/src/index.ts", "export const value = 2;\n"); commit(root); - expect(inclusionInputs(root, "layout", inventory, "fixed-runner", source).fingerprint).toBe(original.fingerprint); - expect(inclusionInputs(root, "layout", inventory, "fixed-runner").fingerprint).not.toBe(original.fingerprint); -}); - -test("validated installed asset bytes and mode join immutable source fingerprints",()=>{ - const root=fixture();rmSync(join(root,"node_modules"));mkdirSync(join(root,"node_modules")); - const installed=resolve(import.meta.dir,"../node_modules"); - for(const entry of readdirSync(installed)) if(entry!=="axe-core") symlinkSync(join(installed,entry),join(root,"node_modules",entry),"dir"); - const owner="packages/ui-react/tests/browser/offline/cold-capture/commands.ts"; - for(const file of [owner,"scripts/build.ts","scripts/build-execution.ts","scripts/build-receipt.ts","scripts/build-repeat-observation.ts","scripts/bin-modes.ts","scripts/publishable-packages.ts","scripts/workspace-lease.mjs","scripts/ci-proof.ts","scripts/check-pr.ts","scripts/ci-runner.ts",".github/workflows/ci.yml","package.json","packages/ui-react/package.json","packages/ui-kit/package.json"]) - write(root,file,frozenGeneratedSource(file)); - write(root,spec,`import "../../../ui-react/tests/browser/offline/cold-capture/commands.ts";`); - write(root,"node_modules/axe-core/package.json",JSON.stringify({name:"axe-core",version:"4.13.0"}));write(root,"node_modules/axe-core/axe.min.js","owned asset before");commit(root); - const initial=inclusionInputs(root,"layout",inventory,"fixed-runner").fingerprint; - write(root,"node_modules/axe-core/axe.min.js","owned asset after"); - expect(inclusionInputs(root,"layout",inventory,"fixed-runner").fingerprint).not.toBe(initial); - const beforeMode=inclusionInputs(root,"layout",inventory,"fixed-runner").fingerprint;chmodSync(join(root,"node_modules/axe-core/axe.min.js"),0o755); - expect(inclusionInputs(root,"layout",inventory,"fixed-runner").fingerprint).not.toBe(beforeMode); - rmSync(join(root,"node_modules/axe-core/axe.min.js")); - expect(()=>inclusionInputs(root,"layout",inventory,"fixed-runner")).toThrow("Unresolved immutable"); -}); - -test("selected Vitest screenshot baselines are immutable proof inputs",()=>{ - const root=fixture(),baseline="packages/ui-kit/tests/visual/__screenshots__/one.visual.tsx/owned-chromium-linux.png"; - write(root,spec,'expect(subject).toMatchScreenshot("owned");');write(root,baseline,"first pinned image bytes");commit(root); - const original=inclusionInputs(root,"layout",inventory,"fixed-runner").fingerprint; - write(root,baseline,"changed pinned image bytes");commit(root); - expect(inclusionInputs(root,"layout",inventory,"fixed-runner").fingerprint,"SCREENSHOT_BASELINE_CONTENT_INVALIDATES_RETAINED_PROOF").not.toBe(original); -}); - -test("baseline additions, renames, deletion, mode and immutable source use actual tracked image identity",()=>{ - const root=fixture(),directory="packages/ui-kit/tests/visual/__screenshots__/one.visual.tsx",baseline=directory+"/owned-chromium-linux.png"; - write(root,spec,'expect(subject).toMatchScreenshot("owned");');write(root,baseline,"original image");const source=commit(root),original=inclusionInputs(root,"layout",inventory,"fixed-runner").fingerprint; - write(root,directory+"/added.png","added image");commit(root);const added=inclusionInputs(root,"layout",inventory,"fixed-runner").fingerprint;expect(added).not.toBe(original); - renameSync(join(root,directory+"/added.png"),join(root,directory+"/renamed.png"));commit(root);expect(inclusionInputs(root,"layout",inventory,"fixed-runner").fingerprint).not.toBe(added); - rmSync(join(root,directory+"/renamed.png"));commit(root);expect(inclusionInputs(root,"layout",inventory,"fixed-runner").fingerprint).toBe(original); - chmodSync(join(root,baseline),0o755);commit(root);expect(inclusionInputs(root,"layout",inventory,"fixed-runner").fingerprint).not.toBe(original); - expect(inclusionInputs(root,"layout",inventory,"fixed-runner",source).fingerprint).toBe(original); -}); -test("custom screenshot directories, resolvers and computed options stay fresh",()=>{ - for(const body of ['expect(subject).toMatchScreenshot("owned",{resolveScreenshotPath:()=>"/unowned.png"});','const options=externalOptions;expect(subject).toMatchScreenshot("owned",options);','const options={comparatorOptions:{threshold:0}};Object.assign(options,external);expect(subject).toMatchScreenshot("owned",options);']){const root=fixture();write(root,spec,body);commit(root);expect(()=>inclusionInputs(root,"layout",inventory,"fixed-runner")).toThrow("Unsupported screenshot");} - const root=fixture();write(root,spec,'expect(subject).toMatchScreenshot("owned");');write(root,"packages/ui-kit/vitest.config.ts",'export default {test:{browser:{screenshotDirectory:"/unowned"}}};');commit(root);expect(()=>inclusionInputs(root,"layout",inventory,"fixed-runner")).toThrow("Unsupported screenshot"); -}); -test("a screenshot-directory symlink cannot hide an external baseline behind absent tracked children",()=>{ - for(const suffix of ["", "/one.visual.tsx"]){const root=fixture(),directory="packages/ui-kit/tests/visual/__screenshots__"+suffix;write(root,spec,'expect(subject).toMatchScreenshot("owned");');mkdirSync(dirname(join(root,directory)),{recursive:true});symlinkSync("/tmp/unowned-baselines",join(root,directory));commit(root);expect(()=>inclusionInputs(root,"layout",inventory,"fixed-runner")).toThrow("Screenshot directory");} -}); diff --git a/tests/integration-command.test.ts b/tests/integration-command.test.ts index 12b4a537b4..1781270958 100644 --- a/tests/integration-command.test.ts +++ b/tests/integration-command.test.ts @@ -133,6 +133,7 @@ fi`); chmodSync(shim, 0o755); if(s.mode==="receipt-uncovered"){selected.selections.unit="false";} if(s.mode==="missing-selection")delete selected.selections.endurance; if(s.mode==="unexpected-skip"){selected.selections.endurance="true";selected.results.endurance="success";} + if(s.mode==="retained-receipt"){selected.selections.browser="true";selected.results.browser="skipped";selected.retained=["browser"];} const job=(id,name,conclusion="success")=>({id,name,status:"completed",conclusion,run_id:91,head_sha:head}); const jobs=[job(1,"changeset"),job(2,"proof"),...categories.flatMap((name,index)=>name==="browser"&&s.mode.startsWith("browser-") ?[1,2,3].filter(shard=>s.mode!=="browser-missing-third"||shard!==3).map(shard=>job(20+shard,"browser ("+shard+")")) @@ -427,6 +428,11 @@ test("shared merge executable requires all three delivered browser shards", asyn expect(missing.dispatched, "NO_MERGE_WITH_MISSING_THIRD_BROWSER_SHARD").toBe(false); expect(missing.code).toBe(1); expect(missing.err).toContain("Actual selected job inventory differs"); + // Retention is retired (#4107): a receipt excusing a skipped selected browser job is not proof. + const retained = await scenario("retained-receipt"); + expect(retained.dispatched, "NO_MERGE_ON_RETAINED_BROWSER_PROOF").toBe(false); + expect(retained.code).toBe(1); + expect(retained.err).toContain("Retained proof is retired"); }); test("delivered issues accepts 22 and the finite boundary with every milestone read back", async () => { diff --git a/tests/integration-proof.test.ts b/tests/integration-proof.test.ts index 236f23f13f..15021643d0 100644 --- a/tests/integration-proof.test.ts +++ b/tests/integration-proof.test.ts @@ -1,7 +1,7 @@ import { expect, test } from "bun:test"; import { verifyIntegrationProof } from "../scripts/integration-proof"; import { scanText } from "../scripts/check-leakage"; -import type { API } from "../scripts/proof-reuse"; +import type { API } from "../scripts/proof-api"; const candidate = { repository: "https://github.com/odysseus/brain-kit", pr: 7, head: "a".repeat(40), base: "b".repeat(40) }; const job = { id: 19, name: "changeset", status: "completed", conclusion: "success", run_id: 17, head_sha: candidate.head }; diff --git a/tests/locked-browser-assets.test.ts b/tests/locked-browser-assets.test.ts deleted file mode 100644 index 79d36f9197..0000000000 --- a/tests/locked-browser-assets.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { afterEach, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join, resolve } from "node:path"; -import { createHash } from "node:crypto"; -import { auditedReaderDigest, lockedBrowserAsset } from "../scripts/locked-browser-assets"; -import { frozenGeneratedSource } from "./frozen-generated-source"; -const roots:string[]=[],repo=resolve(import.meta.dir,".."),owner="packages/ui-react/tests/browser/offline/cold-capture/commands.ts",literal="../../node_modules/axe-core/axe.min.js"; -afterEach(()=>{for(const root of roots.splice(0))rmSync(root,{recursive:true,force:true});}); -function fixture(){const root=mkdtempSync(join(tmpdir(),"locked-browser-asset-"));roots.push(root); - const write=(file:string,text:string)=>{mkdirSync(dirname(join(root,file)),{recursive:true});writeFileSync(join(root,file),text);}; - write(owner,frozenGeneratedSource(owner));write("package.json","{}");write("bun.lock","{}");write("node_modules/axe-core/package.json",JSON.stringify({name:"axe-core",version:"4.13.0"}));write("node_modules/axe-core/axe.min.js","owned bytes");return{root,write};} -test("only exact audited dependency asset readers admit bytes; missing, escaped and symbolic inputs stay unknown",()=>{ - const {root,write}=fixture();expect(lockedBrowserAsset(root,owner,literal)?.package).toBe("axe-core"); - expect(lockedBrowserAsset(root,"unowned.ts",literal)).toBeUndefined();expect(lockedBrowserAsset(root,owner,"../../node_modules/other/file.js")).toBeUndefined(); - write(owner,frozenGeneratedSource(owner)+"\n// drift");expect(lockedBrowserAsset(root,owner,literal)).toBeUndefined();write(owner,frozenGeneratedSource(owner)); - write("node_modules/axe-core/package.json",JSON.stringify({name:"other",version:"4.13.0"}));expect(lockedBrowserAsset(root,owner,literal)).toBeUndefined(); - write("node_modules/axe-core/package.json",JSON.stringify({name:"axe-core",version:"4.13.0"})); - rmSync(join(root,"node_modules/axe-core/axe.min.js"));expect(lockedBrowserAsset(root,owner,literal)).toBeUndefined(); - write("outside.js","other bytes");symlinkSync(join(root,"outside.js"),join(root,"node_modules/axe-core/axe.min.js"));expect(lockedBrowserAsset(root,owner,literal)).toBeUndefined(); -}); -// #2408 (maintainer ruling 2026-11-04): an audited reader that drifts from its -// pin leaves its asset unknown, so proof runs fresh, until a post-merge re-audit -// refreshes the pin. The repo's own reader is therefore held to whichever branch -// its bytes are on, and a drifted reader can never yield a receipt. -test("the repo reader yields the installed receipt only while it matches its audited pin; drift stays unknown",async()=>{ - const pinned=createHash("sha256").update(readFileSync(join(repo,owner))).digest("hex")===auditedReaderDigest(owner); - const resource=lockedBrowserAsset(repo,owner,literal); - if(!pinned){expect(resource,"DRIFTED_READER_BINDING_UNKNOWN").toBeUndefined();return;} - expect(resource,"PINNED_READER_RECEIPT").toBeDefined(); - const manifest=JSON.parse(readFileSync(join(repo,"node_modules/axe-core/package.json"),"utf8"));expect(resource?.version).toBe(manifest.version); - const digest=Buffer.from(await crypto.subtle.digest("SHA-256",await Bun.file(join(repo,"node_modules/axe-core/axe.min.js")).arrayBuffer())).toString("hex");expect(resource?.sha256).toBe(digest); -}); -test("the frozen audited reader matches its pin and yields the installed receipt",async()=>{ - const {root}=fixture();rmSync(join(root,"node_modules"),{recursive:true});symlinkSync(join(repo,"node_modules"),join(root,"node_modules"),"dir"); - const pin=auditedReaderDigest(owner);expect(pin,"READER_IS_AUDITED").toBeDefined();expect(createHash("sha256").update(frozenGeneratedSource(owner)).digest("hex"),"FROZEN_READER_MATCHES_PIN").toBe(pin!); - const resource=lockedBrowserAsset(root,owner,literal);expect(resource,"PINNED_READER_RECEIPT").toBeDefined(); - const manifest=JSON.parse(readFileSync(join(repo,"node_modules/axe-core/package.json"),"utf8"));expect(resource?.version).toBe(manifest.version); - const digest=Buffer.from(await crypto.subtle.digest("SHA-256",await Bun.file(join(repo,"node_modules/axe-core/axe.min.js")).arrayBuffer())).toString("hex");expect(resource?.sha256).toBe(digest); -}); diff --git a/tests/native-diagram-inputs.test.ts b/tests/native-diagram-inputs.test.ts deleted file mode 100644 index e16bae7e31..0000000000 --- a/tests/native-diagram-inputs.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import {afterEach,expect,test} from "bun:test"; -import assert from "node:assert/strict"; -import {chmodSync,cpSync,lstatSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,realpathSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; -import {tmpdir} from "node:os"; -import {dirname,join,resolve} from "node:path"; -import {diagramSourceSetup,diagramSourceDomains} from "../scripts/diagram-export-source.mjs"; -import {nativeDiagramInputs,nativeDiagramSourceInventory,type NativeDiagramDiagnostic} from "../scripts/native-diagram-inputs"; -const repo=resolve(import.meta.dir,".."),roots:string[]=[],owner="packages/ui-react/tests/browser/diagram-export-command.ts",caller="packages/ui-kit/vitest.config.ts"; -// Delivered #2293 owns the qualified bytes. Never substitute HEAD/worktree bytes, -// Git archive filters, or a newly computed candidate fingerprint for this control. -const frozen="0d780605fe1ea9a281cce947b1f0074f3f3e7acc"; -const qualifiedSource="e8502b6ffb3c575f2e9a1c93dea8dbf5ceda93ece367da9d542cb10b1c9ac32b"; -const qualifiedInstallation="ea866695f2a83f9da2fcf18e75e95e936668ecb28e1449845a2584aa1025b728"; -const ownedPaths=[...diagramSourceSetup,...diagramSourceDomains.map(name=>`packages/${name}`),owner,caller,"scripts/ci-proof.ts"]; -afterEach(()=>{for(const root of roots.splice(0))rmSync(root,{recursive:true,force:true});}); -function fixture(current=false,install?:(modules:string)=>void){ - const root=mkdtempSync(join(tmpdir(),"odysseus-native-inputs-"));roots.push(root); - const tree=Bun.spawnSync(["git","ls-tree","-r","-z",current?"HEAD":frozen,"--",...ownedPaths],{cwd:repo,stdout:"pipe",stderr:"pipe"}); - expect(tree.exitCode,"FROZEN_SOURCE_OWNER_MUST_BE_AVAILABLE_OFFLINE").toBe(0); - const entries=tree.stdout.toString().split("\0").filter(Boolean).map(row=>{const tab=row.indexOf("\t"),[mode,kind,oid]=row.slice(0,tab).split(" ");expect(kind).toBe("blob");expect(["100644","100755"]).toContain(mode);return{mode,oid,path:row.slice(tab+1)};}); - // Match the repository's immutable source protocol: read raw objects in one - // batch, verifying each header/length and complete output before using it. - const batch=Bun.spawnSync(["git","cat-file","--batch"],{cwd:repo,stdin:Buffer.from(entries.map(entry=>entry.oid).join("\n")+"\n"),stdout:"pipe",stderr:"pipe"}); - expect(batch.exitCode).toBe(0);const bytes=Buffer.from(batch.stdout);let offset=0; - for(const entry of entries){ - const end=bytes.indexOf(10,offset);expect(end).toBeGreaterThanOrEqual(offset); - const [oid,kind,length]=bytes.subarray(offset,end).toString("ascii").split(" "),size=Number(length); - expect(oid).toBe(entry.oid);expect(kind).toBe("blob");expect(Number.isSafeInteger(size)&&size>=0&&end+1+size`${top}/${name}`):[top];for(const name of names){if(name.startsWith("@schlessera/"))continue;const target=join(root,"node_modules",name);mkdirSync(dirname(target),{recursive:true});symlinkSync(realpathSync(join(repo,"node_modules",name)),target,"dir");}} - let diagnostic:NativeDiagramDiagnostic|undefined; - const importers=new Map([[owner,new Set([caller])]]),bind=()=>nativeDiagramInputs(root,[owner,caller],importers,value=>{diagnostic=value;}); - return{root,importers,bind,diagnostic:()=>diagnostic}; -} -function sourceRefused(control:ReturnType,name:string){ - expect(control.bind(),name).toBeUndefined();const diagnostic=control.diagnostic(); - assert(diagnostic,"UNKNOWN_NATIVE_BINDING_MUST_REPORT_DIAGNOSTIC"); - expect(diagnostic.status,"UNKNOWN_NATIVE_BINDING_HAS_REASON").toBe("source-mismatch"); - assert(diagnostic.actual?.source,"SOURCE_REFUSAL_MUST_REPORT_ACTUAL_IDENTITY"); - expect(diagnostic.expected.source).toBe(qualifiedSource); - expect(diagnostic.actual.source).not.toBe(diagnostic.expected.source); - expect(diagnostic.actual.installation).toBe(qualifiedInstallation); - expect(JSON.stringify(diagnostic)).not.toContain(control.root); -} -test("fixed native qualification binds the independently frozen complete source without Docker or image lookup",()=>{ - const control=fixture(),path=process.env.PATH,bin=join(control.root,"commands");mkdirSync(bin);symlinkSync(realpathSync(process.execPath),join(bin,"bun")); - try{ - process.env.PATH=bin;const binding=control.bind(); - expect(control.diagnostic(),"FROZEN_NATIVE_INSTALLATION_MUST_MATCH_QUALIFIED_BYTES: reinstall this owned checkout under umask 022 from a fresh private cache (CONTRIBUTING.md); never refresh qualification pins").toMatchObject({ - status:"qualified",stage:"complete",sourceInputs:859, - actual:{source:qualifiedSource,installation:qualifiedInstallation}, - installation:{packages:930,files:66881,bytes:1374331961} - }); - expect(binding?.files.length,"COMPLETE_NATIVE_QUALIFICATION_WITHOUT_DOCKER_OR_IMAGE_LOOKUP").toBe(859); - expect(binding?.files.toSorted()).toEqual(nativeDiagramSourceInventory(control.root).inputs.map(entry=>entry.path).toSorted()); - expect(binding?.identity.source).toBe(qualifiedSource);expect(binding?.identity.installation).toBe(qualifiedInstallation); - expect(control.diagnostic()?.status).toBe("qualified"); - }finally{if(path===undefined)delete process.env.PATH;else process.env.PATH=path;} -}); -test("an additional native importer requires fresh proof",()=>{ - const control=fixture();control.importers.get(owner)!.add("new-caller.ts"); - expect(control.bind(),"NATIVE_IMPORTER_REQUIRES_FRESH_PROOF").toBeUndefined();expect(control.diagnostic()?.status).toBe("unsealed-role"); -}); -test.each([owner,caller,"scripts/ci-proof.ts"])("changed pinned native input %s requires fresh proof",file=>{ - const control=fixture(),target=join(control.root,file);writeFileSync(target,readFileSync(target,"utf8")+"\n// changed native operation\n"); - expect(control.bind(),"NATIVE_PIN_REQUIRES_FRESH_PROOF").toBeUndefined();expect(control.diagnostic()?.status).toBe("source-pin-mismatch"); - const pin=control.diagnostic()?.pins?.find(pin=>pin.path===file); - assert(pin,"PIN_REFUSAL_MUST_REPORT_EXPECTED_PIN");assert(pin.actual,"PIN_REFUSAL_MUST_REPORT_ACTUAL_PIN"); - expect(pin.actual).not.toBe(pin.expected); -}); -test("added package source requires native requalification",()=>{ - const control=fixture();writeFileSync(join(control.root,"packages/core/src/unused-native-probe.ts"),"export const Odysseus=1;"); - sourceRefused(control,"NATIVE_SOURCE_ADDITION_REQUIRES_REQUALIFICATION"); -}); -test("changed package content requires native requalification",()=>{ - const control=fixture(),target=join(control.root,"packages/core/src/cli/brain.ts");writeFileSync(target,readFileSync(target,"utf8")+"\n// changed package content\n"); - sourceRefused(control,"NATIVE_SOURCE_CONTENT_REQUIRES_REQUALIFICATION"); -}); -test("changed package executable mode requires native requalification",()=>{ - const control=fixture(),target=join(control.root,"packages/core/src/cli/brain.ts");chmodSync(target,(lstatSync(target).mode&0o777)^0o111); - sourceRefused(control,"NATIVE_SOURCE_MODE_REQUIRES_REQUALIFICATION"); -}); -// An installer's umask narrows the modes it writes, and the installation identity -// includes modes. Simulate one package written under each umask. -const syntheticInstall=(mask:number)=>(modules:string)=>{ - const previous=process.umask(mask); - try{ - const base=join(modules,"odysseus-ledger");mkdirSync(join(base,"bin"),{recursive:true,mode:0o755}); - writeFileSync(join(base,"package.json"),JSON.stringify({name:"odysseus-ledger",version:"1.0.0"}),{mode:0o644}); - writeFileSync(join(base,"bin/ledger.js"),"#!/usr/bin/env bun\nconsole.log(\"Ithaca\");\n",{mode:0o755}); - }finally{process.umask(previous);} -}; -test("an install under umask 0077 is refused with the umask 022 recovery, and that recovery restores its identity",()=>{ - const restrictive=fixture(false,syntheticInstall(0o077)),reference=fixture(false,syntheticInstall(0o022)); - expect(restrictive.bind(),"RESTRICTIVE_UMASK_INSTALL_IS_REFUSED").toBeUndefined(); - const refused=restrictive.diagnostic();assert(refused,"RESTRICTIVE_UMASK_REFUSAL_MUST_REPORT_DIAGNOSTIC"); - expect(refused.status).toBe("installation-mismatch");expect(refused.actual?.source).toBe(qualifiedSource); - expect(refused.recovery,"INSTALLATION_REFUSAL_NAMES_THE_REQUIRED_UMASK").toContain("umask 022"); - expect(refused.recovery,"INSTALLATION_REFUSAL_NAMES_THE_INSTALL_COMMAND").toContain("sh scripts/prepare-diagnostic-install.sh"); - expect(JSON.stringify(refused)).not.toContain(restrictive.root); - reference.bind();const expected=reference.diagnostic();assert(expected?.actual?.installation,"REFERENCE_INSTALL_MUST_REPORT_IDENTITY"); - // Same packages, files and bytes: only the modes differ. - expect(refused.installation).toEqual(expected.installation);expect(refused.actual?.installation).not.toBe(expected.actual.installation); - // The documented recovery: replace the owned install under umask 022. - rmSync(join(restrictive.root,"node_modules/odysseus-ledger"),{recursive:true});syntheticInstall(0o022)(join(restrictive.root,"node_modules")); - restrictive.bind();expect(restrictive.diagnostic()?.actual?.installation,"UMASK_022_RECOVERY_RESTORES_THE_IDENTITY").toBe(expected.actual.installation); -}); -test("relocated installed native dependency requires fresh proof",()=>{ - const control=fixture(),clone=join(control.root,"relocated/marked");mkdirSync(dirname(clone));cpSync(realpathSync(join(control.root,"node_modules/marked")),clone,{recursive:true});rmSync(join(control.root,"node_modules/marked"));symlinkSync(clone,join(control.root,"node_modules/marked"),"dir"); - expect(control.bind(),"NATIVE_INSTALLED_ORIGIN_REQUIRES_FRESH_PROOF").toBeUndefined();expect(control.diagnostic()?.stage).toBe("installation");expect(control.diagnostic()?.errorCode,"UNKNOWN_INSTALLED_ORIGIN_HAS_BOUNDED_REASON").toBe("NATIVE_DEPENDENCY_ORIGIN_CHANGED"); -}); -test("the actual current candidate qualifies only when its complete frozen source and pins match",()=>{ - const control=fixture(true),source=nativeDiagramSourceInventory(control.root),binding=control.bind(),diagnostic=control.diagnostic(); - assert(diagnostic,"CURRENT_CANDIDATE_MUST_REPORT_DIAGNOSTIC"); - // A legitimate new file or pinned proof/caller edit is an unsupported operation, - // not a broken positive fixture. The frozen positive above must still qualify. - if(source.sha256===qualifiedSource&&diagnostic.pins?.every(pin=>pin.owned&&pin.actual===pin.expected)){ - expect(binding?.identity.source).toBe(qualifiedSource);expect(diagnostic?.status).toBe("qualified"); - }else{ - expect(binding,"CHANGED_CANDIDATE_MUST_KEEP_FRESH_NATIVE_PROOF").toBeUndefined();expect(["source-mismatch","source-pin-mismatch"]).toContain(diagnostic.status); - } -}); diff --git a/tests/native-diagram-retired.test.ts b/tests/native-diagram-retired.test.ts new file mode 100644 index 0000000000..3f68402c99 --- /dev/null +++ b/tests/native-diagram-retired.test.ts @@ -0,0 +1,30 @@ +// The frozen native diagram qualification is retired (#4105, maintainer ruling +// 2026-11-16). Its pins made every dependency change fail `unit` until a +// manual Docker requalification moved them. Nothing in the scripts or tests +// may pin those identities again: the producer's proof runs fresh in its +// container boundary, and its own run-time checks verify what it mounts. +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; + +const root = resolve(import.meta.dir, ".."); + +const RETIRED = [ + "e8502b6ffb3c575f2e9a1c93dea8dbf5ceda93ece367da9d542cb10b1c9ac32b", // frozen #2293 source + "ea866695f2a83f9da2fcf18e75e95e936668ecb28e1449845a2584aa1025b728", // last qualified installation + "e724696a55955e9f32d396b2031214600086533c3f9b8baabcc1c6bb7311f1db", // pinned ui-kit vitest config + // The diagram export command's own hash is not listed: no script pins a + // current source file any more, which tests/first-party-source-pins.test.ts holds. + "c58de06eba788b6b892416ddda3abb28fa1e8e908f25c0800482fbe05e0de678", // pinned ci-proof +]; + +test("no script or test pins the retired native diagram qualification", () => { + // Two patterns: Bun's glob matches nothing when a brace alternative holds a `/`. + const files = ["{scripts,tests}/**/*.{ts,tsx,mjs,js}", "packages/*/{tests,scripts}/**/*.{ts,tsx,mjs,js}"] + .flatMap((pattern) => [...new Bun.Glob(pattern).scanSync({ cwd: root, dot: false })]) + .filter((file) => !file.includes("node_modules") && file !== "tests/native-diagram-retired.test.ts"); + // The scan must see the files the binding lived in, or an empty glob passes vacuously. + expect(files, "SCAN_COVERS_THE_PROOF_SCRIPTS").toContain("scripts/browser-input-closure.ts"); + const pinned = files.flatMap((file) => RETIRED.filter((hash) => readFileSync(join(root, file), "utf8").includes(hash)).map((hash) => `${file}: ${hash.slice(0, 8)}`)); + expect(pinned, "NATIVE_DIAGRAM_QUALIFICATION_STAYS_RETIRED").toEqual([]); +}); diff --git a/tests/proof-reuse.test.ts b/tests/proof-reuse.test.ts deleted file mode 100644 index b3ee2782e0..0000000000 --- a/tests/proof-reuse.test.ts +++ /dev/null @@ -1,238 +0,0 @@ -import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join, resolve } from "node:path"; -import { browserInventory, checkout, git, normalizeInventory, proofInputs, runnerIdentity, type Inputs, type Spec } from "../scripts/proof-inputs"; -import { boundedLedger, contextFromEvent, findRetained, receiptFromLog, retainedCategories, validateSource, type API, type Context, type FreshReceipt, type Source } from "../scripts/proof-reuse"; -import { proofProblems, PROOF_JOBS } from "../scripts/ci-proof"; -import * as workerAudit from "../scripts/browser-worker-audit"; -import { PROOF_SHARDS, shardNumbers } from "../scripts/proof-shards"; -const roots: string[] = []; -// These are synthetic receipt/API protocol fixtures, not browser execution -// qualification. Keep real immutable fingerprint/source recomputation while -// modeling an admitted capability. Actual capability/refusal/native controls -// live in the worker-audit, inclusion and real browser proof tests. -let capability:ReturnType>; -beforeEach(()=>{capability=spyOn(workerAudit,"inspectWorkerAudit").mockReturnValue({qualified:true,diagnostic:{version:1,expectedIdentity:undefined,actualIdentity:undefined,reason:"isolated fingerprint fixture"}});}); -afterEach(()=>capability.mockRestore()); -afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); -const runner = "ubuntu-24.04/fixed/Linux/X64/bun-1.4.2"; -const layout = "packages/ui-react/tests/browser/one.layout.tsx"; -const secondLayout = "packages/ui-react/tests/browser/two.layout.tsx"; -const visual = "packages/ui-kit/tests/visual/one.visual.tsx"; -const secondVisual = "packages/ui-kit/tests/visual/two.visual.tsx"; -const shared = "packages/ui-react/tests/browser/shared.offline.tsx"; -const inventory: Spec[] = normalizeInventory([ - { project: "visual", file: visual }, { project: "visual", file: secondVisual }, - { project: "rail-fine", file: shared }, { project: "ui-react-layout", file: shared }, - { project: "ui-react-layout", file: layout }, { project: "ui-react-layout", file: secondLayout }, -]); -function write(root: string, file: string, text: string) { mkdirSync(dirname(join(root, file)), { recursive: true }); writeFileSync(join(root, file), text); } -function commit(root: string): string { - git(root, "add", "."); git(root, "-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "-c", "commit.gpgsign=false", "commit", "-qm", "fixture"); - return checkout(root).sha; -} -function fixture() { - const root = mkdtempSync(join(tmpdir(), "proof-reuse-")); roots.push(root); git(root, "init", "-q"); - git(root, "config", "commit.gpgsign", "false"); - for (const file of [layout, secondLayout, visual, secondVisual, shared]) write(root, file, "export {};\n"); - write(root, ".gitignore", "node_modules\n"); symlinkSync(resolve(import.meta.dir, "../node_modules"), join(root, "node_modules"), "dir"); - for (const path of ["package.json", "bun.lock", "tsconfig.json"]) write(root, path, "{}\n"); - for (const path of ["bunfig.toml", "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/visual.mjs", "scripts/build.ts", "scripts/workspace-lease.mjs", "packages/ui-kit/src/styles.css", "packages/ui-react/src/styles.css"]) write(root, path, ""); - write(root, "packages/ui-kit/tests/proof-inputs.json", "[]"); write(root, "scripts/css-proof-inputs.json", "[]"); - write(root, visual, `import "../../../core/fixtures/corpus/input.md";\n`); - write(root, "scripts/browser-shard-costs.json", JSON.stringify({ seconds: { [`visual::${visual}`]: 1 } })); - write(root, "scripts/ci-proof.ts", "// unchanged proof harness\n"); - write(root, ".github/workflows/ci.yml", "name: CI\n"); - write(root, "packages/core/fixtures/corpus/input.md", "Fixture source\n"); const base = commit(root); - write(root, "pr-input.txt", "immutable contribution\n"); const head = commit(root); - const merged = git(root, "-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "-c", "commit.gpgsign=false", "commit-tree", checkout(root).tree, "-p", base, "-p", head, "-m", "combined fixture").trim(); - git(root, "reset", "--hard", merged); - return root; -} -const context: Context = { repository: "schlessera/brain-kit", headRepository: "schlessera/brain-kit", branch: "chore/fixture", pr: 42, run: 100 }; -function evidence(root: string, inputs: Inputs) { - const identity = checkout(root); - const ids = shardNumbers("browser").map(shard => 100 + shard); - const receipts: FreshReceipt[] = shardNumbers("browser").map(shard => ({ version: 1, category: "browser", shard: `${shard}/${PROOF_SHARDS.browser}`, checkout: identity, inputs })); - const source: Source = { run: 90, attempt: 1, jobs: ids, checkout: identity, inputs }; - const calls: string[] = []; - const run = { id: 90, event: "pull_request", status: "completed", conclusion: "success", run_attempt: 1, - head_sha: identity.parents[1], head_branch: context.branch, path: ".github/workflows/ci.yml", head_repository: { full_name: context.headRepository }, repository: { full_name: context.repository }, created_at: new Date().toISOString() }; - const jobs = ids.map((id, i) => ({ id, run_id: 90, head_sha: identity.parents[1], name: `browser (${i + 1})`, status: "completed", conclusion: "success", check_run_url: `https://api.github.com/repos/${context.repository}/check-runs/${id}`, - steps: [{ name: "Complete browser proof", status: "completed", conclusion: "success" }] })); - const logs = receipts.map(r => `2026-07-12T00:00:00Z ${identity.sha}\n2026-07-12T00:00:01Z refs/remotes/pull/42/merge\n2026-07-12T00:00:02Z BRAIN_PROOF_RECEIPT ${JSON.stringify(r)}\n`); - const api: API = { - async json(path) { - calls.push(path); - if (path === "actions/runs/90/attempts/1") return run; - if (path === "actions/runs/90/attempts/1/jobs?per_page=100") return { total_count: jobs.length, jobs }; - if (path.startsWith("check-runs/")) return { id: Number(path.split("/").at(-1)), head_sha: identity.parents[1], status: "completed", conclusion: "success", app: { slug: "github-actions" } }; - if (path === `git/commits/${identity.sha}`) return { sha: identity.sha, tree: { sha: identity.tree }, parents: identity.parents.map(sha => ({ sha })) }; - throw new Error(`Unexpected API ${path}`); - }, - async log(id) { calls.push(`log/${id}`); return logs[id - 101]!; }, - }; - return { api, source, run, jobs, logs, calls }; -} -test("a changed foreign leaf retains browser inputs; shared specs and every source/fixture/harness invalidate them", () => { - const root = fixture(); const first = proofInputs(root, "browser", inventory, runner); - expect(first.version).toBe(2); expect(first.excluded).toEqual([]); - write(root, layout, "// changed layout-only assertion\n"); commit(root); - expect(proofInputs(root, "browser", inventory, runner).fingerprint).toBe(first.fingerprint); - const baseline = checkout(root).sha; - for (const file of [visual, shared, "packages/ui-kit/vite.config.ts", "scripts/ci-proof.ts", "packages/core/fixtures/corpus/input.md", "bun.lock"]) { - write(root, file, "changed\n"); commit(root); - expect(proofInputs(root, "browser", inventory, runner).fingerprint, file).not.toBe(first.fingerprint); - git(root, "reset", "--hard", baseline); git(root, "clean", "-fd"); - } - expect(proofInputs(root, "browser", inventory, runner + "/changed").fingerprint).not.toBe(first.fingerprint); -}); -test("imported foreign leaves join input closure; new discovery and partition ownership cannot disappear", () => { - const root = fixture(); write(root, visual, `import "../../../core/fixtures/corpus/input.md"; import "../../../ui-react/tests/browser/one.layout.tsx";\n`); commit(root); - const inputs = proofInputs(root, "browser", inventory, runner); expect(inputs.version).toBe(2); - write(root, layout, "changed\n"); commit(root); - expect(proofInputs(root, "browser", inventory, runner).fingerprint).not.toBe(inputs.fingerprint); - write(root, "packages/ui-kit/tests/visual/new.visual.tsx", "export {};\n"); commit(root); - const discovered = normalizeInventory([...inventory, { project: "visual", file: "packages/ui-kit/tests/visual/new.visual.tsx" }]); - expect(proofInputs(root, "browser", discovered, runner).partitions.flat()).toContain("visual::packages/ui-kit/tests/visual/new.visual.tsx"); - expect(() => proofInputs(root, "browser", inventory, runner, "HEAD", [shared])).toThrow("input ownership"); - expect(() => proofInputs(root, "browser", inventory, "")).toThrow("Unknown runner"); -}); -test("logs must contain one fresh receipt tied to the actual checkout and correct shard", () => { - const root = fixture(); const { logs } = evidence(root, proofInputs(root, "browser", inventory, runner)); - expect(receiptFromLog(logs[0]!, "browser", 1).checkout).toEqual(checkout(root)); - expect(() => receiptFromLog(logs[0]! + logs[0], "browser", 1)).toThrow("ambiguous"); - expect(() => receiptFromLog(logs[0]!.split("\n").slice(1).join("\n"), "browser", 1)).toThrow("actual job checkout"); - expect(() => receiptFromLog(logs[0]!, "browser", 2)).toThrow("Wrong fresh"); - // A receipt from the two-shard era names another partition and is never admitted (#2414). - expect(() => receiptFromLog(logs[0]!.replace(`"shard":"1/${PROOF_SHARDS.browser}"`, `"shard":"1/2"`), "browser", 1)).toThrow("Wrong fresh"); -}); -test("successful immutable source receipts validate against APIs", async () => { - const root = fixture(), inputs = proofInputs(root, "browser", inventory, runner); - const valid = evidence(root, inputs); - await validateSource(root, "browser", valid.source, inputs, context, valid.api); - expect(valid.calls.length).toBeGreaterThan(0); - // Retain the older checkout spelling alongside v7's actual remote ref. - valid.logs[0] = valid.logs[0]!.replace("refs/remotes/pull/42/merge", "refs/pull/42/merge"); - await validateSource(root, "browser", valid.source, inputs, context, valid.api); -}); -test("cancelled, missing, foreign and mismatched evidence is rejected", async () => { - const root = fixture(), inputs = proofInputs(root, "browser", inventory, runner); - for (const state of ["cancelled", "failure", "action_required", "waiting"]) { - const bad = evidence(root, inputs); bad.run.conclusion = state; - await expect(validateSource(root, "browser", bad.source, inputs, context, bad.api)).rejects.toThrow("successful automatic"); - } - const mismatch = evidence(root, inputs); mismatch.source.inputs = { ...inputs, fingerprint: "0".repeat(64) }; - await expect(validateSource(root, "browser", mismatch.source, inputs, context, mismatch.api)).rejects.toThrow("input equivalence"); - const missing = evidence(root, inputs); missing.jobs[1]!.conclusion = "skipped"; - await expect(validateSource(root, "browser", missing.source, inputs, context, missing.api)).rejects.toThrow("fresh successful job"); - const foreign = evidence(root, inputs); foreign.run.head_repository.full_name = "odysseus/other"; - await expect(validateSource(root, "browser", foreign.source, inputs, context, foreign.api)).rejects.toThrow("successful automatic"); - const forged = evidence(root, inputs); forged.logs[0] = forged.logs[0]!.replace("refs/remotes/pull/42/merge", "refs/remotes/pull/43/merge"); - await expect(validateSource(root, "browser", forged.source, inputs, context, forged.api)).rejects.toThrow("source pull request"); -}); -test("changed source blobs cannot use a forged matching fingerprint or an old receipt", async () => { - const root = fixture(), inputs = proofInputs(root, "browser", inventory, runner), original = evidence(root, inputs); - write(root, "scripts/ci-proof.ts", "changed harness\n"); commit(root); - const changed = proofInputs(root, "browser", inventory, runner); - original.source.inputs = changed; - original.logs = original.logs.map(log => log.replace(JSON.stringify(inputs), JSON.stringify(changed))); - const api: API = { json: original.api.json, async log(id) { return original.logs[id - 101]!; } }; - await expect(validateSource(root, "browser", original.source, changed, context, api)).rejects.toThrow("immutable algorithm or dependency"); -}); -test("missing, invalid or stale current ledger cannot bless skipped selected proof", async () => { - const root = fixture(); - for (const ledger of [null, {}, { version: 1, checkout: checkout(root), retained: [] }, { version: 1, checkout: { sha: "0".repeat(40) }, retained: {} }]) { - await expect(retainedCategories(root, ledger, undefined, undefined)).rejects.toThrow("current-head proof ledger"); - } - const needs: Record }> = { changeset: { result: "success", outputs: Object.fromEntries(PROOF_JOBS.map(name => [name, "true"])) }, - ...Object.fromEntries(PROOF_JOBS.map(name => [name, { result: name === "browser" ? "skipped" : "success" }])) }; - expect(proofProblems(needs)).toContain("browser: selected proof did not pass (skipped)"); - expect(proofProblems(needs, new Set(["browser"]))).toEqual([]); - needs.browser = { result: "failure" }; - expect(proofProblems(needs, new Set(["browser"]))).toContain("browser: retained proof must skip fresh execution (failure)"); -}); -test("lookup retains a complete fresh pair, conservatively declines mismatches and never chains skipped proof", async () => { - const root = fixture(), inputs = proofInputs(root, "browser", inventory, runner), original = evidence(root, inputs); - const sourceJSON = original.api.json; - const api: API = { ...original.api, async json(path) { - if (path.startsWith("actions/workflows/")) return { workflow_runs: [original.run] }; - return sourceJSON(path); - } }; - expect((await findRetained(root, { browser: true }, context, api, inventory, runner)).browser).toEqual(original.source); - original.jobs[0]!.conclusion = "skipped"; - expect(await findRetained(root, { browser: true }, context, api, inventory, runner)).toEqual({}); - original.jobs[0]!.conclusion = "success"; - write(root, visual, "changed assertion\n"); commit(root); - expect(await findRetained(root, { browser: true }, context, api, inventory, runner)).toEqual({}); -}); -test("nonautomatic, draft and deleted-head contexts are fresh; fork ready PR lookup remains read-only", () => { - const event = { pull_request: { number: 42, draft: false, head: { ref: context.branch, repo: { full_name: "odysseus/brain-kit" } } } }; - const env = { GITHUB_ACTIONS: "true", GITHUB_EVENT_NAME: "pull_request", GITHUB_REPOSITORY: context.repository, GITHUB_RUN_ID: "100" }; - expect(contextFromEvent(event, env)?.headRepository).toBe("odysseus/brain-kit"); - expect(contextFromEvent(event, { ...env, GITHUB_EVENT_NAME: "schedule" })).toBeUndefined(); - expect(contextFromEvent(event, { ...env, GITHUB_EVENT_NAME: "push" })).toBeUndefined(); - expect(contextFromEvent(event, { ...env, GITHUB_ACTIONS: "" })).toBeUndefined(); - event.pull_request.draft = true; expect(contextFromEvent(event, env)).toBeUndefined(); - event.pull_request.draft = false; event.pull_request.head.repo.full_name = ""; expect(contextFromEvent(event, env)).toBeUndefined(); -}); -test("the actual compiler input inventory includes test leaves used by a build", () => { - const root = fixture(); - write(root, "packages/ui-react/tsconfig.build.json", JSON.stringify({ compilerOptions: { jsx: "react-jsx" }, include: ["tests/browser/**/*.tsx"] })); commit(root); - expect(proofInputs(root, "browser", inventory, runner).excluded).not.toContain(layout); -}); -test("native discovery consumes the JSON file, preserving colored console diagnostics as diagnostics", async () => { - const root = fixture(); - write(root, "scripts/visual.mjs", 'const projects = projectArgs.length ? [] : ["visual", "rail-fine"];\n'); - const discovered = [...inventory, { project: "ui-react-endurance", file: "packages/ui-react/tests/browser/recordings.endurance.tsx" }].sort((a, b) => a.project.localeCompare(b.project) || a.file.localeCompare(b.file)); - const original = Bun.spawn; - const spawn = spyOn(Bun, "spawn").mockImplementationOnce(((argv: string[], options: Parameters[1]) => { - const output = argv.find((arg: string) => arg.startsWith("--json="))?.slice("--json=".length); - if (output) writeFileSync(output, JSON.stringify(discovered.map(s => ({ file: join(root, s.file), projectName: `${s.project} (chromium)` })))); - return original([process.execPath, "-e", 'console.log("\\u001b[31mconsole diagnostic\\u001b[0m");'], options); - }) as typeof Bun.spawn); - try { expect(await browserInventory(root)).toEqual(discovered); } - finally { spawn.mockRestore(); } -}); -test("Git-derived, unknown dynamic module selection and exported foreign helpers refuse retention", () => { - const root = fixture(); - for (const name of ["GITHUB_SHA", "GITHUB_RUN_ID"]) { - write(root, visual, `const input = process.env.${name};\n`); commit(root); - expect(() => proofInputs(root, "browser", inventory, runner)).toThrow("Unresolved immutable"); - } - write(root, visual, "const input = await import(modulePath);\n"); commit(root); - expect(() => proofInputs(root, "browser", inventory, runner)).toThrow("Unresolved immutable"); - write(root, visual, 'const input = Bun.spawn(["git", "rev-parse", "HEAD"]);\n'); commit(root); - expect(() => proofInputs(root, "browser", inventory, runner)).toThrow("Unresolved immutable"); - write(root, visual, "export {};\n"); write(root, layout, "export const helper = 1;\n"); commit(root); - expect(proofInputs(root, "browser", inventory, runner).excluded).not.toContain(layout); -}); - -test("large receipts fall back to fresh proof before crossing the native environment envelope", async () => { - const root = fixture(), inputs = proofInputs(root, "browser", inventory, runner), { source } = evidence(root, inputs); - const ledger = { version: 1 as const, checkout: checkout(root), retained: { browser: source } }; - expect(boundedLedger(ledger).retained.browser).toEqual(source); - source.inputs = { ...inputs, runner: "\\".repeat(100000) }; - expect(Buffer.byteLength(JSON.stringify(JSON.stringify(ledger)))).toBeGreaterThan(131072); - const bounded = boundedLedger(ledger); - const child = Bun.spawn([process.execPath, "-e", 'const needs=JSON.parse(process.env.PROOF_NEEDS);if(Object.keys(JSON.parse(needs.changeset.outputs.reuse).retained).length)process.exit(1);console.log("fresh");'], { - cwd: root, stdout: "pipe", stderr: "pipe", env: { ...process.env, PROOF_NEEDS: JSON.stringify({ changeset: { outputs: { reuse: JSON.stringify(bounded) } } }) }, - }); - const [out, code] = await Promise.all([new Response(child.stdout).text(), child.exited]); - expect(code).toBe(0); expect(out.trim()).toBe("fresh"); expect(bounded.checkout).toEqual(ledger.checkout); -}); - - -test("root-redirect environment overrides refuse retention before generated fixture binding", () => { - const env = { ImageVersion: "fixed", RUNNER_OS: "Linux", RUNNER_ARCH: "X64" }; - expect(runnerIdentity(env)).toContain("brain-roots-absent-v1"); - for (const name of ["BRAIN_ROOT", "BRAIN_WORKER_DATA_ROOT", "BRAIN_WORKER_CONFIG_ROOT"]) { - expect(runnerIdentity({ ...env, [name]: "/untrusted/redirect" })).toBe(""); - expect(runnerIdentity({ ...env, [name]: "" })).toBe(""); - } -}); - -test("distinct Chromium and WebKit projects keep separate normalized proof identities",()=>{ - expect(normalizeInventory([{projectName:"diagrams-chromium (chromium)",file:"packages/ui-react/tests/browser/diagrams-renderer.layout.tsx"},{projectName:"diagrams-webkit (webkit)",file:"packages/ui-react/tests/browser/diagrams-renderer.layout.tsx"}])).toEqual([{project:"diagrams-chromium",file:"packages/ui-react/tests/browser/diagrams-renderer.layout.tsx"},{project:"diagrams-webkit",file:"packages/ui-react/tests/browser/diagrams-renderer.layout.tsx"}]); -}); diff --git a/tests/refresh-browser-costs.test.ts b/tests/refresh-browser-costs.test.ts index ba2618098f..e3b8800413 100644 --- a/tests/refresh-browser-costs.test.ts +++ b/tests/refresh-browser-costs.test.ts @@ -2,7 +2,7 @@ import { expect, test } from "bun:test"; import {readFileSync} from "node:fs"; import {resolve} from "node:path"; import { refreshBrowserCosts } from "../scripts/refresh-browser-costs"; -import type { API } from "../scripts/proof-reuse"; +import type { API } from "../scripts/proof-api"; import { PROOF_SHARDS, shardNumbers } from "../scripts/proof-shards"; const sha = "a".repeat(40), parent = "b".repeat(40), tree = "c".repeat(40); diff --git a/tests/source-browser-dispatch.test.ts b/tests/source-browser-dispatch.test.ts deleted file mode 100644 index 1b3f8c3776..0000000000 --- a/tests/source-browser-dispatch.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import {afterEach,expect,test} from "bun:test"; -import {mkdirSync,mkdtempSync,readFileSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; -import {tmpdir} from "node:os"; -import {dirname,join,resolve} from "node:path"; -import {browserImporters} from "../scripts/bound-browser-runtime-inputs"; -import {sourceBrowserDispatch} from "../scripts/source-browser-dispatch"; -const repo=resolve(import.meta.dir,".."),roots:string[]=[],base="packages/ui-react/src/hooks/websocket-handlers/",owner=base+"index.ts",stats="packages/ui-react/src/lib/stats/context-text.ts"; -const files=[owner,stats,...["chat","activity","mask","provider","connection","handoff"].map(name=>base+name+".ts")]; -afterEach(()=>{for(const root of roots.splice(0))rmSync(root,{recursive:true,force:true});}); -function fixture(){const root=mkdtempSync(join(tmpdir(),"source-browser-dispatch-"));roots.push(root);const write=(file:string,text:string)=>{mkdirSync(dirname(join(root,file)),{recursive:true});writeFileSync(join(root,file),text);};symlinkSync(join(repo,"node_modules"),join(root,"node_modules"),"dir");for(const file of files)write(file,readFileSync(join(repo,file),"utf8"));return{root,write};} -test("private finite registries bind their existing predicate and copied handler source",()=>{ - const {root}=fixture(),bindings=sourceBrowserDispatch(root,files,browserImporters(root,files)); - expect(bindings.get(owner)?.has("serverMessageHandlers[msg.type](msg as never, context)")).toBe(true); - expect(bindings.get(stats)?.has('REQUIRED[kind as StatsSection["kind"]](section as Record)')).toBe(true); -}); -test("an additional importer cannot mutate a handler map before the private dispatcher copies it",()=>{ - const {root,write}=fixture();write("extra.ts",`import {providerFrameHandlers} from "./${base}provider.ts"; providerFrameHandlers.session_info=external;`); - expect(sourceBrowserDispatch(root,[...files,"extra.ts"],browserImporters(root,[...files,"extra.ts"])).has(owner)).toBe(false); -}); -test("audited imports of a different chat helper cannot gain the handler map through drift",()=>{ - const {root,write}=fixture(),consumers=["packages/ui-react/src/ws-client/inbound.ts","packages/ui-react/src/hooks/use-websocket.ts"],selected=[...files,...consumers]; - for(const file of consumers)write(file,readFileSync(join(repo,file),"utf8")); - expect(sourceBrowserDispatch(root,selected,browserImporters(root,selected)).has(owner)).toBe(true); - for(const consumer of consumers){ - const specifier=consumer.includes("/hooks/")?"./websocket-handlers/chat.js":"../hooks/websocket-handlers/chat.js"; - write(consumer,readFileSync(join(repo,consumer),"utf8")+`\nimport {chatFrameHandlers} from "${specifier}"; chatFrameHandlers.text_delta=external;\n`); - expect(sourceBrowserDispatch(root,selected,browserImporters(root,selected)).has(owner),`UNREVIEWED_HELPER_CONSUMER_REFUSED: ${consumer}`).toBe(false); - write(consumer,readFileSync(join(repo,consumer),"utf8")); - expect(sourceBrowserDispatch(root,selected,browserImporters(root,selected)).has(owner)).toBe(true); - } -}); -test("registry escape, owner drift and changed imported handler definitions remain unknown",()=>{ - for(const file of [owner,stats,base+"provider.ts",base+"connection.ts"]){const {root,write}=fixture();write(file,readFileSync(join(root,file),"utf8")+"\n// source drift\n");expect(sourceBrowserDispatch(root,files,browserImporters(root,files)).has(file===stats?stats:owner)).toBe(false);} - const {root,write}=fixture();write(owner,readFileSync(join(root,owner),"utf8")+"\nexport const escaped=serverMessageHandlers;\n");expect(sourceBrowserDispatch(root,files,browserImporters(root,files)).has(owner)).toBe(false); -}); -test("unreviewed terminal chat handling cannot gain a trusted dispatch binding",()=>{ - const {root,write}=fixture(),chat=base+"chat.ts",text=readFileSync(join(root,chat),"utf8"); - const reviewed="context.state.endTurnQuestions(context.key, context.frameTurnId);"; - expect(text).toContain(reviewed); - write(chat,text.replace(reviewed,"unreviewed(msg, context);")); - expect(sourceBrowserDispatch(root,files,browserImporters(root,files)).has(owner),"UNREVIEWED_CHAT_HANDLER_REFUSED").toBe(false); -}); diff --git a/tests/source-browser-payloads.test.ts b/tests/source-browser-payloads.test.ts deleted file mode 100644 index 46337ef33d..0000000000 --- a/tests/source-browser-payloads.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { afterEach, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join, resolve } from "node:path"; -import ts from "typescript"; -import { sourceBrowserPayload } from "../scripts/source-browser-payloads"; -import { discoverInputClosure } from "../scripts/browser-input-closure"; -const repo=resolve(import.meta.dir,".."),roots:string[]=[]; -afterEach(()=>{for(const root of roots.splice(0))rmSync(root,{recursive:true,force:true});}); -function expressions(source:string){const ast=ts.createSourceFile("owner.ts",source,ts.ScriptTarget.Latest,true);const result:string[]=[];const walk=(node:ts.Node)=>{if(ts.isCallExpression(node)&&/\.(?:fulfill|setContent)$/.test(node.expression.getText(ast)))result.push(node.getText(ast));ts.forEachChild(node,walk);};walk(ast);return result;} -test("only the exact literal SVG rectangle and pixel probe bind source-owned payload bytes",()=>{ - const root=mkdtempSync(join(tmpdir(),"browser-literal-payload-"));roots.push(root); - for(const owner of ["packages/ui-kit/tests/visual/form-browser.ts","packages/ui-kit/tests/visual/ghost-browser.ts"]){ - const source=readFileSync(join(repo,owner),"utf8");mkdirSync(dirname(join(root,owner)),{recursive:true});writeFileSync(join(root,owner),source); - const calls=expressions(source),allowed=calls.filter(call=>sourceBrowserPayload(root,owner,call));expect(allowed.length).toBe(1); - const closure=discoverInputClosure(root,[owner]);expect(closure.unresolved.some(value=>value.includes(allowed[0]!))).toBe(false); - expect(calls.filter(call=>!sourceBrowserPayload(root,owner,call)).length).toBeGreaterThan(0); - writeFileSync(join(root,owner),source+"\n// lexical binding drift\n");expect(sourceBrowserPayload(root,owner,allowed[0]!)).toBe(false); - expect(sourceBrowserPayload(root,owner,'page.setContent("")')).toBe(false); - } -});