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
refactor: apply /simplify findings from the depfree pass
Adam Eivy674646bf124a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex bf59876d13..99bfea681d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -12,9 +12,9 @@- **The root `pm2` dependency moved out of the dev-only bucket, because `npm start` launches the production process with it.** The root `start`, `pm2:*` and `dev:stop` scripts all invoke `./node_modules/pm2/bin/pm2`, so an install run with `--omit=dev` (or `NODE_ENV=production`) would have left every one of them with no binary to run. Nothing in the repo installs that way today and `server/package.json` already declares `pm2` as a normal dependency, so this was a latent footgun rather than a live break — but it would have cost someone an afternoon the first time a slimmed Docker or CI install path appeared. The lockfile change is limited to the bucket rename and dropping `"dev": true` from pm2 and its transitives; no versions moved. `scripts/root-runtime-deps.test.js` now derives the rule from the manifest instead of hardcoding pm2 — every package a root script reaches into via `./node_modules/<pkg>/…` has to be a real dependency — so the next root script wired to a dev-only binary fails the suite rather than waiting for a production install path to expose it.-- **Replaced ESLint with Biome in the client, dropping 108 net packages including the `keyv` chain named in the August 2026 npm compromise.** `keyv`, `flat-cache`, and `file-entry-cache` were hit by the Shai-Hulud supply-chain attack. PortOS was never exposed — it held `[email protected]` / `[email protected]` / `[email protected]` while the malicious releases were the *next major* in each line, unreachable from the caret ranges in the lockfile, with no install hook anywhere in the tree (npm has since unpublished all three). They were not direct dependencies either: they arrived as a single chain under one root, `eslint → file-entry-cache → flat-cache → keyv`, dev-only and client-only. Since `[email protected]` hard-requires `file-entry-cache` and no release drops it, the only way to shed the chain was to stop using ESLint — so this is a maintenance win, not a security fix. An `overrides` pin would have been a no-op, because every range was already at the top of its published major.+- **Replaced ESLint with Biome in the client, dropping 110 net packages including the `keyv` chain named in the August 2026 npm compromise.** `keyv`, `flat-cache`, and `file-entry-cache` were hit by the Shai-Hulud supply-chain attack. PortOS was never exposed — it held `[email protected]` / `[email protected]` / `[email protected]` while the malicious releases were the *next major* in each line, unreachable from the caret ranges in the lockfile, with no install hook anywhere in the tree (npm has since unpublished all three). They were not direct dependencies either: they arrived as a single chain under one root, `eslint → file-entry-cache → flat-cache → keyv`, dev-only and client-only. Since `[email protected]` hard-requires `file-entry-cache` and no release drops it, the only way to shed the chain was to stop using ESLint — so this is a maintenance win, not a security fix. An `overrides` pin would have been a no-op, because every range was already at the top of its published major.- `@biomejs/[email protected]` replaces the stack: a native binary with no regular dependencies and 8 platform optionals, of which one installs. The client lockfile goes 446 → 338 packages. Parity was proven with fixtures rather than inferred from a clean run — a linter with no rules also reports zero problems — and `npm run lint` still covers the same 1859 files with 0 problems. The swap was cheap largely because `exhaustive-deps` was already deliberately disabled, which is the rule that usually makes linter migrations painful.+ `@biomejs/[email protected]` replaces the stack: a native binary with no regular dependencies and 8 platform optionals, of which one installs. The client lockfile goes 447 → 337 packages. That count includes `typescript`, which the migration orphaned — it was a client devDependency purely to satisfy `@eslint-react/eslint-plugin`'s peer dep, and with the client holding no `tsconfig`, no `.ts`/`.tsx` sources, no `tsc` script, and nothing peer-depending on it, it came out too (retiring a Dependabot ignore rule and issue #3351 with it). Parity was proven with fixtures rather than inferred from a clean run — a linter with no rules also reports zero problems — and `npm run lint` still covers the same 1859 files with 0 problems. The swap was cheap largely because `exhaustive-deps` was already deliberately disabled, which is the rule that usually makes linter migrations painful.The `crypto.randomUUID` ban is preserved as a GritQL plugin, and it matters: that call is undefined on insecure origins, and PortOS is routinely reached over plain HTTP via Tailscale. It matches on the syntax-tree node kind rather than code snippets, so it still catches `crypto.`, `globalThis.crypto.`, `window.`, `self.`, optional chaining, bare `typeof` references, and assignment targets — while continuing to ignore `crypto['randomUUID']` exactly as the old rule did. Its exemptions for `src/lib/uuid.js` and test files are written as negated globs because a Biome override's `plugins` list is additive, so an empty list does not disable an inherited plugin.diff --git a/.github/dependabot.yml b/.github/dependabot.ymlindex 6009d85bd1..f3a543b15a 100644--- a/.github/dependabot.yml+++ b/.github/dependabot.yml@@ -18,16 +18,6 @@ updates:schedule:interval: weeklyopen-pull-requests-limit: 10- ignore:- # The client is plain JS/JSX — `typescript` is here only to satisfy the- # peer dep of @eslint-react/eslint-plugin, which pulls typescript-eslint- # and ts-api-utils. Neither supports TypeScript 7 yet- # (@typescript-eslint/[email protected] peers `>=4.8.4 <6.1.0`,- # [email protected] peers `<7`), and installing it crashes eslint- # with `Cannot read properties of undefined (reading 'Intrinsic')`.- # Drop this ignore once typescript-eslint ships TS7 support (see #3351).- - dependency-name: typescript- versions: ['>=7.0.0']- package-ecosystem: github-actionsdirectory: /schedule:diff --git a/PLAN.md b/PLAN.mdindex 4650c70a7b..e049cedd2f 100644--- a/PLAN.md+++ b/PLAN.md@@ -301,13 +301,17 @@ is not reliably announced.`MoodBoardDetail.jsx`, `OpenClaw.jsx`, `LoraDatasetDetail.jsx`, `Browser.jsx`.Prefer wrapping in `FormField` (visible label + `htmlFor`/`id` pairing) over an`aria-label` when the surface has room for a visible label.-- [ ] **Consider `eslint-plugin-jsx-a11y` in `client/eslint.config.js`.** It would- enforce this class automatically instead of relying on periodic audits. Skipped in- this pass because enabling it surfaces hundreds of findings at once and would fail- CI until the backlog above is drained — sequence it after the sweep, and start with- only the rules the repo already honors (`jsx-a11y/alt-text`,- `jsx-a11y/aria-props`, `jsx-a11y/role-has-required-aria-props`,- `jsx-a11y/label-has-associated-control`) rather than the full `recommended` set.+- [ ] **Enable Biome's `a11y` rules in `client/biome.jsonc`.** It would enforce this+ class automatically instead of relying on periodic audits. Note this got *cheaper*+ when the client moved from ESLint to Biome: the rules ship in Biome's `a11y` group,+ so this no longer needs a new dependency (`eslint-plugin-jsx-a11y`) at all — it is+ now purely a config change. Still skipped in this pass because enabling the group+ surfaces hundreds of findings at once and would fail CI until the backlog above is+ drained — sequence it after the sweep, and start with only the rules the repo+ already honors (`a11y/useAltText`, `a11y/useValidAriaProps`,+ `a11y/useAriaPropsForRole`, `a11y/noLabelWithoutControl`) rather than the whole+ group. The config already uses an explicit per-rule list, so adding a handful is+ the established shape.### Factor the "bump a seeded Claude provider tier" migration skeleton into `_lib.js`diff --git a/browser/.npmrc b/browser/.npmrcnew file mode 100644index 0000000000..dab1a7db8c--- /dev/null+++ b/browser/.npmrc@@ -0,0 +1,8 @@+# Block install scripts by default to reduce supply-chain attack surface.+# See client/.npmrc for why this cannot be inherited from the repo-root .npmrc:+# npm reads the project config from the local prefix and never walks upward.+#+# This workspace has no dependencies today, so the setting is purely pre-emptive —+# it means the guard is already in place if any are ever added, rather than the+# addition silently arriving with an install-time execution slot.+ignore-scripts=truediff --git a/client/biome.jsonc b/client/biome.jsoncindex b752efae47..479473eacb 100644--- a/client/biome.jsonc+++ b/client/biome.jsonc@@ -1,7 +1,6 @@{"$schema": "./node_modules/@biomejs/biome/configuration_schema.json","root": true,- "vcs": { "enabled": false },"files": {"includes": ["src/**/*.js", "src/**/*.jsx"]},diff --git a/client/package-lock.json b/client/package-lock.jsonindex 903d9e0c55..8e4f031191 100644--- a/client/package-lock.json+++ b/client/package-lock.json@@ -33,7 +33,6 @@"jsdom": "30.0.1","rollup-plugin-visualizer": "7.0.1","tailwindcss": "4.3.3",- "typescript": "6.0.3","vite": "8.2.0","vitest": "4.1.10"}@@ -4039,20 +4038,6 @@}}},- "node_modules/typescript": {- "version": "6.0.3",- "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",- "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",- "dev": true,- "license": "Apache-2.0",- "bin": {- "tsc": "bin/tsc",- "tsserver": "bin/tsserver"- },- "engines": {- "node": ">=14.17"- }- },"node_modules/undici": {"version": "8.9.0","resolved": "https://registry.npmjs.org/undici/-/undici-8.9.0.tgz",diff --git a/client/package.json b/client/package.jsonindex db2be5c647..0c05f1afbd 100644--- a/client/package.json+++ b/client/package.json@@ -39,7 +39,6 @@"jsdom": "30.0.1","rollup-plugin-visualizer": "7.0.1","tailwindcss": "4.3.3",- "typescript": "6.0.3","vite": "8.2.0","vitest": "4.1.10"},diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsxindex ab84067329..e2f3037cc2 100644--- a/client/src/components/cos/TaskAddForm.jsx+++ b/client/src/components/cos/TaskAddForm.jsx@@ -190,8 +190,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = faif (settings.simplify !== undefined) setSimplify(settings.simplify);}descriptionRef.current?.focus();- // biome-ignore lint/correctness/useHookAtTopLevel: `api.useCosTaskTemplate` is an HTTP call (POST .../use), not a React hook — Biome matches on the `use` prefix alone.- await api.useCosTaskTemplate(template.id).catch(() => {});+ await api.applyCosTaskTemplate(template.id).catch(() => {});toast.success(`Template applied: ${template.name}`);}, [newTask.app]);diff --git a/client/src/components/cos/TaskAddForm.test.jsx b/client/src/components/cos/TaskAddForm.test.jsxindex 184ccbdeb9..dd07020f01 100644--- a/client/src/components/cos/TaskAddForm.test.jsx+++ b/client/src/components/cos/TaskAddForm.test.jsx@@ -9,7 +9,7 @@ const api = vi.hoisted(() => ({// Back the reviewer table's Model column (useReviewerModelOptions).getLocalLlmStatus: vi.fn(),getProviders: vi.fn(),- useCosTaskTemplate: vi.fn()+ applyCosTaskTemplate: vi.fn()}));vi.mock('../../services/api', () => api);@@ -21,7 +21,7 @@ describe('TaskAddForm responsive layout', () => {api.getCodeReviewDefaults.mockResolvedValue(null);api.getLocalLlmStatus.mockResolvedValue({ ollama: { models: [] }, lmstudio: { models: [] } });api.getProviders.mockResolvedValue({ providers: [] });- api.useCosTaskTemplate.mockResolvedValue({ success: true });+ api.applyCosTaskTemplate.mockResolvedValue({ success: true });});it('keeps PR completion controls full-width on mobile', async () => {@@ -72,7 +72,7 @@ describe('TaskAddForm quick templates', () => {api.getCodeReviewDefaults.mockResolvedValue(null);api.getLocalLlmStatus.mockResolvedValue({ ollama: { models: [] }, lmstudio: { models: [] } });api.getProviders.mockResolvedValue({ providers: [] });- api.useCosTaskTemplate.mockResolvedValue({ success: true });+ api.applyCosTaskTemplate.mockResolvedValue({ success: true });});it('applies a slashdo template settings block to the run-shape toggles', async () => {@@ -98,7 +98,7 @@ describe('TaskAddForm quick templates', () => {await waitFor(() => expect(worktreeToggle()).not.toBeChecked());expect(screen.getByPlaceholderText('Task description *')).toHaveValue('Investigate and file an issue for: ');- expect(api.useCosTaskTemplate).toHaveBeenCalledWith('builtin-do-plan-task');+ expect(api.applyCosTaskTemplate).toHaveBeenCalledWith('builtin-do-plan-task');});it('leaves the toggles as-is for a template with no settings block', async () => {diff --git a/client/src/components/pipeline/manuscript/constants.js b/client/src/components/pipeline/manuscript/constants.jsindex a8ab14160b..f1a0efeaa5 100644--- a/client/src/components/pipeline/manuscript/constants.js+++ b/client/src/components/pipeline/manuscript/constants.js@@ -75,8 +75,7 @@ export const SUBTYPE_LABEL = {// an inherited Object.prototype member — a truthy non-string that the `|| subtype`// fallback wouldn't catch and that React then throws on as a non-element child.export const subtypeLabel = (subtype) =>- // biome-ignore lint/suspicious/noPrototypeBuiltins: `Object.prototype.hasOwnProperty.call(obj, k)` IS the safe form — Biome flags it anyway, unlike ESLint's no-prototype-builtins.- (Object.prototype.hasOwnProperty.call(SUBTYPE_LABEL, subtype) ? SUBTYPE_LABEL[subtype] : null) || subtype;+ (Object.hasOwn(SUBTYPE_LABEL, subtype) ? SUBTYPE_LABEL[subtype] : null) || subtype;// Approximate a textarea's height to its content so the manuscript reads as one// continuous scroll (lets jump-to-anchor scroll the page, not an inner box).diff --git a/client/src/hooks/useCitySettings.js b/client/src/hooks/useCitySettings.jsindex 3564cb25a7..019d6f7efd 100644--- a/client/src/hooks/useCitySettings.js+++ b/client/src/hooks/useCitySettings.js@@ -70,8 +70,7 @@ const loadSettings = () => {// Such installs keep their chosen fixed preset — Manual — rather than being// silently opted into adaptation. Presence of the key (even 'auto') is honored;// this is the "absent vs. present" distinction, so a stored 'auto' survives.- // biome-ignore lint/suspicious/noPrototypeBuiltins: `Object.prototype.hasOwnProperty.call(obj, k)` IS the safe form — Biome flags it anyway, unlike ESLint's no-prototype-builtins.- if (!Object.prototype.hasOwnProperty.call(parsed, 'qualityMode')) {+ if (!Object.hasOwn(parsed, 'qualityMode')) {merged.qualityMode = 'manual';}return merged;diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex 23051e72d9..260207b5e9 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -177,7 +177,7 @@ export const createCosTemplateFromTask = (task, templateName) => request('/cos/tmethod: 'POST',body: JSON.stringify({ task, templateName })});-export const useCosTaskTemplate = (id) => request(`/cos/templates/${id}/use`, { method: 'POST' });+export const applyCosTaskTemplate = (id) => request(`/cos/templates/${id}/use`, { method: 'POST' });export const updateCosTaskTemplate = (id, data) => request(`/cos/templates/${id}`, {method: 'PUT',body: JSON.stringify(data)diff --git a/docs/DEPS.md b/docs/DEPS.mdindex 8b292b3a90..f429b13a35 100644--- a/docs/DEPS.md+++ b/docs/DEPS.md@@ -61,6 +61,7 @@ Before removing a Tier 3 candidate, run a transitive-dep check (`npm ls <pkg>`).| `@eslint/js` | — | REMOVED | linting | Removed with `eslint` || `@eslint-react/eslint-plugin` | — | REMOVED | linting | Removed with `eslint`; its 8 enabled rules map to Biome rules + one GritQL plugin || `eslint-plugin-react-hooks` | — | REMOVED | linting | Removed with `eslint`; `rules-of-hooks` → Biome `useHookAtTopLevel` |+| `typescript` | — | REMOVED | (none) | 2026-08-04. Was only here for `@eslint-react`'s peer dep; client has no tsconfig / `.ts` sources / `tsc` script || `@tailwindcss/postcss` | 1 | KEEP | styling | || `tailwindcss` | 1 | KEEP | styling | || `@vitejs/plugin-react` | 1 | KEEP | build | |@@ -89,7 +90,8 @@ Before removing a Tier 3 candidate, run a transitive-dep check (`npm ls <pkg>`).- **Trigger**: the August 2026 Shai-Hulud npm compromise hit `keyv`, `flat-cache`, and `file-entry-cache` (among ~430 packages). PortOS was **never exposed** — it held `[email protected]`, `[email protected]`, `[email protected]`, while the malicious releases were the *next major* in each line (`6.0.0` / `6.1.24` / `11.1.6`), unreachable from the `^4` / `^4.0.0` / `^8.0.0` ranges. npm has since unpublished all three, and no install hook ever existed in the tree.- **Why they were here at all**: not direct dependencies. A single chain under one root — `eslint → file-entry-cache → flat-cache → keyv` — client workspace, devDependencies only. `[email protected]` (latest) hard-requires `file-entry-cache@^8.0.0`; no eslint release drops it. So the only way to shed them was to stop using eslint.- **Semver headroom was already zero**: the highest published `[email protected]` *is* `8.0.0`, `[email protected]` *is* `4.0.1`, `[email protected]` *is* `4.5.4`. An `overrides` pin would have been a no-op — there was nowhere to float. Removal was therefore a **maintenance** win, not a security fix.-- **Resolution**: replaced eslint with `@biomejs/[email protected]`. Client lockfile **446 → 338 packages** (−108; 118 eslint packages out, 9 Biome entries in, only 1 platform binary installed). All four eslint-chain packages now report 0 occurrences in `client/package-lock.json`.+- **Resolution**: replaced eslint with `@biomejs/[email protected]`. Client lockfile **447 → 337 packages** (−110; the eslint tree out, 9 Biome entries in, only 1 platform binary installed). All four eslint-chain packages now report 0 occurrences in `client/package-lock.json`.+- **`typescript` went with it.** It was a client devDependency solely to satisfy `@eslint-react/eslint-plugin`'s peer dep — the client has no `tsconfig`, zero `.ts`/`.tsx` sources, no `tsc` script, and nothing peer-depends on it. Removing it also retires the `.github/dependabot.yml` ignore rule that pinned it below TS7 (and issue #3351, which tracked waiting on typescript-eslint for TS7 support — now moot).- **Rule parity was proven with fixtures, not inferred from a clean run** — a linter with no rules also reports "0 problems". Every rule the old config enforced fires under Biome; `npm run lint` covers the same **1859 files** with 0 problems. `exhaustive-deps` was already `off` (documented, deliberate), which is what made this a half-day swap instead of a risky one.- **The `crypto.randomUUID` ban survives as a GritQL plugin** (`client/lint-no-random-uuid.grit`). This rule is load-bearing: `crypto.randomUUID` is undefined on insecure origins, and PortOS is routinely reached over plain HTTP via Tailscale. It matches on the CST node kind rather than code snippets, so it catches `crypto.`, `globalThis.crypto.`, `window.`, `self.`, optional chaining, bare `typeof` references, and assignment targets — and, matching the old ESLint rule exactly, *not* `crypto['randomUUID']`. Exemptions for `src/lib/uuid.js` and `src/**/*.test.{js,jsx}` are expressed as **negated globs**, because a Biome override's `plugins` list is *additive*: `plugins: []` does NOT disable an inherited plugin. Do not "simplify" that back.- **Deliberately scoped**: Biome's formatter and `assist` are disabled (enabling them would rewrite all 1859 files in one unreviewable diff), and the rule set uses `preset: "none"` with an explicit list rather than Biome's broader `recommended` — keeping this a tooling swap, not a smuggled lint-policy change. Adopting more Biome rules is a separate decision.diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex 65250a01b9..662ead3ecb 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -17,7 +17,10 @@ const FULL_TRIGGER_RULES = [{ re: /^(?:server|client)\/vitest\.config(?:\.db)?\.js$/, reason: 'test runner configuration changed' },{ re: /^server\/vitest\.setup\.js$/, reason: 'server test setup changed' },{ re: /^client\/src\/test\/setup\.js$/, reason: 'client test setup changed' },- { re: /^client\/eslint\.config\.js$/, reason: 'lint configuration changed' },+ // Biome config + its GritQL plugins (the former client/eslint.config.js). The+ // .grit files carry real enforced rules — notably the crypto.randomUUID ban —+ // so a change there is as load-bearing as a change to the config itself.+ { re: /^client\/(?:biome\.jsonc|[^/]+\.grit)$/, reason: 'lint configuration changed' },{ re: /^client\/vite\.config\.js$/, reason: 'client build configuration changed' },{ re: /^server\/index\.js$/, reason: 'server composition root changed' },{ re: /^client\/src\/App\.jsx$/, reason: 'client composition root changed' },diff --git a/scripts/ensure-deps.js b/scripts/ensure-deps.jsindex d44a0cd16b..fb8871a7c4 100644--- a/scripts/ensure-deps.js+++ b/scripts/ensure-deps.js@@ -8,10 +8,9 @@ import { execFileSync } from 'child_process';import { createHash } from 'crypto';import { join, dirname } from 'path';import { fileURLToPath } from 'url';-import { rebuildTrusted } from './trusted-rebuilds.js';+import { rebuildTrusted, NPM } from './trusted-rebuilds.js';const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');-const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';// Persisted package.json hashes (per workspace) from the last successful install.// A changed hash means the manifest moved since we last resolved the tree, so andiff --git a/scripts/trusted-rebuilds.js b/scripts/trusted-rebuilds.jsindex 3256d658e3..fcc894ffbd 100644--- a/scripts/trusted-rebuilds.js+++ b/scripts/trusted-rebuilds.js@@ -16,11 +16,41 @@* node scripts/trusted-rebuilds.js server*/import { execFileSync } from 'child_process';-import { join, dirname } from 'path';+import { existsSync, readdirSync } from 'fs';+import { join, dirname, resolve } from 'path';import { fileURLToPath } from 'url';const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');-const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';++/** npm's Windows shim. Shared so callers don't re-derive it. */+export const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';++/**+ * Every directory npm can install into with that directory as the local prefix:+ * the repo root plus each top-level directory carrying its own package.json.+ * Discovered rather than hand-listed — a hardcoded roster is the same drift this+ * module exists to eliminate, one level up: add a 5th workspace, forget to add it+ * to the list, and its `ignore-scripts` guard is silently absent while CI stays+ * green. Nested manifests (`server/cos-runner`) and the vendored `lib/slashdo`+ * submodule are deliberately excluded — nobody installs with those as the prefix,+ * and the submodule is not ours to configure.+ *+ * Returns labels; pair with `workspaceDir()` for the path. Root sorts first, the+ * rest alphabetically, so callers get a stable order.+ */+export function discoverWorkspaces() {+ const nested = readdirSync(ROOT, { withFileTypes: true })+ .filter((entry) => entry.isDirectory() && entry.name !== 'node_modules' && !entry.name.startsWith('.'))+ .map((entry) => entry.name)+ .filter((name) => existsSync(join(ROOT, name, 'package.json')))+ .sort();+ return ['root', ...nested];+}++/** Absolute path for a workspace label from `discoverWorkspaces()`. */+export function workspaceDir(label) {+ return label === 'root' ? ROOT : join(ROOT, label);+}/*** `fatal: true` means a failed rebuild fails the install — the package is@@ -32,15 +62,18 @@ const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';*/export const TRUSTED_REBUILDS = {server: [- // Builds the native PTY addon. The shell/TUI features hard-require it.- { pkgs: ['node-pty'], fatal: true },- // Retained as insurance: sharp ships prebuilt bindings via- // optionalDependencies today (no lifecycle hook), so this is currently a- // no-op — but it is runtime-critical if it ever regains one.- { pkgs: ['sharp'], fatal: true },- // Transitive, behind optional local-inference features. Its postinstall- // fetches platform binaries; absent them the feature is unavailable, not- // fatal. protobufjs's postinstall only generates a minimal build.+ // node-pty builds the native PTY addon and the shell/TUI features hard-require+ // it. sharp rides along in the same call: it ships prebuilt bindings via+ // optionalDependencies today so its rebuild is currently a no-op, but it is+ // equally runtime-critical if it ever regains a lifecycle hook. Grouped+ // because they share `fatal` — a group exists to give *different* failure+ // semantics, not to hang a different comment on each package, and every extra+ // group costs another npm spawn (~180ms) for no behavioral gain.+ { pkgs: ['node-pty', 'sharp'], fatal: true },+ // Transitive, behind optional local-inference features. onnxruntime-node's+ // postinstall fetches platform binaries; absent them the feature is+ // unavailable, not fatal. protobufjs's postinstall only generates a minimal+ // build.{ pkgs: ['onnxruntime-node', 'protobufjs'], fatal: false }]};@@ -65,17 +98,23 @@ export function rebuildTrusted(dir, label) {}// CLI entry: `node scripts/trusted-rebuilds.js <label> [dir]`-if (process.argv[1] && import.meta.url === `file://${process.argv[1]}`) {+function main() {const label = process.argv[2];if (!label) {console.error(`❌ usage: node scripts/trusted-rebuilds.js <${Object.keys(TRUSTED_REBUILDS).join('|')}>`);process.exit(1);}- const dir = process.argv[3] ?? (label === 'root' ? ROOT : join(ROOT, label));if (!TRUSTED_REBUILDS[label]) {console.log(`✅ no trusted rebuilds needed for ${label}`);process.exit(0);}console.log(`🔨 Rebuilding trusted install-script packages for ${label}`);- process.exit(rebuildTrusted(dir, label) ? 0 : 1);+ process.exit(rebuildTrusted(process.argv[3] ?? workspaceDir(label), label) ? 0 : 1);}++// Matches the entry-guard idiom in scripts/run-ci-lint.js — `resolve()` on both+// sides so a relative `node scripts/…` invocation still matches.+const isMain = process.argv[1]+ && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url));++if (isMain) main();diff --git a/scripts/trusted-rebuilds.test.js b/scripts/trusted-rebuilds.test.jsindex 47cbc4e339..c83280a46e 100644--- a/scripts/trusted-rebuilds.test.js+++ b/scripts/trusted-rebuilds.test.js@@ -1,68 +1,82 @@import { describe, it, expect } from 'vitest';import { readFileSync, existsSync, readdirSync } from 'fs';-import { join, dirname } from 'path';-import { fileURLToPath } from 'url';+import { join } from 'path';-import { TRUSTED_REBUILDS } from './trusted-rebuilds.js';+import { TRUSTED_REBUILDS, discoverWorkspaces, workspaceDir } from './trusted-rebuilds.js';-const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');--// Every workspace that npm can install into with that workspace as the *local-// prefix*. npm resolves the project .npmrc from the local prefix and never walks-// up the tree, so each of these needs its own file — the repo-root .npmrc does-// NOT cover `cd client && npm install` or `npm ci --prefix client` (what CI-// runs). A missing file silently re-grants every dependency in that workspace an-// install-time code-execution slot, which is exactly the hole a preinstall-hook-// worm (the Aug 2026 keyv/cacheable compromise) walks through.-const WORKSPACES = ['.', 'client', 'server', 'autofixer'];+// Discovered, not hand-listed: a hardcoded roster here would silently miss a+// workspace added later, leaving it with no `ignore-scripts` guard while this+// suite stayed green — the same drift the shared allowlist exists to prevent.+const WORKSPACES = discoverWorkspaces();const LIFECYCLE_HOOKS = ['preinstall', 'install', 'postinstall'];-/** Packages in a workspace's installed tree that declare a lifecycle install hook. */-function packagesWithInstallHooks(workspace) {- const modulesDir = join(ROOT, workspace, 'node_modules');+/**+ * Packages in a workspace's installed tree that declare a lifecycle install hook.+ * Returns null when the workspace has no node_modules (e.g. the client tree in+ * the server CI job), which is a skip rather than a pass.+ *+ * Only two levels are ever walked — top-level `node_modules/*` and one level into+ * `node_modules/@scope/*` — because npm scopes do not nest.+ */+function packagesWithInstallHooks(label) {+ const modulesDir = join(workspaceDir(label), 'node_modules');if (!existsSync(modulesDir)) return null;- const found = new Set();- const scanDir = (dir) => {- let entries;++ const dirNames = (dir) => {try {- entries = readdirSync(dir, { withFileTypes: true });+ return readdirSync(dir, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .map((entry) => entry.name);} catch {- return;- }- for (const entry of entries) {- if (!entry.isDirectory()) continue;- // Recurse one level into scopes (@scope/pkg) only.- if (entry.name.startsWith('@')) {- scanDir(join(dir, entry.name));- continue;- }- const manifest = join(dir, entry.name, 'package.json');- if (!existsSync(manifest)) continue;- let pkg;- try {- pkg = JSON.parse(readFileSync(manifest, 'utf8'));- } catch {- continue;- }- if (LIFECYCLE_HOOKS.some((hook) => pkg?.scripts?.[hook])) {- found.add(pkg.name ?? entry.name);- }+ return [];}};- scanDir(modulesDir);++ const packageDirs = dirNames(modulesDir).flatMap((name) => (+ name.startsWith('@')+ ? dirNames(join(modulesDir, name)).map((scoped) => join(modulesDir, name, scoped))+ : [join(modulesDir, name)]+ ));++ const found = new Set();+ for (const packageDir of packageDirs) {+ const manifest = join(packageDir, 'package.json');+ if (!existsSync(manifest)) continue;+ let pkg;+ try {+ pkg = JSON.parse(readFileSync(manifest, 'utf8'));+ } catch {+ continue;+ }+ if (LIFECYCLE_HOOKS.some((hook) => pkg?.scripts?.[hook])) found.add(pkg.name);+ }return found;}describe('ignore-scripts guard', () => {- it.each(WORKSPACES)('%s/.npmrc pins ignore-scripts=true', (workspace) => {- const npmrc = join(ROOT, workspace, '.npmrc');- expect(existsSync(npmrc), `${workspace}/.npmrc is missing — npm does not inherit the root .npmrc for this workspace's install path`).toBe(true);+ it('discovers every installable workspace', () => {+ // Sanity-check the discovery itself: if it silently returned only the root,+ // every per-workspace assertion below would vacuously pass.+ expect(WORKSPACES).toContain('root');+ expect(WORKSPACES).toContain('client');+ expect(WORKSPACES).toContain('server');+ expect(WORKSPACES.length).toBeGreaterThanOrEqual(4);+ });++ // npm resolves the project .npmrc from the *local prefix* and never walks up the+ // tree, so the repo-root file does NOT cover `cd client && npm install` or+ // `npm ci --prefix client` (what CI runs). A workspace missing this file silently+ // re-grants every dependency in it an install-time code-execution slot — the+ // vector the Aug 2026 keyv/cacheable worm used via a preinstall hook.+ it.each(WORKSPACES)('%s/.npmrc pins ignore-scripts=true', (label) => {+ const npmrc = join(workspaceDir(label), '.npmrc');+ expect(existsSync(npmrc), `${label}/.npmrc is missing — npm does not inherit the root .npmrc for this workspace's install path`).toBe(true);const lines = readFileSync(npmrc, 'utf8').split('\n').map((line) => line.trim()).filter((line) => line && !line.startsWith('#'));- expect(lines, `${workspace}/.npmrc must set ignore-scripts=true`).toContain('ignore-scripts=true');+ expect(lines, `${label}/.npmrc must set ignore-scripts=true`).toContain('ignore-scripts=true');});});@@ -79,26 +93,25 @@ describe('trusted rebuild allowlist', () => {}});- // The point of the allowlist is that ignore-scripts=true blocks EVERY install- // hook, so any package that legitimately needs one must be named explicitly.- // If a new dependency shows up with a postinstall and nobody decides about it,- // it is silently left unbuilt — which surfaces later as a confusing runtime- // crash on a missing native binding. Fail here instead, at the point the- // dependency is added, and force the decision: add it to the allowlist, or- // confirm its hook is genuinely unnecessary and add it to the ignore list.- const DELIBERATELY_UNBUILT = {- // No install hook is needed for these to work; their scripts are optional- // niceties (codegen / telemetry / prebuild shortcuts).- server: []- };-- it.each(WORKSPACES)('%s: every installed package with an install hook is accounted for', (workspace) => {- const hooked = packagesWithInstallHooks(workspace);- if (hooked === null) {- // node_modules absent (e.g. the client workspace in the server CI job).- return;+ it('groups packages by distinct failure semantics, not one group per package', () => {+ // Each group is another npm spawn, so a group only earns its cost by carrying+ // a different `fatal` value than its neighbours.+ for (const [label, groups] of Object.entries(TRUSTED_REBUILDS)) {+ const fatalValues = groups.map((group) => group.fatal);+ expect(new Set(fatalValues).size, `${label}: two groups share the same \`fatal\` value — merge them into one npm rebuild call`).toBe(groups.length);}- const label = workspace === '.' ? 'root' : workspace;+ });++ // ignore-scripts=true blocks EVERY install hook, so any package that legitimately+ // needs one must be named explicitly. If a new dependency arrives with a+ // postinstall and nobody decides about it, it is silently left unbuilt — which+ // surfaces much later as a confusing runtime crash on a missing native binding.+ // Fail here instead, when the dependency lands, and force the decision.+ const DELIBERATELY_UNBUILT = {};++ it.each(WORKSPACES)('%s: every installed package with an install hook is accounted for', (label) => {+ const hooked = packagesWithInstallHooks(label);+ if (hooked === null) return; // node_modules absent in this jobconst allowed = new Set([...(TRUSTED_REBUILDS[label] ?? []).flatMap((group) => group.pkgs),...(DELIBERATELY_UNBUILT[label] ?? [])@@ -106,7 +119,7 @@ describe('trusted rebuild allowlist', () => {const unaccounted = [...hooked].filter((name) => !allowed.has(name));expect(unaccounted,- `${workspace}: these packages declare an install hook that ignore-scripts=true blocks, but are not in the allowlist in scripts/trusted-rebuilds.js. Either add them (if the build is needed) or list them under DELIBERATELY_UNBUILT: ${unaccounted.join(', ')}`+ `${label}: these packages declare an install hook that ignore-scripts=true blocks, but are not in the allowlist in scripts/trusted-rebuilds.js. Either add them (if the build is needed) or list them under DELIBERATELY_UNBUILT: ${unaccounted.join(', ')}`).toEqual([]);});});