Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
perf(ci): stop downloading a CUDA provider no runner can use, and cache the server install (#4756)
[._.]/ Adam Eivy410150e6dac1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9eff0bb577..f56d30c42d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -48,7 +48,6 @@ jobs:windows: ${{ steps.plan.outputs.windows }}windows_mode: ${{ steps.plan.outputs.windows_mode }}windows_files: ${{ steps.plan.outputs.windows_files }}- server_native: ${{ steps.plan.outputs.server_native }}steps:- uses: actions/checkout@v7with:@@ -88,7 +87,6 @@ jobs:SMOKE_MODE: ${{ steps.plan.outputs.smoke }}WINDOWS_MODE: ${{ steps.plan.outputs.windows }}WINDOWS_TEST_MODE: ${{ steps.plan.outputs.windows_mode }}- SERVER_NATIVE: ${{ steps.plan.outputs.server_native }}run: |{echo "### CI impact plan"@@ -101,7 +99,6 @@ jobs:echo "- Client build: \`${BUILD_MODE}\`"echo "- Server smoke: \`${SMOKE_MODE}\`"echo "- Windows server tests: \`${WINDOWS_MODE}\` (\`${WINDOWS_TEST_MODE}\`)"- echo "- Server native rebuild: \`${SERVER_NATIVE}\`"} >> "$GITHUB_STEP_SUMMARY"server:@@ -126,12 +123,93 @@ jobs:cache: npmcache-dependency-path: server/package-lock.json+ # setup-node's npm cache only preserves ~/.npm, the tarball cache: `npm ci`+ # still wipes and repopulates a 570 MB node_modules on all three server+ # jobs. Cache the installed tree instead and skip the install on a hit.+ #+ # No restore-keys. The install below is skipped on a hit, so a near-miss+ # restore would silently ship a node_modules built from a different+ # lockfile. Exact key or nothing. package.json is in the hash alongside+ # the lockfile so that skipping `npm ci` does not also skip its+ # manifest-vs-lockfile check, and the key carries the Node *major* rather+ # than the resolved patch, because NODE_MODULE_VERSION is stable across+ # patches and keying on the patch would discard the entry on every Node+ # 24.x release. The transform-artifact cache below keeps its own key and+ # its own restore-keys; this one is about dependencies.+ #+ # Hit rate comes from the nightly full run: there is no push trigger on+ # `main`, so the 09:17 UTC schedule is what seeds these caches on the+ # default branch, which is the only scope every PR branch can read.+ # See docs/GITHUB_ACTIONS.md.+ - name: Cache server node_modules+ id: server-modules+ uses: actions/cache@v4+ with:+ path: server/node_modules+ key: server-modules-${{ runner.os }}-${{ runner.arch }}-node24-${{ hashFiles('server/package-lock.json', 'server/package.json', 'server/.npmrc', 'scripts/trusted-rebuilds.js') }}++ # A restored tree is only reusable if it was rebuilt before it was saved,+ # and that is not answerable by looking at the tree — with today's+ # versions the rebuild is nearly a no-op, so every allowlisted package+ # imports fine on a never-rebuilt one. The rebuild step below leaves an+ # explicit mark; this reads it back.+ #+ # `continue-on-error` on purpose: a bad entry must not wedge every PR+ # until a human clears the cache by hand. It fails, the two steps below+ # see a non-success outcome, and the job builds the tree it needs. It does+ # not *replace* the bad entry — cache keys are immutable and actions/cache+ # skips the save on an exact hit — so that entry keeps costing each run a+ # reinstall until the key moves or it ages out. That is precisely the+ # pre-cache cost: the worst case degrades to the old behaviour, never to a+ # red repo.+ #+ # `outcome != 'success'` covers all three cases in one expression: on a+ # cache miss this step is skipped (outcome `skipped`), on a hit it is+ # `success` or `failure`.+ - name: Check the restored node_modules was rebuilt+ id: server-modules-usable+ if: steps.server-modules.outputs.cache-hit == 'true'+ continue-on-error: true+ run: node scripts/trusted-rebuild-stamp.js check server+- name: Install server dependencies+ if: steps.server-modules-usable.outcome != 'success'run: npm ci --prefix server- # After npm ci: it wipes node_modules, so a pre-install restore is lost.- # Vite/Vitest write transform artifacts under node_modules/.vite (and- # historically .vitest). Reusing them skips re-transforming unchanged files.+ # server/.npmrc pins ignore-scripts=true, so the allowlisted packages need+ # this explicit rebuild. Same condition as the install: whenever this job+ # builds the tree it will cache, it must build a rebuilt one — and the+ # mark is written in the same block, so a failed rebuild cannot leave one+ # behind for a later job to trust.+ #+ # `shell: bash` is load-bearing, not style. windows-server would default+ # to pwsh, where a *native* command's non-zero exit neither throws nor+ # stops the block (`$PSNativeCommandUseErrorActionPreference` is false)+ # and only the last command's code becomes the step result — so a failed+ # rebuild would run the mark anyway, reset the exit code to 0, and publish+ # a green, marked, un-rebuilt tree. Under `bash -e` the block stops at+ # the rebuild, the job fails, and actions/cache (`post-if: success()`)+ # never saves it.+ - name: Rebuild trusted native dependencies+ if: steps.server-modules-usable.outcome != 'success'+ shell: bash+ env:+ # Skip onnxruntime-node's CUDA execution provider. Its postinstall+ # downloads it on linux-x64 whenever the .so is absent — several+ # hundred MB, on two jobs, every run — and no hosted runner has an+ # NVIDIA GPU to use it with. The CPU binaries ship in the tarball, so+ # inference still works; this is the single largest cost in the job.+ ONNXRUNTIME_NODE_INSTALL_CUDA: skip+ run: |+ node scripts/trusted-rebuilds.js server+ node scripts/trusted-rebuild-stamp.js write server++ # After the install: `npm ci` wipes node_modules, so a restore ordered+ # ahead of it is lost. Vite/Vitest write transform artifacts under+ # node_modules/.vite (and historically .vitest); reusing them skips+ # re-transforming unchanged files. Separate from the cache above, and+ # deliberately: this is where a near miss is safe, so this is the entry+ # that keeps restore-keys and stays warm across a lockfile bump.- name: Cache Vitest transform artifactsuses: actions/cache@v4with:@@ -143,14 +221,6 @@ jobs:vitest-server-${{ runner.os }}-${{ hashFiles('server/package-lock.json') }}-vitest-server-${{ runner.os }}-- # server/.npmrc pins ignore-scripts=true, so the native deps npm skipped- # need the explicit allowlist rebuild to be usable (node-pty et al).- # Always-run-only plans (prompt-upgrade + changelog fragment guards)- # import no native addons, so skip the rebuild there.- - name: Rebuild trusted native dependencies- if: needs.impact.outputs.server_native == 'true'- run: node scripts/trusted-rebuilds.js server-- name: Check server entry-point syntaxrun: node --check server/index.js@@ -256,9 +326,78 @@ jobs:cache: npmcache-dependency-path: server/package-lock.json+ # Same entry and same contract as the server job — see it for the key, and+ # for why the install and rebuild below are gated on the mark rather than+ # on the cache hit.+ - name: Cache server node_modules+ id: server-modules+ uses: actions/cache@v4+ with:+ path: server/node_modules+ key: server-modules-${{ runner.os }}-${{ runner.arch }}-node24-${{ hashFiles('server/package-lock.json', 'server/package.json', 'server/.npmrc', 'scripts/trusted-rebuilds.js') }}++ # A restored tree is only reusable if it was rebuilt before it was saved,+ # and that is not answerable by looking at the tree — with today's+ # versions the rebuild is nearly a no-op, so every allowlisted package+ # imports fine on a never-rebuilt one. The rebuild step below leaves an+ # explicit mark; this reads it back.+ #+ # `continue-on-error` on purpose: a bad entry must not wedge every PR+ # until a human clears the cache by hand. It fails, the two steps below+ # see a non-success outcome, and the job builds the tree it needs. It does+ # not *replace* the bad entry — cache keys are immutable and actions/cache+ # skips the save on an exact hit — so that entry keeps costing each run a+ # reinstall until the key moves or it ages out. That is precisely the+ # pre-cache cost: the worst case degrades to the old behaviour, never to a+ # red repo.+ #+ # `outcome != 'success'` covers all three cases in one expression: on a+ # cache miss this step is skipped (outcome `skipped`), on a hit it is+ # `success` or `failure`.+ - name: Check the restored node_modules was rebuilt+ id: server-modules-usable+ if: steps.server-modules.outputs.cache-hit == 'true'+ continue-on-error: true+ run: node scripts/trusted-rebuild-stamp.js check server+- name: Install server dependencies+ if: steps.server-modules-usable.outcome != 'success'run: npm ci --prefix server+ # server/.npmrc pins ignore-scripts=true, so the allowlisted packages need+ # this explicit rebuild. Same condition as the install: whenever this job+ # builds the tree it will cache, it must build a rebuilt one — and the+ # mark is written in the same block, so a failed rebuild cannot leave one+ # behind for a later job to trust.+ #+ # `shell: bash` is load-bearing, not style. windows-server would default+ # to pwsh, where a *native* command's non-zero exit neither throws nor+ # stops the block (`$PSNativeCommandUseErrorActionPreference` is false)+ # and only the last command's code becomes the step result — so a failed+ # rebuild would run the mark anyway, reset the exit code to 0, and publish+ # a green, marked, un-rebuilt tree. Under `bash -e` the block stops at+ # the rebuild, the job fails, and actions/cache (`post-if: success()`)+ # never saves it.+ - name: Rebuild trusted native dependencies+ if: steps.server-modules-usable.outcome != 'success'+ shell: bash+ env:+ # Skip onnxruntime-node's CUDA execution provider. Its postinstall+ # downloads it on linux-x64 whenever the .so is absent — several+ # hundred MB, on two jobs, every run — and no hosted runner has an+ # NVIDIA GPU to use it with. The CPU binaries ship in the tarball, so+ # inference still works; this is the single largest cost in the job.+ ONNXRUNTIME_NODE_INSTALL_CUDA: skip+ run: |+ node scripts/trusted-rebuilds.js server+ node scripts/trusted-rebuild-stamp.js write server++ # After the install: `npm ci` wipes node_modules, so a restore ordered+ # ahead of it is lost. Vite/Vitest write transform artifacts under+ # node_modules/.vite (and historically .vitest); reusing them skips+ # re-transforming unchanged files. Separate from the cache above, and+ # deliberately: this is where a near miss is safe, so this is the entry+ # that keeps restore-keys and stays warm across a lockfile bump.- name: Cache Vitest transform artifactsuses: actions/cache@v4with:@@ -270,11 +409,6 @@ jobs:vitest-server-${{ runner.os }}-${{ hashFiles('server/package-lock.json') }}-vitest-server-${{ runner.os }}-- # server/.npmrc pins ignore-scripts=true — DB suites that touch sharp /- # node-pty still need the explicit allowlist rebuild.- - name: Rebuild trusted native dependencies- run: node scripts/trusted-rebuilds.js server-- name: Provision test database (portos_test)run: npm run setup:db:test --prefix server@@ -312,9 +446,78 @@ jobs:cache: npmcache-dependency-path: server/package-lock.json+ # Same entry and same contract as the server job — see it for the key, and+ # for why the install and rebuild below are gated on the mark rather than+ # on the cache hit.+ - name: Cache server node_modules+ id: server-modules+ uses: actions/cache@v4+ with:+ path: server/node_modules+ key: server-modules-${{ runner.os }}-${{ runner.arch }}-node24-${{ hashFiles('server/package-lock.json', 'server/package.json', 'server/.npmrc', 'scripts/trusted-rebuilds.js') }}++ # A restored tree is only reusable if it was rebuilt before it was saved,+ # and that is not answerable by looking at the tree — with today's+ # versions the rebuild is nearly a no-op, so every allowlisted package+ # imports fine on a never-rebuilt one. The rebuild step below leaves an+ # explicit mark; this reads it back.+ #+ # `continue-on-error` on purpose: a bad entry must not wedge every PR+ # until a human clears the cache by hand. It fails, the two steps below+ # see a non-success outcome, and the job builds the tree it needs. It does+ # not *replace* the bad entry — cache keys are immutable and actions/cache+ # skips the save on an exact hit — so that entry keeps costing each run a+ # reinstall until the key moves or it ages out. That is precisely the+ # pre-cache cost: the worst case degrades to the old behaviour, never to a+ # red repo.+ #+ # `outcome != 'success'` covers all three cases in one expression: on a+ # cache miss this step is skipped (outcome `skipped`), on a hit it is+ # `success` or `failure`.+ - name: Check the restored node_modules was rebuilt+ id: server-modules-usable+ if: steps.server-modules.outputs.cache-hit == 'true'+ continue-on-error: true+ run: node scripts/trusted-rebuild-stamp.js check server+- name: Install server dependencies+ if: steps.server-modules-usable.outcome != 'success'run: npm ci --prefix server+ # server/.npmrc pins ignore-scripts=true, so the allowlisted packages need+ # this explicit rebuild. Same condition as the install: whenever this job+ # builds the tree it will cache, it must build a rebuilt one — and the+ # mark is written in the same block, so a failed rebuild cannot leave one+ # behind for a later job to trust.+ #+ # `shell: bash` is load-bearing, not style. windows-server would default+ # to pwsh, where a *native* command's non-zero exit neither throws nor+ # stops the block (`$PSNativeCommandUseErrorActionPreference` is false)+ # and only the last command's code becomes the step result — so a failed+ # rebuild would run the mark anyway, reset the exit code to 0, and publish+ # a green, marked, un-rebuilt tree. Under `bash -e` the block stops at+ # the rebuild, the job fails, and actions/cache (`post-if: success()`)+ # never saves it.+ - name: Rebuild trusted native dependencies+ if: steps.server-modules-usable.outcome != 'success'+ shell: bash+ env:+ # Skip onnxruntime-node's CUDA execution provider. Its postinstall+ # downloads it on linux-x64 whenever the .so is absent — several+ # hundred MB, on two jobs, every run — and no hosted runner has an+ # NVIDIA GPU to use it with. The CPU binaries ship in the tarball, so+ # inference still works; this is the single largest cost in the job.+ ONNXRUNTIME_NODE_INSTALL_CUDA: skip+ run: |+ node scripts/trusted-rebuilds.js server+ node scripts/trusted-rebuild-stamp.js write server++ # After the install: `npm ci` wipes node_modules, so a restore ordered+ # ahead of it is lost. Vite/Vitest write transform artifacts under+ # node_modules/.vite (and historically .vitest); reusing them skips+ # re-transforming unchanged files. Separate from the cache above, and+ # deliberately: this is where a near miss is safe, so this is the entry+ # that keeps restore-keys and stays warm across a lockfile bump.- name: Cache Vitest transform artifactsuses: actions/cache@v4with:@@ -326,9 +529,6 @@ jobs:vitest-server-${{ runner.os }}-${{ hashFiles('server/package-lock.json') }}-vitest-server-${{ runner.os }}-- - name: Rebuild trusted native dependencies- run: node scripts/trusted-rebuilds.js server-- name: Check server entry-point syntaxrun: node --check server/index.jsdiff --git a/docs/DEPS.md b/docs/DEPS.mdindex 01a04ab995..a6e169d060 100644--- a/docs/DEPS.md+++ b/docs/DEPS.md@@ -141,4 +141,4 @@ These exist purely to force-bump transitive deps; revisit if `npm audit` flags n`ignore-scripts=true` is pinned in **every** workspace's own `.npmrc` (root, `client/`, `server/`, `autofixer/`, `browser/`) — not just the repo root. The list is not maintained by hand: `discoverWorkspaces()` in `scripts/trusted-rebuilds.js` globs every top-level directory carrying a `package.json`, and the test asserts each discovered one has the setting — so a workspace added later is caught rather than silently unguarded. npm resolves the project `.npmrc` from the *local prefix* and never walks up the directory tree, so a root-only setting does not cover `cd client && npm install` or `npm ci --prefix server` (what CI runs). Deleting any workspace `.npmrc` silently re-grants every dependency in that workspace an install-time code-execution slot — the vector the Shai-Hulud worm used.-Packages that legitimately need an install script are named explicitly in the allowlist in `scripts/trusted-rebuilds.js`, the single source consumed by `npm run setup`, `scripts/ensure-deps.js`, `setup.ps1`, `update.sh` / `update.ps1`, and CI. `scripts/trusted-rebuilds.test.js` fails if a workspace `.npmrc` loses the setting, or if a dependency appears with an install hook that nobody has explicitly decided about.+Packages that legitimately need an install script are named explicitly in the allowlist in `scripts/trusted-rebuilds.js`, the single source consumed by `npm run setup`, `scripts/ensure-deps.js`, `setup.ps1`, `update.sh` / `update.ps1`, and CI. `scripts/trusted-rebuilds.test.js` fails if a workspace `.npmrc` loses the setting, or if a dependency appears with an install hook that nobody has explicitly decided about. Because CI caches `server/node_modules` between jobs, `scripts/trusted-rebuild-stamp.js` writes a mark into the tree in the same step that rebuilds it and checks that mark after a cache restore — a tree cached before the rebuild is otherwise indistinguishable from a good one, since the allowlisted packages all ship prebuilt bindings and import fine either way.diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.mdindex 749cefe457..0cf64a5903 100644--- a/docs/GITHUB_ACTIONS.md+++ b/docs/GITHUB_ACTIONS.md@@ -56,12 +56,116 @@ workers stay busy; the DB suite already serializes files because those testsshare one Postgres.Each test job restores Vite/Vitest transform artifacts-(`node_modules/.vite`, `node_modules/.vitest`) **after** `npm ci` — install-wipes `node_modules`, so a pre-install restore is lost. `scripts/run-ci-tests.js`+(`node_modules/.vite`, `node_modules/.vitest`) **after** the install — `npm ci`+wipes `node_modules`, so a restore ordered ahead of it is lost.+`scripts/run-ci-tests.js`writes Vitest wall time to the job summary so later runs can be comparedagainst the pre-change full-suite job wall on `main` (2026-08-16, run`31951919659`): server ~300s, client+build ~467s, Windows ~463s.+### Reusing the server install++Three jobs install the server workspace — `server`, `database`, and+`windows-server`. `setup-node`'s `cache: npm` only preserves `~/.npm`, the+tarball cache, so `npm ci` still wipes and repopulates a ~570 MB+`node_modules` on each of them. Two changes cut that.++**Skip the CUDA execution provider.** onnxruntime-node bundles its CPU binaries+in the npm tarball, but its postinstall *downloads* the CUDA EP — several+hundred MB — on linux-x64 whenever `libonnxruntime_providers_cuda.so` is+absent. `server/.npmrc` pins `ignore-scripts=true`, so that runs inside+`scripts/trusted-rebuilds.js`, on the `server` and `database` jobs, every run.+No hosted runner has an NVIDIA GPU to use it with. Setting+`ONNXRUNTIME_NODE_INSTALL_CUDA=skip` on the rebuild step removes the download+outright, and inference is unaffected. This is the largest single saving here,+and it costs no cache budget.++**Cache the installed tree**, keyed on `runner.os`, `runner.arch`, the Node+major, and a hash of `server/package-lock.json`, `server/package.json`,+`server/.npmrc`, and `scripts/trusted-rebuilds.js`. On a hit the install and+the rebuild are both skipped. `scripts/ci-base-sha.test.js` guards the+contract; the parts that are not obvious:++- **Install and rebuild share one condition.** `ignore-scripts=true` means npm+ alone leaves the allowlisted packages un-built, so whenever a job builds the+ tree it will cache, it must build a rebuilt one. (The `server` job used to+ skip the rebuild for always-run-only plans; that condition is narrower, so it+ is gone — along with the planner's `server_native` output, which had no other+ consumer.)+- **A restored tree is checked by a mark, not by importing things.**+ `scripts/trusted-rebuild-stamp.js` writes+ `node_modules/.portos-trusted-rebuild.json` in the same `run:` block as the+ rebuild, recording the allowlist hash, platform, arch, and+ `NODE_MODULE_VERSION`. A cache hit reads it back and reinstalls on any+ mismatch.++ That step is pinned to `shell: bash`, which is load-bearing rather than+ stylistic. `windows-server` would otherwise default to pwsh, where a+ *native* command's non-zero exit neither throws nor stops the block+ (`$PSNativeCommandUseErrorActionPreference` is false) and only the last+ command's code becomes the step result — so a failed rebuild would write the+ mark anyway, exit 0, and publish a green, marked, un-rebuilt entry. Under+ `bash -e` the block stops at the rebuild and the job fails, and+ `actions/cache` declares `post-if: success()`, so nothing is saved.++ It has to be an extrinsic mark because "was this rebuilt?" is not answerable+ by inspecting the tree. With today's versions the rebuild is close to a+ no-op: node-pty and sharp ship prebuilt bindings inside their tarballs (there+ is no `build/` directory even in a fully rebuilt tree), onnxruntime-node+ bundles its CPU binaries, and protobufjs only regenerates a bundle nothing+ requires. `require()`-ing those packages therefore succeeds on a+ never-rebuilt tree and proves nothing. That is a property of the current+ versions, not a guarantee — a release that drops a prebuild for the runner's+ platform, or an install under `npm_config_build_from_source` (which makes+ node-pty's install script *delete* the prebuilds), puts the rebuild back on+ the critical path, and the mark still discriminates.+- **A bad entry is survived, not repaired.** The check is+ `continue-on-error`, and the install and rebuild key off+ `steps.server-modules-usable.outcome != 'success'` — one expression covering+ all three cases, since the step is `skipped` on a miss. The entry itself is+ not replaced: cache keys are immutable and `actions/cache` skips its save on+ an exact hit, so it keeps costing each run a reinstall until the key moves.+ It will not age out on its own either — GitHub's 7-day eviction is keyed on+ *access*, and an entry every run restores is accessed every run. Purging it+ would mean granting the workflow `actions: write`, which is not worth it when+ the worst case is already just the pre-cache cost.++ Two residual cases are accepted rather than defended. A rebuild in which only+ a `fatal: false` group failed exits 0, so a partially-rebuilt tree is marked+ and shared — where before, each job rebuilt from scratch and a transient+ failure degraded exactly one run. Today that is inert: with the CUDA download+ skipped onnxruntime-node's script early-exits, and protobufjs only+ regenerates a bundle nothing requires. And the dependency entry physically+ contains `node_modules/.vite`, so those artifacts are stored in both entries;+ `!` exclusions do not fix it, because `@actions/cache` resolves `path` with+ `implicitDescendants: false` — a bare directory pattern is archived whole and+ a sibling negation has nothing to subtract.+- **No `restore-keys` on this entry**, because the install is skipped on a hit+ and a near-miss restore would run the suite against a different lockfile's+ `node_modules`. The transform-artifact cache is the opposite case — its+ contents are revalidated rather than trusted — so it keeps its own key and its+ own restore-keys, and stays warm across a lockfile bump that misses here.+- **The key pins the Node major, not the resolved patch.**+ `NODE_MODULE_VERSION` is stable across patch releases, so keying on+ `steps.node.outputs.node-version` would discard the entry on every Node 24.x+ release for no ABI benefit; the mark carries the exact ABI as a backstop. A+ test compares the literal against the job's own `node-version:` pin.+ `server/package.json` is in the hash alongside the lockfile so that skipping+ `npm ci` does not also skip its manifest-vs-lockfile agreement check.++Hit rate comes from the nightly full run. There is no push trigger on `main`, and+a cache written by a pull request is visible only to that branch — so the 09:17+UTC schedule is what seeds the entries on the default branch, the one scope every+PR branch can read. A PR that changes the lockfile misses by design.++Two entries exist per key state (Linux, shared by `server` and `database`, plus+Windows) at roughly 570 MB each, against GitHub's 10 GB per-repo cache budget.+Eviction is LRU, so the constantly-read `main` entries outlive the PR-scoped ones+— but a burst of lockfile-churning PRs can still push out the transform caches+and `~/.npm`. If that starts showing up as unexplained cold runs, the dependency+cache is the part to drop: the CUDA skip above carries most of the saving on its+own.+### Shallow checkoutsNo job clones full history. `actions/checkout` runs at `fetch-depth: 2`,@@ -93,8 +197,9 @@ The selected work is split across parallel jobs:- **Server tests** — full, related, or explicit feature test files. Smoke-bootsthe server on the same job when server source changed (the smoke path uses the- file backend under `NODE_ENV=test` and does not need Postgres). Always-run-only- plans skip the native-addon rebuild.+ file backend under `NODE_ENV=test` and does not need Postgres). The install+ and the native-addon rebuild are skipped when a `server/node_modules` cache is+ restored and its trusted-rebuild mark checks out.- **Client tests and build** — affected client tests; production build wheneverclient source changed; client lint on the same install so Biome does not pay asecond `npm ci`.diff --git a/scripts/ci-base-sha.test.js b/scripts/ci-base-sha.test.jsindex 2652d0007c..43f0b613fc 100644--- a/scripts/ci-base-sha.test.js+++ b/scripts/ci-base-sha.test.js@@ -106,3 +106,128 @@ describe('ci.yml required checks', () => {expect(jobs.gate).not.toMatch(/needs\.lint\b/);});});++describe('ci.yml server node_modules cache', () => {+ const jobs = workflowJobs(WORKFLOW);++ /** Every job that installs the server workspace — the three this cache serves. */+ const installers = Object.entries(jobs)+ .filter(([, body]) => body.includes('npm ci --prefix server'));++ /** The `Cache server node_modules` step of one job, up to the next step. */+ function cacheEntry(body) {+ const rest = body.slice(body.indexOf('- name: Cache server node_modules'));+ const end = rest.indexOf(' - name:', 1);+ return end > 0 ? rest.slice(0, end) : rest;+ }++ it('caches the installed tree on every job that installs it', () => {+ expect(installers.map(([id]) => id).sort())+ .toEqual(['database', 'server', 'windows-server']);++ for (const [, body] of installers) expect(cacheEntry(body)).toMatch(/id: server-modules\b/);+ });++ it('installs and rebuilds together, on any tree this job will cache', () => {+ // server/.npmrc pins ignore-scripts=true, so a tree saved before the+ // trusted rebuild is un-built — and the job that saved it still reports+ // success. Whenever a job builds the tree it will cache, it must build a+ // rebuilt one, so a condition on the rebuild NARROWER than the one on the+ // install (the `server` job used to gate on the planner's server_native+ // flag) reintroduces the hole.+ for (const [id, body] of installers) {+ const install = body.match(+ /- name: Install server dependencies\n {8}if: (?<cond>.*)\n {8}run: npm ci --prefix server/,+ );+ const rebuild = body.match(+ /- name: Rebuild trusted native dependencies\n {8}if: (?<cond>.*)\n/,+ );+ expect(install, id).not.toBeNull();+ expect(rebuild, id).not.toBeNull();+ expect(rebuild.groups.cond, id).toBe(install.groups.cond);+ expect(install.groups.cond, id).toBe("steps.server-modules-usable.outcome != 'success'");+ }+ });++ it('marks the tree in the same step that rebuilds it, under a fail-fast shell', () => {+ // Two steps could drift, and a failed rebuild in step one would still let+ // step two mark the tree as good. One `run:` block cannot — but only if+ // the shell stops on the first non-zero exit, and windows-server defaults+ // to pwsh, where a native command's failure neither throws nor stops the+ // block and only the LAST command's code becomes the step result. Without+ // the pin, a failed Windows rebuild would mark the tree anyway, exit 0, and+ // publish a green, marked, un-rebuilt cache entry.+ for (const [id, body] of installers) {+ const rebuild = body.slice(body.indexOf('- name: Rebuild trusted native dependencies'));+ expect(rebuild, id).toMatch(+ /run: \|\n {10}node scripts\/trusted-rebuilds\.js server\n {10}node scripts\/trusted-rebuild-stamp\.js write server/,+ );+ expect(rebuild.slice(0, rebuild.indexOf('run: |')), id).toMatch(/\n {8}shell: bash\n/);+ }+ });++ it('checks a restored tree without letting a bad entry wedge the repo', () => {+ for (const [id, body] of installers) {+ const check = body.match(+ /- name: Check the restored node_modules was rebuilt\n {8}id: server-modules-usable\n {8}if: (?<cond>.*)\n {8}continue-on-error: true\n {8}run: node scripts\/trusted-rebuild-stamp\.js check server/,+ );+ // Without continue-on-error the same broken entry fails every run+ // forever: nothing a pull request touches feeds the key, so the next run+ // restores it and dies identically until a human clears the cache.+ expect(check, id).not.toBeNull();+ expect(check.groups.cond, id).toBe("steps.server-modules.outputs.cache-hit == 'true'");+ // And it must come before the steps whose condition reads its outcome.+ expect(body.indexOf('id: server-modules-usable'), id)+ .toBeLessThan(body.indexOf('run: npm ci --prefix server'));+ }+ });++ it('never restores a near-miss dependency tree', () => {+ // `npm ci` is skipped on a hit, so a restore-keys fallback would hand the+ // job a node_modules built from a DIFFERENT lockfile and run the suite+ // against it. Exact key or nothing — unlike the transform cache below,+ // where a near miss is revalidated rather than trusted.+ for (const [id, body] of installers) {+ expect(cacheEntry(body), id).not.toMatch(/restore-keys/);+ expect(body, id).toMatch(/key: vitest-server-[^\n]*\n {10}restore-keys:/);+ }+ });++ it('keys on everything that changes what a correct tree contains', () => {+ const inputs = [+ // Dependency identity. package.json rides along so that skipping `npm ci`+ // does not also skip its manifest-vs-lockfile agreement check.+ 'server/package-lock.json', 'server/package.json',+ // Whether install scripts ran at all, and which packages get rebuilt.+ 'server/.npmrc', 'scripts/trusted-rebuilds.js',+ ];+ for (const [id, body] of installers) {+ const entry = cacheEntry(body);+ for (const input of inputs) expect(entry, `${id}: ${input}`).toContain(`'${input}'`);+ // Compiled addons do not load across a different OS, arch, or ABI.+ expect(entry, id).toMatch(/runner\.os \}\}-\$\{\{ runner\.arch \}\}-node/);+ }+ });++ it('pins the key to the Node major the jobs actually install', () => {+ // The major, not the resolved patch: NODE_MODULE_VERSION is stable across+ // patch releases, so keying on the patch would discard a ~570 MB entry on+ // every Node 24.x release for no ABI benefit. The tradeoff is that the+ // literal has to be kept honest, which is what this asserts.+ for (const [id, body] of installers) {+ const pinned = body.match(/node-version: (?<major>\d+)\.x/);+ expect(pinned, id).not.toBeNull();+ expect(cacheEntry(body), id).toContain(`-node${pinned.groups.major}-`);+ }+ });++ it('does not pay for a CUDA execution provider no runner can use', () => {+ // onnxruntime-node's postinstall downloads the CUDA EP on linux-x64+ // whenever the .so is absent — several hundred MB, on two jobs, every run.+ // No hosted runner has an NVIDIA GPU, and the CPU binaries ship in the+ // tarball. This is the single largest cost the caching work removes.+ for (const [id, body] of installers) {+ expect(body, id).toMatch(/ONNXRUNTIME_NODE_INSTALL_CUDA: skip/);+ }+ });+});diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex df8fd2c6d3..55ab0e24b0 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -272,7 +272,6 @@ export function buildCiTestPlan(changedFiles, {windows: true,windowsMode: 'full',windowsFiles: [],- serverNative: true,};}@@ -303,7 +302,6 @@ export function buildCiTestPlan(changedFiles, {windows: false,windowsMode: 'skip',windowsFiles: [],- serverNative: false,};}@@ -387,16 +385,9 @@ export function buildCiTestPlan(changedFiles, {windows,windowsMode: windows ? 'related' : 'skip',windowsFiles: windows ? windowsContractTests(trackedSet) : [],- serverNative: needsServerNative(server),};}-function needsServerNative(server) {- if (server.mode === 'skip') return false;- if (server.mode !== 'files') return true;- return server.files.some((path) => !ALWAYS_RUN_TESTS.includes(path));-}-function fullPlan(changedFiles, reason) {return {full: true,@@ -411,7 +402,6 @@ function fullPlan(changedFiles, reason) {windows: true,windowsMode: 'full',windowsFiles: [],- serverNative: true,};}@@ -436,7 +426,6 @@ export function emitGitHubPlan(plan) {windows: plan.windows,windows_mode: plan.windowsMode,windows_files: JSON.stringify(plan.windowsFiles),- server_native: plan.serverNative,};Object.entries(outputs).forEach(([name, value]) => writeStepOutput(name, value));diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.jsindex a03da8040b..5c5e1f2306 100644--- a/scripts/ci-test-plan.test.js+++ b/scripts/ci-test-plan.test.js@@ -45,7 +45,6 @@ describe('CI test impact planner', () => {build: false,smoke: false,windows: false,- serverNative: false,});});@@ -327,7 +326,6 @@ describe('CI test impact planner', () => {build: true,smoke: true,windows: true,- serverNative: true,});});@@ -336,7 +334,6 @@ describe('CI test impact planner', () => {'server/services/sprites/atlas.js',], { trackedFiles: TRACKED });expect(sprites.windows).toBe(false);- expect(sprites.serverNative).toBe(true);const spawn = buildCiTestPlan(['server/lib/bufferedSpawn.js',diff --git a/scripts/trusted-rebuild-stamp.js b/scripts/trusted-rebuild-stamp.jsnew file mode 100644index 0000000000..f0bd2cadbd--- /dev/null+++ b/scripts/trusted-rebuild-stamp.js@@ -0,0 +1,106 @@+/**+ * Marks a node_modules tree as having been through the trusted rebuild, and+ * checks that mark later.+ *+ * Why a mark and not an inspection: CI caches `server/node_modules` between+ * jobs, and a tree is only safe to reuse if it was saved *after*+ * `scripts/trusted-rebuilds.js` ran — `server/.npmrc` pins+ * `ignore-scripts=true`, so npm alone leaves the allowlisted packages+ * un-built. But "was this rebuilt?" is not answerable by looking at the tree.+ * With today's versions the rebuild is close to a no-op: node-pty and sharp+ * ship prebuilt bindings inside their tarballs (there is no `build/` directory+ * even in a fully rebuilt tree), onnxruntime-node bundles its CPU binaries and+ * only fetches the CUDA execution provider, and protobufjs only regenerates a+ * bundle nothing requires. So `require()`-ing the packages proves nothing — it+ * succeeds on a never-rebuilt tree, which is exactly the false confidence this+ * module replaced.+ *+ * That is a property of the current dependency versions, not a guarantee. A+ * release that drops a prebuild for the runner's platform, or an install under+ * `npm_config_build_from_source` (which makes node-pty's install script *delete*+ * the prebuilds), puts the rebuild back on the critical path. An extrinsic mark+ * keeps the check honest across that change instead of quietly going vacuous+ * with it.+ *+ * The mark records what would invalidate the tree even at an unchanged cache+ * key: the allowlist it was built against, and the platform/ABI it was built+ * for. Any mismatch reads as "not rebuilt" and the caller reinstalls.+ *+ * node scripts/trusted-rebuild-stamp.js write server # after a rebuild+ * node scripts/trusted-rebuild-stamp.js check server # after a cache restore+ */+import { createHash } from 'crypto';+import { existsSync, readFileSync, writeFileSync } from 'fs';+import { join, resolve } from 'path';+import { fileURLToPath } from 'url';++import { TRUSTED_REBUILDS, discoverWorkspaces, workspaceDir } from './trusted-rebuilds.js';++export const STAMP_FILE = '.portos-trusted-rebuild.json';++const stampPath = (label) => join(workspaceDir(label), 'node_modules', STAMP_FILE);++/**+ * What the tree must match to count as rebuilt. The allowlist is hashed rather+ * than embedded so that regrouping or renaming a package invalidates the mark;+ * `modules` is NODE_MODULE_VERSION, which is what a compiled addon is actually+ * bound to.+ */+export function expectedStamp(label, { platform = process.platform, arch = process.arch, modules = process.versions.modules } = {}) {+ return {+ label,+ allowlist: createHash('sha256').update(JSON.stringify(TRUSTED_REBUILDS[label] ?? null)).digest('hex').slice(0, 16),+ platform,+ arch,+ modules: String(modules),+ };+}++/** Returns the mismatched field names — empty means the tree is usable. */+export function compareStamp(expected, found) {+ if (!found) return ['missing'];+ return Object.keys(expected).filter((key) => found[key] !== expected[key]);+}++/**+ * CLI body, returning an exit code instead of calling process.exit, so every+ * branch is assertable. Mirrors the shape of scripts/trusted-rebuilds.js.+ */+export function runCli(argv, { read = tryRead, write = writeFileSync, expected = expectedStamp } = {}) {+ const [action, label] = argv;+ const workspaces = discoverWorkspaces();+ if (!['write', 'check'].includes(action) || !workspaces.includes(label)) {+ console.error(`❌ usage: node scripts/trusted-rebuild-stamp.js <write|check> <${workspaces.join('|')}>`);+ return 1;+ }+ const stamp = expected(label);+ if (action === 'write') {+ write(stampPath(label), `${JSON.stringify(stamp, null, 2)}\n`);+ console.log(`🔖 ${label}: marked node_modules as trusted-rebuilt (${stamp.platform}-${stamp.arch}, abi ${stamp.modules})`);+ return 0;+ }+ const mismatched = compareStamp(stamp, read(stampPath(label)));+ if (mismatched.length) {+ console.error(`❌ ${label}: node_modules is not a trusted-rebuilt tree (${mismatched.join(', ')})`);+ console.error(' It was cached before the rebuild, or built for a different allowlist or ABI.');+ return 1;+ }+ console.log(`✅ ${label}: node_modules carries a matching trusted-rebuild mark`);+ return 0;+}++function tryRead(path) {+ if (!existsSync(path)) return null;+ const raw = readFileSync(path, 'utf8');+ try {+ return JSON.parse(raw);+ } catch {+ // A truncated restore is "not rebuilt", not a crash — the caller reinstalls.+ return null;+ }+}++const isMain = process.argv[1]+ && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url));++if (isMain) process.exit(runCli(process.argv.slice(2)));diff --git a/scripts/trusted-rebuild-stamp.test.js b/scripts/trusted-rebuild-stamp.test.jsnew file mode 100644index 0000000000..e0e9fa1755--- /dev/null+++ b/scripts/trusted-rebuild-stamp.test.js@@ -0,0 +1,81 @@+import { describe, expect, it, vi } from 'vitest';++import { TRUSTED_REBUILDS } from './trusted-rebuilds.js';+import { STAMP_FILE, compareStamp, expectedStamp, runCli } from './trusted-rebuild-stamp.js';++const linux = { platform: 'linux', arch: 'x64', modules: '137' };++describe('expectedStamp', () => {+ it('binds the mark to the allowlist, not just to the workspace name', () => {+ // Regrouping or renaming a package has to invalidate an existing mark: the+ // tree was built against a different set of rebuilds.+ const before = expectedStamp('server', linux);+ const original = TRUSTED_REBUILDS.server;+ try {+ TRUSTED_REBUILDS.server = [{ pkgs: ['node-pty'], fatal: true }];+ expect(expectedStamp('server', linux).allowlist).not.toBe(before.allowlist);+ } finally {+ TRUSTED_REBUILDS.server = original;+ }+ expect(expectedStamp('server', linux)).toEqual(before);+ });++ it('records the ABI a compiled addon is actually bound to', () => {+ // The cache key carries the Node *major*; NODE_MODULE_VERSION is the thing+ // a .node file will refuse to load against.+ expect(expectedStamp('server', linux).modules).toBe('137');+ expect(expectedStamp('server', { ...linux, modules: 999 }).modules).toBe('999');+ });+});++describe('compareStamp', () => {+ const expected = expectedStamp('server', linux);++ it('accepts a tree built for the same allowlist, platform, and ABI', () => {+ expect(compareStamp(expected, { ...expected })).toEqual([]);+ });++ it('treats an absent mark as not rebuilt', () => {+ // The case the old require()-based check could never catch: npm ci alone+ // leaves every allowlisted package importable, because they ship prebuilt+ // bindings in their tarballs.+ expect(compareStamp(expected, null)).toEqual(['missing']);+ });++ it('names every field that disagrees', () => {+ expect(compareStamp(expected, { ...expected, platform: 'win32', modules: '115' }))+ .toEqual(['platform', 'modules']);+ });+});++describe('trusted-rebuild-stamp CLI', () => {+ const stamp = expectedStamp('server', linux);+ const expected = () => stamp;++ it('writes the mark next to the tree it describes', () => {+ const write = vi.fn();+ expect(runCli(['write', 'server'], { write, expected })).toBe(0);+ const [path, body] = write.mock.calls[0];+ // Split on either separator: this file runs in the Windows job too,+ // where join() yields backslashes.+ expect(path.split(/[\\/]/).slice(-3)).toEqual(['server', 'node_modules', STAMP_FILE]);+ expect(JSON.parse(body)).toEqual(stamp);+ });++ it('passes a matching mark and fails a mismatched or missing one', () => {+ expect(runCli(['check', 'server'], { read: () => stamp, expected })).toBe(0);+ expect(runCli(['check', 'server'], { read: () => ({ ...stamp, arch: 'arm64' }), expected })).toBe(1);+ expect(runCli(['check', 'server'], { read: () => null, expected })).toBe(1);+ });++ it('rejects a bad action or workspace before touching the tree', () => {+ // Same trap trusted-rebuilds.js guards: a typo must not fall through to a+ // green no-op, which is the false confidence this whole check exists to+ // remove.+ const write = vi.fn();+ expect(runCli(['check', 'sever'], { expected, write })).toBe(1);+ expect(runCli(['stamp', 'server'], { expected, write })).toBe(1);+ expect(runCli(['write'], { expected, write })).toBe(1);+ expect(write).not.toHaveBeenCalled();+ });+});